### Installing Dependencies for Gladia API Example (Bash) Source: https://github.com/xdevspo/flutter-gladia/blob/master/example/README.md Navigates into the example directory and uses `dart pub get` to fetch and install the necessary dependencies for the Dart console application. This step is required before running the example. ```bash cd example dart pub get ``` -------------------------------- ### Install Dependencies with flutter pub get Source: https://github.com/xdevspo/flutter-gladia/blob/master/doc/getting_started.md Runs the Flutter package manager command to fetch and install the dependencies listed in pubspec.yaml. ```Bash flutter pub get ``` -------------------------------- ### Install Dependencies with dart pub get Source: https://github.com/xdevspo/flutter-gladia/blob/master/doc/getting_started.md Runs the Dart package manager command to fetch and install the dependencies listed in pubspec.yaml for pure Dart projects. ```Bash dart pub get ``` -------------------------------- ### Install Dependencies - Flutter Pub Bash Source: https://github.com/xdevspo/flutter-gladia/blob/master/example/doc/README.md Use this command in your terminal within the project directory to install all necessary dependencies. The `flutter pub get` command fetches packages defined in the `pubspec.yaml` file. This step is essential before running any examples. ```bash flutter pub get ``` -------------------------------- ### Add Gladia Dependency to pubspec.yaml Source: https://github.com/xdevspo/flutter-gladia/blob/master/doc/getting_started.md Adds the Gladia SDK package to your project's dependencies list in the pubspec.yaml file. ```YAML dependencies: gladia: ^0.1.0 ``` -------------------------------- ### Initialize GladiaClient in Dart Source: https://github.com/xdevspo/flutter-gladia/blob/master/doc/getting_started.md Creates an instance of the GladiaClient, which is required to interact with the Gladia API. Requires your API key and optionally enables logging. ```Dart import 'package:gladia/gladia.dart'; // Create a client with API key final client = GladiaClient( apiKey: 'your_api_key', enableLogging: true, // Optional for debugging ); ``` -------------------------------- ### Installing Flutter Dependencies (Bash) Source: https://github.com/xdevspo/flutter-gladia/blob/master/README.md Executes the `flutter pub get` command to fetch and install the dependencies listed in the `pubspec.yaml` file, including the newly added `gladia` package. This command resolves package versions and updates the project's lock file. ```Bash flutter pub get ``` -------------------------------- ### Run Dart Example - Bash Command Source: https://github.com/xdevspo/flutter-gladia/blob/master/example/doc/README.md Execute this command in your terminal to run a specific example file, such as `main.dart`. The `dart run` command compiles and runs the specified Dart script. Replace `example/main.dart` with the path to the example you wish to run. ```bash dart run example/main.dart ``` -------------------------------- ### Setting Gladia API Key - .env Configuration Source: https://github.com/xdevspo/flutter-gladia/blob/master/example/doc/README.md This snippet shows the required format for setting your Gladia API key in a `.env` file. Create this file in the example directory and replace the placeholder with your actual key. The examples load credentials from this file. ```text GLADIA_API_KEY=your_api_key_here ``` -------------------------------- ### Running Gladia API Console Example with API Key (Bash) Source: https://github.com/xdevspo/flutter-gladia/blob/master/example/README.md Demonstrates how to run the Dart console example for the Gladia API v2, providing the API key either as a command line argument (`--api-key`) or via the `GLADIA_API_KEY` environment variable. Requires a prepared audio file. ```bash # With command line parameter dart run console_sync_example.dart --api-key= --audio-file=path/to/audio.mp3 # With environment variable export GLADIA_API_KEY= dart run console_sync_example.dart --audio-file=path/to/audio.mp3 ``` -------------------------------- ### Running Gladia API Console Example (Basic) (Bash) Source: https://github.com/xdevspo/flutter-gladia/blob/master/example/README.md Executes the Dart console example script `console_sync_example.dart` using the `dart run` command. This assumes the API key is available via the `GLADIA_API_KEY` environment variable and an audio file is specified or defaults are used. ```bash dart run console_sync_example.dart ``` -------------------------------- ### Running the Flutter Application Source: https://github.com/xdevspo/flutter-gladia/blob/master/example/doc/basic_example.md The command-line instruction to run the Flutter application after setting up the project and dependencies. ```Bash flutter run ``` -------------------------------- ### Starting Live Transcription (Dart) Source: https://github.com/xdevspo/flutter-gladia/blob/master/example/doc/live_transcription_example.md This method orchestrates the live transcription process. It requests permissions, initializes a Gladia transcription session with specified options, creates and connects a WebSocket, configures and starts audio recording, and begins streaming audio data to the WebSocket periodically. ```Dart Future _startRecording() async { try { // Request permissions await _requestPermissions(); if (_errorMessage.isNotEmpty) return; setState(() { _status = 'Initializing session...'; _transcriptionText = ''; }); // 1. Initialize transcription session final options = LiveTranscriptionOptions( encoding: 'pcm', sampleRate: 16000, bitDepth: 16, language: 'en', diarize: true, speakerCount: 2, interim: true, // Get interim results ); final initResult = await _client.initiateLiveTranscription( options: options, ); setState(() { _status = 'Connecting to WebSocket...'; }); // 2. Create WebSocket connection _socket = _client.createLiveTranscriptionSocket( websocketUrl: initResult.websocketUrl, onTranscriptionResult: (result) { setState(() { _transcriptionText = result.text; if (result.metadata?.isFinal == true) { _status = 'Final result received'; } else { _status = 'Transcription in progress...'; } }); }, onError: (error) { setState(() { _errorMessage = 'WebSocket error: $error'; _isRecording = false; }); }, onDone: () { setState(() { _status = 'Connection closed'; _isRecording = false; }); }, ); // 3. Start connection await _socket!.connect(); setState(() { _status = 'Starting audio recording...'; }); // 4. Configure audio recording await _recorder.start( encoder: AudioEncoder.pcm16bits, samplingRate: 16000, numChannels: 1, ); setState(() { _isRecording = true; _status = 'Recording and transcription active'; }); // 5. Start periodic audio data retrieval and sending _recorder.onAmplitudeChanged(const Duration(milliseconds: 200)).listen((amp) async { if (_isRecording && _socket != null) { try { final buffer = await _recorder.getCurrent(); if (buffer != null) { _socket!.sendAudioData(buffer); } } catch (e) { print('Error getting audio data: $e'); } } }); } catch (e) { setState(() { _errorMessage = 'Error starting recording: $e'; _isRecording = false; }); } } ``` -------------------------------- ### Setting Up Audio Capture with record package - Dart Source: https://github.com/xdevspo/flutter-gladia/blob/master/doc/live_transcription_guide.md Configures and starts audio recording using the 'record' package. It sets parameters like encoder, bit rate, sample rate, and number of channels, and specifies a temporary file path to store the recorded audio. ```Dart final audioRecorder = AudioRecorder(); // Start recording await audioRecorder.start( RecordConfig( encoder: AudioEncoder.wav, bitRate: 256000, sampleRate: 16000, numChannels: 1, ), path: tempFilePath, ); ``` -------------------------------- ### Transcribe Audio from URL using Gladia SDK (Dart) Source: https://github.com/xdevspo/flutter-gladia/blob/master/doc/getting_started.md Shows how to transcribe audio hosted at a remote URL. Initializes the client, initiates the transcription process with the URL, and then retrieves the transcription result using the task ID. ```Dart import 'package:gladia/gladia.dart'; Future transcribeAudioUrl() async { final client = GladiaClient(apiKey: 'your_api_key'); final audioUrl = 'https://example.com/audio.mp3'; try { // Initiate transcription by URL final initResult = await client.initiateTranscription(audioUrl: audioUrl); // Get transcription result final result = await client.getTranscriptionResult(taskId: initResult.id); print('Text: ${result.text}'); } catch (e) { print('Error: $e'); } } ``` -------------------------------- ### Transcribe Local Audio File using Gladia SDK (Dart) Source: https://github.com/xdevspo/flutter-gladia/blob/master/doc/getting_started.md Demonstrates how to transcribe a local audio file using the Gladia SDK. Initializes the client, specifies the file path, calls the transcription method, and prints the full text and segmented results. ```Dart import 'dart:io'; import 'package:gladia/gladia.dart'; Future transcribeAudioFile() async { // Initialize client final client = GladiaClient(apiKey: 'your_api_key'); // Path to audio file final file = File('path/to/audio/file.mp3'); try { // Transcribe file (combines all stages in one call) final result = await client.transcribeFile(file: file); // Get full text print('Full text: ${result.text}'); // Access segments with timestamps if (result.segments != null) { for (final segment in result.segments!) { print('${segment.start} - ${segment.end}: ${segment.text}'); } } } catch (e) { print('Error: $e'); } } ``` -------------------------------- ### Getting Transcription List - Dart Source: https://github.com/xdevspo/flutter-gladia/blob/master/doc/usage_examples.md Demonstrates how to retrieve a list of all previous transcription tasks associated with the API key and iterate through the list to print details like ID, status, creation time, and result URL for each item. ```Dart import 'package:gladia/gladia.dart'; Future main() async { final client = GladiaClient(apiKey: 'your_api_key'); try { // Get list of all transcriptions final transcriptions = await client.getTranscriptionList(); // Output information about transcriptions for (final item in transcriptions.items) { print('ID: ${item.id}'); print('Status: ${item.status}'); print('Created: ${item.createdAt}'); if (item.resultUrl != null) { print('Result URL: ${item.resultUrl}'); } print('---'); } } catch (e) { print('Error: $e'); } } ``` -------------------------------- ### Basic File Transcription - Dart Source: https://github.com/xdevspo/flutter-gladia/blob/master/doc/usage_examples.md Demonstrates how to initialize the Gladia client and perform a complete file transcription process, printing the resulting text or any encountered errors. ```Dart import 'dart:io'; import 'package:gladia/gladia.dart'; Future main() async { // Initialize client final client = GladiaClient(apiKey: 'your_api_key'); // Path to audio file final file = File('path/to/file.mp3'); try { // Complete file transcription process final result = await client.transcribeFile(file: file); // Output text print('Transcription text: ${result.text}'); } catch (e) { print('Error: $e'); } } ``` -------------------------------- ### Starting Microphone Recording in Dart Source: https://github.com/xdevspo/flutter-gladia/blob/master/example/doc/live_transcription_example.md Starts recording audio from the device's microphone using the 'record' package. It configures the recorder with the required audio format (PCM 16-bit), sampling rate (16000 Hz), and number of channels (1) to match the transcription service requirements. ```Dart await _recorder.start( encoder: AudioEncoder.pcm16bits, samplingRate: 16000, numChannels: 1, ); ``` -------------------------------- ### Configuring Gladia API Key in .env File Source: https://github.com/xdevspo/flutter-gladia/blob/master/example/doc/basic_example.md Shows the required format for the `.env` file to store the Gladia API key, which is then loaded by the application using the `flutter_dotenv` package. ```dotenv GLADIA_API_KEY=your_api_key ``` -------------------------------- ### App Entry Point and Initialization (Dart) Source: https://github.com/xdevspo/flutter-gladia/blob/master/example/doc/live_transcription_example.md The main function serves as the entry point for the Flutter application. It ensures Flutter bindings are initialized, loads environment variables using dotenv, and then runs the main application widget. ```Dart import 'dart:convert'; import 'dart:io'; import 'dart:typed_data'; import 'package:flutter/material.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:gladia/gladia.dart'; import 'package:permission_handler/permission_handler.dart'; import 'package:record/record.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await dotenv.load(); runApp(const LiveTranscriptionApp()); } ``` -------------------------------- ### Adding Gladia SDK and Dependencies to pubspec.yaml Source: https://github.com/xdevspo/flutter-gladia/blob/master/example/doc/basic_example.md Specifies the necessary dependencies (`gladia`, `flutter_dotenv`) to be added to the `pubspec.yaml` file for using the Gladia API SDK and loading environment variables in a Flutter project. ```YAML dependencies: flutter: sdk: flutter gladia: ^0.1.0 flutter_dotenv: ^5.0.2 ``` -------------------------------- ### Implementing Real-time Transcription in Flutter (Dart) Source: https://github.com/xdevspo/flutter-gladia/blob/master/doc/live_transcription_guide.md This Flutter StatefulWidget and its State class provide a full example of setting up and managing a real-time audio transcription session. It handles microphone permissions, initializes recording using the 'record' package, connects to the Gladia API via WebSocket, sends audio data periodically, and updates the UI with interim and final transcription results. ```Dart import 'dart:async'; import 'dart:io'; import 'package:flutter/material.dart'; import 'package:gladia/gladia.dart'; import 'package:record/record.dart'; import 'package:path_provider/path_provider.dart'; import 'package:permission_handler/permission_handler.dart'; class LiveTranscriptionExample extends StatefulWidget { @override _LiveTranscriptionExampleState createState() => _LiveTranscriptionExampleState(); } class _LiveTranscriptionExampleState extends State { // API key final String apiKey = 'your_api_key'; // Client and socket late GladiaClient gladiaClient; LiveTranscriptionSocket? socket; // Recording final record = AudioRecorder(); String tempFilePath = ''; bool isRecording = false; // Transcription String transcription = ''; Timer? sendingTimer; @override void initState() { super.initState(); gladiaClient = GladiaClient(apiKey: apiKey); _prepareTempFile(); } @override void dispose() { _stopRecording(); sendingTimer?.cancel(); socket?.close(); super.dispose(); } // Prepare temp file for recording Future _prepareTempFile() async { final tempDir = await getTemporaryDirectory(); tempFilePath = '${tempDir.path}/temp_audio.wav'; } // Start recording and transcription Future _startRecording() async { // Check microphone permission if (await Permission.microphone.request().isGranted) { try { // 1. Initialize transcription session final sessionResult = await gladiaClient.initLiveTranscription( options: LiveTranscriptionOptions( encoding: 'pcm', sampleRate: 16000, language: 'en', ), ); // 2. Create WebSocket socket = gladiaClient.createLiveTranscriptionSocket( sessionUrl: sessionResult.url, onMessage: _handleMessage, onDone: () { print('Connection closed'); _reconnectWebSocket(sessionResult.url); }, onError: (error) { print('WebSocket error: $error'); _reconnectWebSocket(sessionResult.url); }, ); // 3. Connect WebSocket await socket!.connect(); // 4. Start recording await record.start( RecordConfig( encoder: AudioEncoder.wav, bitRate: 256000, sampleRate: 16000, numChannels: 1, ), path: tempFilePath, ); // 5. Update state setState(() { isRecording = true; transcription = ''; }); // 6. Start sending audio data sendingTimer = Timer.periodic(Duration(milliseconds: 300), _sendAudioChunk); } catch (e) { print('Error starting recording: $e'); } } else { print('Microphone permission denied'); } } // Stop recording and transcription Future _stopRecording() async { // Cancel timer sendingTimer?.cancel(); sendingTimer = null; if (isRecording) { // Stop recording await record.stop(); // End stream socket?.sendEndOfStream(); // Close connection await socket?.close(); socket = null; // Update state setState(() { isRecording = false; }); } } // Send audio data void _sendAudioChunk(Timer timer) async { if (!isRecording || socket == null) { timer.cancel(); return; } try { final file = File(tempFilePath); if (await file.exists()) { final fileLength = await file.length(); // Skip WAV header if (fileLength > 44) { final raf = await file.open(mode: FileMode.read); await raf.setPosition(44); final audioBytes = await raf.read(fileLength - 44); await raf.close(); // Send audio data socket!.sendAudioData(audioBytes); } } } catch (e) { print('Error sending audio: $e'); } } // Handle WebSocket messages void _handleMessage(dynamic message) { if (message is Map) { if (message['type'] == 'transcript') { final data = message['data']; if (data != null && data['utterance'] != null) { final text = data['utterance']['text']; final isFinal = data['is_final'] ?? false; if (text != null && text.isNotEmpty) { setState(() { if (isFinal) { // Add new line for final results transcription += text + '\n'; } else { // Replace last line for interim results ``` -------------------------------- ### Initializing Gladia Live Transcription Session in Dart Source: https://github.com/xdevspo/flutter-gladia/blob/master/example/doc/live_transcription_example.md Initializes the live transcription session with specific options such as encoding, sample rate, language, diarization settings, and interim results. It then calls initiateLiveTranscription on the Gladia client to get the WebSocket URL and session ID required for the connection. ```Dart final options = LiveTranscriptionOptions( encoding: 'pcm', sampleRate: 16000, bitDepth: 16, language: 'en', diarize: true, speakerCount: 2, interim: true, // Get interim results ); final initResult = await _client.initiateLiveTranscription(options: options); ``` -------------------------------- ### Adding Required Dependencies in pubspec.yaml Source: https://github.com/xdevspo/flutter-gladia/blob/master/example/doc/live_transcription_example.md Lists the required Flutter packages for the project: gladia for the transcription service, record for audio recording, permission_handler for managing permissions, and flutter_dotenv for loading environment variables like the API key. ```YAML dependencies: flutter: sdk: flutter gladia: ^0.1.0 record: ^5.0.0 permission_handler: ^10.0.0 flutter_dotenv: ^5.0.2 ``` -------------------------------- ### Main Application Widget (Dart) Source: https://github.com/xdevspo/flutter-gladia/blob/master/example/doc/live_transcription_example.md The LiveTranscriptionApp widget is the root of the application's widget tree. It sets up the basic MaterialApp with a title, theme, and defines the initial screen (LiveTranscriptionScreen). ```Dart class LiveTranscriptionApp extends StatelessWidget { const LiveTranscriptionApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Gladia Live Transcription Demo', theme: ThemeData( primarySwatch: Colors.blue, visualDensity: VisualDensity.adaptivePlatformDensity, ), home: const LiveTranscriptionScreen(), ); } } ``` -------------------------------- ### Building Live Transcription UI - Flutter/Dart Source: https://github.com/xdevspo/flutter-gladia/blob/master/doc/live_transcription_guide.md This method constructs the main UI for the live transcription screen. It includes an `AppBar`, a `Padding` widget containing a `Column`. The column holds an `Expanded` container for displaying the transcription text within a `SingleChildScrollView` and an `ElevatedButton` to start or stop recording, dynamically changing its text and color based on the `isRecording` state. ```Dart @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Live Transcription'), ), body: Padding( padding: EdgeInsets.all(16.0), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Expanded( child: Container( padding: EdgeInsets.all(16.0), decoration: BoxDecoration( border: Border.all(color: Colors.grey), borderRadius: BorderRadius.circular(8.0), ), child: SingleChildScrollView( child: Text( transcription.isEmpty ? 'Transcription will appear here' : transcription, style: TextStyle(fontSize: 16.0), ), ), ), ), SizedBox(height: 16.0), ElevatedButton( onPressed: isRecording ? _stopRecording : _startRecording, style: ElevatedButton.styleFrom( backgroundColor: isRecording ? Colors.red : Colors.blue, padding: EdgeInsets.symmetric(vertical: 12.0), ), child: Text( isRecording ? 'Stop Recording' : 'Start Recording', style: TextStyle(fontSize: 16.0), ), ) ] ) ) ); } ``` -------------------------------- ### Step-by-Step Transcription with Custom Options - Dart Source: https://github.com/xdevspo/flutter-gladia/blob/master/doc/usage_examples.md Illustrates a multi-step transcription workflow including uploading an audio file, configuring detailed transcription options (language, diarization, paragraphization), initiating the task, retrieving the result, and accessing speaker-specific utterances. ```Dart import 'dart:io'; import 'package:gladia/gladia.dart'; Future main() async { final client = GladiaClient(apiKey: 'your_api_key'); final file = File('path/to/file.mp3'); try { // 1. Upload file final uploadResult = await client.uploadAudioFile(file); print('File uploaded: ${uploadResult.audioUrl}'); // 2. Configure transcription options final options = TranscriptionOptions( language: 'en', // Audio language diarize: true, // Speaker identification speakerCount: 2, // Expected number of speakers paragraphizeSentences: true, // Break into paragraphs // Additional settings for diarization diarizationConfig: DiarizationConfig( minSpeakers: 1, maxSpeakers: 3, ), ); // 3. Initiate transcription final initResult = await client.initiateTranscription( audioUrl: uploadResult.audioUrl, options: options, ); // 4. Get result final result = await client.getTranscriptionResult( taskId: initResult.id, ); // 5. Work with results print('Full text: ${result.text}'); // Access speaker information if (result.utterances != null) { for (final utterance in result.utterances!) { print('Speaker ${utterance.speaker}: ${utterance.text}'); } } } catch (e) { print('Error: $e'); } } ``` -------------------------------- ### Generating Subtitles with Gladia SDK (Dart) Source: https://github.com/xdevspo/flutter-gladia/blob/master/example/doc/advanced_examples.md Shows how to generate subtitles for an audio file from a URL using the Gladia SDK. It configures transcription options to enable subtitle generation in SRT format with specific line length and duration constraints. The example initiates transcription, retrieves the result, downloads the generated subtitle file, and prints its content. ```Dart import 'dart:io'; import 'package:gladia/gladia.dart'; Future main() async { final client = GladiaClient(apiKey: 'your_api_key'); final audioUrl = 'https://example.com/audio.mp3'; try { // Configure options for subtitle generation final options = TranscriptionOptions( language: 'en', subtitles: true, // Enable subtitle generation subtitlesFormat: 'srt', // Subtitle format (srt, vtt) subtitlesConfig: SubtitlesConfig( maxLineLength: 40, // Maximum line length maxLinesCount: 2, // Maximum number of lines minDuration: 1, // Minimum subtitle duration (in seconds) maxDuration: 7, // Maximum subtitle duration (in seconds) ), ); // Initiate transcription final initResult = await client.initiateTranscription( audioUrl: audioUrl, options: options, ); // Get result final result = await client.getTranscriptionResult(taskId: initResult.id); // Get subtitle URL if (result.metadata?.subtitle != null) { final subtitlesUrl = result.metadata!.subtitle!.url; print('Subtitles URL: $subtitlesUrl'); // Download subtitle file final response = await client.downloadFile(subtitlesUrl); final file = File('subtitles.srt'); await file.writeAsBytes(response.data); print('Subtitles saved to file subtitles.srt'); // Display subtitle content final content = await file.readAsString(); print('\nExample content:\n'); print(content.split('\n\n').take(3).join('\n\n')); } } catch (e) { print('Error: $e'); } } ``` -------------------------------- ### Transcribing Audio File using Gladia SDK in Flutter Source: https://github.com/xdevspo/flutter-gladia/blob/master/example/doc/basic_example.md This is the main application code demonstrating the full flow of initializing the Gladia client, selecting a local audio file, calling the transcription API, and displaying the result in a Flutter UI. It includes loading the API key from environment variables and handling loading states and errors. ```Dart import 'dart:async'; import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:gladia/gladia.dart'; Future main() async { // Load environment variables await dotenv.load(); runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Gladia Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: const MyHomePage(title: 'Gladia Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key, required this.title}); final String title; @override State createState() => _MyHomePageState(); } class _MyHomePageState extends State { final GladiaClient client = GladiaClient( apiKey: dotenv.env['GLADIA_API_KEY'] ?? '', enableLogging: true, ); String _transcriptionResult = ''; bool _isLoading = false; Future _transcribeAudio() async { setState(() { _isLoading = true; _transcriptionResult = ''; }); try { // Use the provided test audio file final file = File('audio_file.mp3'); // Simple API call for file transcription final result = await client.transcribeFile( file: file, language: 'en', // Specify audio language ); setState(() { _transcriptionResult = result.text; }); } catch (e) { setState(() { _transcriptionResult = 'Error: $e'; }); } finally { setState(() { _isLoading = false; }); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Padding( padding: const EdgeInsets.all(16.0), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ if (_isLoading) const CircularProgressIndicator() else ElevatedButton( onPressed: _transcribeAudio, child: const Text('Transcribe Audio'), ), const SizedBox(height: 20), Expanded( child: SingleChildScrollView( child: Text( _transcriptionResult.isEmpty ? 'Press the button to transcribe audio' : _transcriptionResult, style: const TextStyle(fontSize: 16), ), ), ), ], ), ), ), ); } } ``` -------------------------------- ### Audio Transcription by URL - Dart Source: https://github.com/xdevspo/flutter-gladia/blob/master/doc/usage_examples.md Shows how to initiate a transcription task directly from a public audio URL, configure options like subtitles, and retrieve the result, specifically accessing the subtitle file URL. ```Dart import 'package:gladia/gladia.dart'; Future main() async { final client = GladiaClient(apiKey: 'your_api_key'); final audioUrl = 'https://example.com/audio.mp3'; try { // Configure transcription options final options = TranscriptionOptions( language: 'en', subtitles: true, subtitlesFormat: 'srt', ); // Initiate transcription by URL final initResult = await client.initiateTranscription( audioUrl: audioUrl, options: options, ); // Get result final result = await client.getTranscriptionResult( taskId: initResult.id, ); // Work with subtitles if (result.metadata?.subtitle != null) { print('Subtitles path: ${result.metadata!.subtitle!.url}'); } } catch (e) { print('Error: $e'); } } ``` -------------------------------- ### Error Handling - Dart Source: https://github.com/xdevspo/flutter-gladia/blob/master/doc/usage_examples.md Provides an example of how to implement error handling when using the Gladia SDK, specifically catching `GladiaApiException` to access API-specific error details like status code and error code, as well as catching general exceptions. ```Dart import 'dart:io'; import 'package:gladia/gladia.dart'; Future main() async { final client = GladiaClient(apiKey: 'your_api_key'); try { // Attempt to transcribe non-existent file final file = File('non_existent_file.mp3'); await client.transcribeFile(file: file); } on GladiaApiException catch (e) { // Handle API errors print('API Error: ${e.message}'); if (e.statusCode != null) { print('Status code: ${e.statusCode}'); } if (e.errorCode != null) { print('Error code: ${e.errorCode}'); } } catch (e) { // Handle other errors print('General error: $e'); } } ``` -------------------------------- ### Configuring Gladia API Key in .env Source: https://github.com/xdevspo/flutter-gladia/blob/master/example/doc/live_transcription_example.md Specifies the Gladia API key required to authenticate with the Gladia service. This key should be stored securely, typically in a .env file, and loaded by the application using a package like flutter_dotenv. ```Shell GLADIA_API_KEY=your_api_key ``` -------------------------------- ### Adding Microphone and Internet Permissions for Android Source: https://github.com/xdevspo/flutter-gladia/blob/master/example/doc/live_transcription_example.md Adds necessary permissions to the Android manifest file (android/app/src/main/AndroidManifest.xml). RECORD_AUDIO is required to access the device's microphone, and INTERNET is needed to connect to the Gladia API over the network. ```XML ``` -------------------------------- ### Live Transcription Screen Widget (Dart) Source: https://github.com/xdevspo/flutter-gladia/blob/master/example/doc/live_transcription_example.md The LiveTranscriptionScreen is a StatefulWidget that manages the state for the main transcription interface. It creates the corresponding State object where the core logic and UI state are handled. ```Dart class LiveTranscriptionScreen extends StatefulWidget { const LiveTranscriptionScreen({super.key}); @override State createState() => _LiveTranscriptionScreenState(); } ``` -------------------------------- ### Initiating Transcription with Callback using Gladia (Dart) Source: https://github.com/xdevspo/flutter-gladia/blob/master/example/doc/advanced_examples.md Illustrates setting up transcription options to include a callback URL, method, and headers. It uploads the audio file and initiates the transcription process, indicating that results will be sent asynchronously to the specified webhook endpoint. Requires an API key, a local audio file, and a configured webhook server. ```Dart import 'dart:io'; import 'package:gladia/gladia.dart'; Future main() async { final client = GladiaClient(apiKey: 'your_api_key'); final file = File('path/to/file.mp3'); try { // Configure options with callback final options = TranscriptionOptions( language: 'en', callbackConfig: CallbackConfig( url: 'https://your-server.com/api/transcription-webhook', method: 'POST', headers: { 'Authorization': 'Bearer your-token', 'Custom-Header': 'custom-value', }, ), ); // Upload file final uploadResult = await client.uploadAudioFile(file); // Initiate transcription with callback final initResult = await client.initiateTranscription( audioUrl: uploadResult.audioUrl, options: options, ); print('Transcription started with ID: ${initResult.id}'); print('Results will be sent to URL: ${options.callbackConfig!.url}'); } catch (e) { print('Error: $e'); } } ``` -------------------------------- ### Requesting Microphone Permissions (Dart) Source: https://github.com/xdevspo/flutter-gladia/blob/master/example/doc/live_transcription_example.md This asynchronous method requests microphone access permission from the user using the permission_handler package. If permission is not granted, it updates the error message state. ```Dart Future _requestPermissions() async { final status = await Permission.microphone.request(); if (status != PermissionStatus.granted) { setState(() { _errorMessage = 'Microphone access is required for this app to work'; }); return; } } ``` -------------------------------- ### Using Advanced Transcription Options with Gladia SDK Source: https://github.com/xdevspo/flutter-gladia/blob/master/example/doc/basic_example.md Demonstrates how to configure and use advanced transcription parameters like speaker diarization (`diarize`), specifying speaker count (`speakerCount`), and paragraph segmentation (`paragraphizeSentences`) by creating a `TranscriptionOptions` object and passing it to the `transcribeFile` method. ```Dart final options = TranscriptionOptions( diarize: true, // Speaker identification speakerCount: 2, // Number of speakers paragraphizeSentences: true, // Break into paragraphs ); final result = await client.transcribeFile( file: file, language: 'en', options: options, ); ``` -------------------------------- ### Initiating Transcription by URL (Dart) Source: https://github.com/xdevspo/flutter-gladia/blob/master/doc/api_reference.md Sends a request to start an audio transcription task using a provided audio file URL. Optionally allows specifying the language and additional transcription options. Returns a Future with the task initialization result. ```dart Future initiateTranscription({ required String audioUrl, String? language, TranscriptionOptions? options, }) ``` -------------------------------- ### Initializing Gladia Live Transcription Session - Dart Source: https://github.com/xdevspo/flutter-gladia/blob/master/doc/live_transcription_guide.md Initializes a new live transcription session with the Gladia REST API. This step is required before establishing a WebSocket connection. It specifies audio parameters like sample rate, bit depth, channels, and encoding. ```Dart final sessionResult = await gladiaClient.initLiveTranscription( sampleRate: 16000, // Sampling rate in Hz bitDepth: 16, // Sample depth in bits channels: 1, // Number of audio channels (1 = mono) encoding: 'wav/pcm', // Audio encoding format ); // Get session ID and WebSocket URL final sessionId = sessionResult.id; final webSocketUrl = sessionResult.url; ``` -------------------------------- ### Disposing Resources (Dart) Source: https://github.com/xdevspo/flutter-gladia/blob/master/example/doc/live_transcription_example.md The dispose method is called when the widget is removed from the widget tree. It ensures that the recording is stopped and resources are cleaned up to prevent memory leaks. ```Dart @override void dispose() { _stopRecording(); super.dispose(); } ``` -------------------------------- ### Cancel Transcription - Dart Source: https://github.com/xdevspo/flutter-gladia/blob/master/doc/usage_examples.md Shows the process of initiating a transcription task using a URL and then cancelling the task using the returned task ID. ```Dart import 'package:gladia/gladia.dart'; Future main() async { final client = GladiaClient(apiKey: 'your_api_key'); final audioUrl = 'https://example.com/audio.mp3'; try { // Initiate transcription final initResult = await client.initiateTranscription( audioUrl: audioUrl, ); // Cancel transcription await client.cancelTranscription(taskId: initResult.id); print('Transcription successfully canceled'); } catch (e) { print('Error: $e'); } } ``` -------------------------------- ### Creating Gladia Live Transcription WebSocket Connection - Dart Source: https://github.com/xdevspo/flutter-gladia/blob/master/doc/live_transcription_guide.md Establishes a WebSocket connection to the Gladia live transcription server using the URL obtained from the session initialization step. It requires callback functions to handle incoming messages, connection closure, and errors. ```Dart final socket = gladiaClient.createLiveTranscriptionSocket( sessionUrl: sessionResult.url, onMessage: handleTranscriptionMessage, onDone: handleConnectionClosed, onError: handleConnectionError, ); ``` -------------------------------- ### Transcribing Audio with Translation using Gladia (Dart) Source: https://github.com/xdevspo/flutter-gladia/blob/master/example/doc/advanced_examples.md Shows how to use the Gladia client to upload an audio file, initiate transcription with translation options (French source, English target), retrieve the result, and print both the original and translated text. Requires an API key and a local audio file. ```Dart import 'dart:io'; import 'package:gladia/gladia.dart'; Future main() async { final client = GladiaClient(apiKey: 'your_api_key'); final file = File('path/to/file.mp3'); try { // Configure options with translation final options = TranscriptionOptions( language: 'fr', // Source audio language directTranslation: true, translation: TranslationConfig( target: 'en', // Target translation language model: 'base', // Translation model ), ); // Upload and transcribe file final uploadResult = await client.uploadAudioFile(file); final initResult = await client.initiateTranscription( audioUrl: uploadResult.audioUrl, options: options, ); final result = await client.getTranscriptionResult(taskId: initResult.id); // Output original text print('Original text: ${result.text}'); // Output translated text if (result.translation != null) { print('\nTranslated text (EN): ${result.translation!.text}'); } } catch (e) { print('Error: $e'); } } ``` -------------------------------- ### Transcribing Audio with LLM Integration using Gladia (Dart) Source: https://github.com/xdevspo/flutter-gladia/blob/master/example/doc/advanced_examples.md Shows how to configure transcription options to enable audioToLLM processing. It sets a prompt and specifies an LLM model (gpt-3.5-turbo). The code uploads and transcribes the file, then prints the original text and the result from the LLM processing. Requires an API key and a local audio file. ```Dart import 'dart:io'; import 'package:gladia/gladia.dart'; Future main() async { final client = GladiaClient(apiKey: 'your_api_key'); final file = File('path/to/file.mp3'); try { // Configure options for LLM integration final options = TranscriptionOptions( language: 'en', // Enable text processing with language model audioToLLM: true, audioToLLMConfig: AudioToLLMConfig( prompt: 'Create a brief summary of the following conversation:', model: 'gpt-3.5-turbo', ), ); // Transcribe file with options final result = await client.transcribeFile( file: file, options: options, ); // Output original text print('Original text: ${result.text}'); // Output LLM processing results if (result.audioToLLM != null) { print('\nLLM processing result:'); print(result.audioToLLM!.result); } } catch (e) { print('Error: $e'); } } ``` -------------------------------- ### Screen State and Variables (Dart) Source: https://github.com/xdevspo/flutter-gladia/blob/master/example/doc/live_transcription_example.md The _LiveTranscriptionScreenState class holds the mutable state for the LiveTranscriptionScreen. It initializes the GladiaClient, audio recorder, and state variables to track recording status, transcription text, status messages, and errors. ```Dart class _LiveTranscriptionScreenState extends State { final GladiaClient _client = GladiaClient( apiKey: dotenv.env['GLADIA_API_KEY'] ?? '', enableLogging: true, ); LiveTranscriptionSocket? _socket; final _recorder = Record(); bool _isRecording = false; String _transcriptionText = ''; String _status = 'Ready to start'; String _errorMessage = ''; @override void dispose() { _stopRecording(); super.dispose(); } Future _requestPermissions() async { final status = await Permission.microphone.request(); if (status != PermissionStatus.granted) { setState(() { _errorMessage = 'Microphone access is required for this app to work'; }); return; } } Future _startRecording() async { try { // Request permissions await _requestPermissions(); if (_errorMessage.isNotEmpty) return; setState(() { _status = 'Initializing session...'; _transcriptionText = ''; }); // 1. Initialize transcription session final options = LiveTranscriptionOptions( encoding: 'pcm', sampleRate: 16000, bitDepth: 16, language: 'en', diarize: true, speakerCount: 2, interim: true, // Get interim results ); final initResult = await _client.initiateLiveTranscription( options: options, ); setState(() { _status = 'Connecting to WebSocket...'; }); // 2. Create WebSocket connection _socket = _client.createLiveTranscriptionSocket( websocketUrl: initResult.websocketUrl, onTranscriptionResult: (result) { setState(() { _transcriptionText = result.text; if (result.metadata?.isFinal == true) { _status = 'Final result received'; } else { _status = 'Transcription in progress...'; } }); }, onError: (error) { setState(() { _errorMessage = 'WebSocket error: $error'; _isRecording = false; }); }, onDone: () { setState(() { _status = 'Connection closed'; _isRecording = false; }); }, ); // 3. Start connection await _socket!.connect(); setState(() { _status = 'Starting audio recording...'; }); // 4. Configure audio recording await _recorder.start( encoder: AudioEncoder.pcm16bits, samplingRate: 16000, numChannels: 1, ); setState(() { _isRecording = true; _status = 'Recording and transcription active'; }); // 5. Start periodic audio data retrieval and sending _recorder.onAmplitudeChanged(const Duration(milliseconds: 200)).listen((amp) async { if (_isRecording && _socket != null) { try { final buffer = await _recorder.getCurrent(); if (buffer != null) { _socket!.sendAudioData(buffer); } } catch (e) { print('Error getting audio data: $e'); } } }); } catch (e) { setState(() { _errorMessage = 'Error starting recording: $e'; _isRecording = false; }); } } Future _stopRecording() async { if (_isRecording) { setState(() { _status = 'Finishing recording...'; }); // Stop recording await _recorder.stop(); // Send end of stream signal _socket?.sendEndOfStream(); // Wait for final processing await Future.delayed(const Duration(seconds: 2)); // Close connection await _socket?.close(); _socket = null; setState(() { _isRecording = false; _status = 'Recording completed'; }); } } ``` -------------------------------- ### Creating and Connecting Gladia WebSocket in Dart Source: https://github.com/xdevspo/flutter-gladia/blob/master/example/doc/live_transcription_example.md Creates a WebSocket connection to the Gladia live transcription service using the URL obtained from initialization. It sets up callbacks for handling transcription results, errors, and connection completion, and then connects the socket to begin communication. ```Dart _socket = _client.createLiveTranscriptionSocket( websocketUrl: initResult.websocketUrl, onTranscriptionResult: (result) { // Process result }, onError: (error) { // Handle errors }, onDone: () { // Handle completion }, ); // Start connection await _socket!.connect(); ``` -------------------------------- ### Adding Microphone Usage Description for iOS Source: https://github.com/xdevspo/flutter-gladia/blob/master/example/doc/live_transcription_example.md Adds the required microphone usage description to the iOS Info.plist file (ios/Runner/Info.plist). This string is displayed to the user when the app requests microphone access, explaining why it's needed for speech transcription. ```XML NSMicrophoneUsageDescription This app needs microphone access for speech transcription ```