uploadAudioFile method

Future<UploadResult> uploadAudioFile(
  1. File file
)

Uploads an audio file to Gladia server

file - audio file to upload Returns UploadResult with URL and file metadata

Implementation

Future<UploadResult> uploadAudioFile(File file) async {
  try {
    // Create FormData to send the file
    final String fileName = file.path.split('/').last;
    final String extension = fileName.split('.').last.toLowerCase();

    // Determine MIME type based on extension
    String mimeType = 'audio/mpeg'; // Default for mp3
    if (extension == 'wav') {
      mimeType = 'audio/wav';
    } else if (extension == 'ogg') {
      mimeType = 'audio/ogg';
    } else if (extension == 'flac') {
      mimeType = 'audio/flac';
    } else if (extension == 'm4a') {
      mimeType = 'audio/m4a';
    }

    final formData = FormData.fromMap({
      'audio': await MultipartFile.fromFile(
        file.path,
        filename: fileName,
        contentType: MediaType.parse(mimeType),
      ),
    });

    // Set temporary headers for multipart/form-data request
    final originalHeaders = Map<String, dynamic>.from(_dio.options.headers);
    _dio.options.headers = {
      'x-gladia-key': apiKey,
      'Content-Type': 'multipart/form-data',
    };

    // Make request to upload the file
    final response = await _dio.post(
      'v2/upload',
      data: formData,
    );

    // Restore original headers
    _dio.options.headers = originalHeaders;

    // Check that the response contains data and is of the correct type
    if (response.data == null) {
      throw GladiaApiException(message: 'Empty response from server');
    }

    // Parse response data safely
    Map<String, dynamic> responseData;

    if (response.data is Map<String, dynamic>) {
      responseData = response.data as Map<String, dynamic>;
    } else if (response.data is String) {
      try {
        // Try to parse the string as JSON
        final jsonData = json.decode(response.data as String);
        if (jsonData is Map<String, dynamic>) {
          responseData = jsonData;
        } else {
          throw GladiaApiException(
            message: 'Response JSON is not an object: ${response.data}',
          );
        }
      } catch (e) {
        throw GladiaApiException(
          message:
              'Unable to parse response as JSON: ${response.data}. Error: $e',
        );
      }
    } else {
      throw GladiaApiException(
        message:
            'Invalid response format from server. Expected Map<String, dynamic> or String, got: ${response.data.runtimeType}. Data: ${response.data}',
      );
    }

    return UploadResult.fromJson(responseData);
  } on DioException catch (e) {
    throw GladiaApiException.fromDioError(e);
  } catch (e) {
    if (e is GladiaApiException) {
      rethrow;
    }
    throw GladiaApiException(message: e.toString());
  }
}