initLiveTranscription method

Future<LiveSessionInitResult> initLiveTranscription({
  1. int sampleRate = 16000,
  2. int bitDepth = 16,
  3. int channels = 1,
  4. String encoding = 'wav/pcm',
  5. String? language,
  6. TranscriptionOptions? options,
})

Initializes session for speech recognition in real time

sampleRate - audio sampling rate in Hz (default 16000) bitDepth - audio bit depth (default 16) channels - audio channel count (default 1) encoding - audio encoding format (default 'wav/pcm') language - audio language (optional) options - additional options for recognition

Returns LiveSessionInitResult with session ID and URL for WebSocket connection

Implementation

Future<LiveSessionInitResult> initLiveTranscription({
  int sampleRate = 16000,
  int bitDepth = 16,
  int channels = 1,
  String encoding = 'wav/pcm',
  String? language,
  TranscriptionOptions? options,
}) async {
  try {
    // Prepare request parameters
    final Map<String, dynamic> requestData = {
      'sample_rate': sampleRate,
      'bit_depth': bitDepth,
      'channels': channels,
      'encoding': encoding,
    };

    // Add language if specified
    if (language != null) {
      requestData['language'] = language;
    }

    // Add options if specified
    if (options != null) {
      // Merge parameters from TranscriptionOptions
      requestData.addAll(options.toJson());
    }

    // Make request for session initialization
    final response = await _dio.post(
      'v2/live',
      data: requestData,
    );

    // 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 LiveSessionInitResult.fromJson(responseData);
  } on DioException catch (e) {
    throw GladiaApiException.fromDioError(e);
  } catch (e) {
    if (e is GladiaApiException) {
      rethrow;
    }
    throw GladiaApiException(message: e.toString());
  }
}