microphone static method

Stream<Uint8List> microphone({
  1. AudioSource? audioSource,
  2. int? sampleRate,
  3. ChannelConfig? channelConfig,
  4. AudioFormat? audioFormat,
})

This function initializes a connection to the native backend (if not already available). Returns a Uint8List stream representing the captured audio. IMPORTANT - on iOS, there is no guarantee that captured audio will be encoded with the requested sampleRate/bitDepth. You must check the sampleRate and bitDepth properties of the MicStream object after invoking this method (though this does not need to be before listening to the returned stream). This is why this method returns a Uint8List - if you request a deeper encoding, you will need to manually convert the returned stream to the appropriate type, e.g., for 16 bit map each element using uint8List.buffer.asUint16List(). Alternatively, you can call toSampleStream(Stream<Uint8List>) to transform the raw stream to a more easily usable stream.

audioSource: The device used to capture audio. The default let's the OS decide. sampleRate: The amount of samples per second. More samples give better quality at the cost of higher data transmission channelConfig: States whether audio is mono or stereo audioFormat: Switch between 8, 16, 32 bit, and floating point PCM streams

Implementation

static Stream<Uint8List> microphone(
    {AudioSource? audioSource,
    int? sampleRate,
    ChannelConfig? channelConfig,
    AudioFormat? audioFormat}) {
  audioSource ??= DEFAULT_AUDIO_SOURCE;
  sampleRate ??= DEFAULT_SAMPLE_RATE;
  channelConfig ??= DEFAULT_CHANNELS_CONFIG;
  audioFormat ??= DEFAULT_AUDIO_FORMAT;

  if (sampleRate < _MIN_SAMPLE_RATE || sampleRate > _MAX_SAMPLE_RATE)
    return Stream.error(
        RangeError.range(sampleRate, _MIN_SAMPLE_RATE, _MAX_SAMPLE_RATE));

  final permissionStatus = _requestPermission
      ? Stream.fromFuture(MicStream.permissionStatus)
      : Stream.value(true);

  return permissionStatus.asyncExpand((grantedPermission) {
    if (!grantedPermission) {
      throw Exception('Microphone permission is not granted');
    }
    return _setupMicStream(
      audioSource!,
      sampleRate!,
      channelConfig!,
      audioFormat!,
    );
  });
}