startStreamingAudio method
Connects to the WebSocket server and starts streaming audio data.
This method checks for microphone permission and whether the recorder is already running. If not, it starts recording audio as a stream and sends each audio chunk to the WebSocket server.
client: The WebSocket client to which audio chunks will be sent.
Throws a PlatformException if there is an error accessing the microphone or starting the stream.
Implementation
Future<void> startStreamingAudio(WebSocket client) async {
// Check if the app has permission to access the microphone
bool hasPermission = await _record.hasPermission();
debugPrint('Microphone permission: $hasPermission');
if (hasPermission) {
_isServingAudio = true; // Set the flag to indicate audio streaming is active.
// Check if the recorder is already open
bool isRecording = await _record.isRecording();
debugPrint('Is recording: $isRecording');
if (!isRecording) {
// Start recording as a stream and wait for the stream
try {
// Configure audio recording settings
var config = RecordConfig(
bitRate: 128000, // Set the bit rate for audio recording
sampleRate: sampleRates, // Set the sample rate
numChannels: numChannels, // Set the number of channels
encoder: AudioEncoder.pcm16bits, // Set the audio encoder
);
// Start the audio stream
Stream<Uint8List> audioStream = await _record.startStream(config);
debugPrint('Audio stream obtained: ${audioStream.length}');
debugPrint('Audio streaming started');
// Listen for audio chunks
_audioSubscription = audioStream.listen(
(Uint8List audioChunk) {
debugPrint('Received audio chunk of ${audioChunk.length} bytes');
if (_isServingAudio) {
client.add(audioChunk); // Send the audio chunk to the WebSocket client
}
},
onError: (error) {
// Handle errors during streaming
debugPrint('Error: $error');
},
onDone: () {
// Handle stream completion
debugPrint('Stream has completed.');
},
cancelOnError: true, // Stops listening if an error occurs
);
} catch (e) {
debugPrint('Error starting audio stream: $e'); // Log any errors encountered when starting the stream
}
} else {
debugPrint('Recorder is already running'); // Log if the recorder is already active
}
} else {
debugPrint('Microphone permission not granted or recorder is unavailable'); // Log if permission is denied
}
}