enableAudio method
Enables the local mic and starts producing the stream with the label audio
NOTE: You can only produce to a room when you have joined the room, if you try to produce before joining the room it will fetch the stream and start producing when you join the room
Implementation
Future<MediaStream?> enableAudio({MediaStream? customAudioStream}) async {
logger.i('enableAudio called');
try {
if (!checkPermission(produceSourcesCheck: ProduceSources.mic)) {
logger.e('❌ Cannot Enable Audio, Permission Denied');
throw Exception('❌ Cannot Enable Audio, Permission Denied');
}
final existingStream = _activeStreams['audio'];
if (existingStream != null) {
logger.w('🔔 Mic Stream Already Enabled');
return null;
}
// transport are being created here
if (_sendTransport == null) {
await _createTransportOnServer(transportType: TransportType.send);
}
MediaStream? stream;
if (customAudioStream != null) {
stream = customAudioStream;
} else {
final ongoingStreamFuture = _pendingFetchingStream['mic'];
if (ongoingStreamFuture != null) {
await ongoingStreamFuture;
} else {
final streamFuture =
deviceHandler.fetchStream(mediaDevice: CustomMediaDevice.mic);
_pendingFetchingStream['mic'] = streamFuture;
}
final pendingFuture = _pendingFetchingStream['mic'];
if (pendingFuture == null) {
logger.i('🔔 Pending Mic Future Not Found');
return null;
}
final fetchedStream = await pendingFuture;
if (fetchedStream == null) {
logger.e('❌ Stream Not Found, cannot do enableAudio');
throw Exception('❌ Stream Not Found');
}
stream = fetchedStream;
}
if (stream != null) {
_activeStreams['audio'] = stream;
emit('stream-fetched', {
'mediaKind': 'mic',
'stream': stream,
'label': 'audio',
});
}
logger.i(
"enableAudio | fetched stream => ${stream?.getAudioTracks().first}",
);
await produce(
label: 'audio',
stream: stream,
appData: {
'producerPeerId': peerId,
},
stopTrackOnClose: true,
);
_pendingFetchingStream.remove('mic');
return stream;
} catch (error) {
logger.e('❌ Error Enabling Audio | error: $error');
deviceHandler.stopStream(_activeStreams['audio']);
_activeStreams.remove('audio');
_pendingFetchingStream.remove('mic');
rethrow;
}
}