startStreamingAudio method
Starts streaming audio data from the microphone.
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 audio player.
Throws a PlatformException if there is an error accessing the microphone or starting the stream.
Implementation
Future<void> startStreamingAudio() async {
// Check if the app has permission to access the microphone
bool hasPermission = await _record.hasPermission();
debugPrint('Microphone permission: $hasPermission');
if (hasPermission) {
// Check if the recorder is already running
bool isRecording = await _record.isRecording();
debugPrint('Is recording: $isRecording');
if (!isRecording) {
// Start recording as a stream and wait for the stream
try {
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');
addAudioChunk(audioChunk); // Process the received audio chunk
},
onError: (error) {
// Handle any errors that occur during streaming
debugPrint('Error: $error');
},
onDone: () {
// Handle stream completion
debugPrint('Stream has completed.');
},
cancelOnError: true, // Stop 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');
}
} else {
debugPrint(
'Microphone permission not granted or recorder is unavailable');
}
}