startAudio method

Future<(bool, AudioRecorder?, Stream<List<int>>?)> startAudio()

Sets up the Audio used for the application. Returns true if the audio is set up correctly, in which case it also returns a reference to the AudioRecorder and the audioSampleBufferedStream

Implementation

Future<(bool, AudioRecorder?, Stream<List<int>>?)> startAudio() async {
  // create a fresh AudioRecorder each time we run - it will be dispose()d when we click stop
  AudioRecorder audioRecorder = AudioRecorder();

  // Check and request permission if needed
  if (!await audioRecorder.hasPermission()) {
    return (false, null, null);
  }

  try {
    // start the audio stream
    // TODO select suitable sample rate for the Frame given BLE bandwidth constraints if we want to switch to Frame mic
    final recordStream = await audioRecorder.startStream(const RecordConfig(
        encoder: AudioEncoder.pcm16bits,
        numChannels: 1,
        sampleRate: _sampleRate));

    // buffer the audio stream into chunks of 4096 samples
    final audioSampleBufferedStream = bufferedListStream(
      recordStream.map((event) {
        return event.toList();
      }),
      // samples are PCM16, so 2 bytes per sample
      4096 * 2,
    );

    return (true, audioRecorder, audioSampleBufferedStream);
  } catch (e) {
    _log.severe('Error starting Audio: $e');
    return (false, null, null);
  }
}