pcmToWaveBuffer method

Future<Uint8List> pcmToWaveBuffer({
  1. required Uint8List inputBuffer,
  2. required Pcm codec,
})

Convert a raw PCM buffer to a WAVE buffer.

Adds a WAVE header in front of the PCM data It adds a Wave envelop in front of the PCM buffer, so that the file can be played back with startPlayerFromBuffer().

Implementation

Future<Uint8List> pcmToWaveBuffer({
  required Uint8List inputBuffer,
  required Pcm codec,
}) async {
  if (codec.audioFormat != AudioFormat.raw || codec.sampleRate == null) {
    throw Exception('Codec must be raw PCM');
  }

  var size = inputBuffer.length;
  var header = WaveHeader(
    WaveHeader.formatPCM,
    codec.nbrChannels(),
    codec.sampleRate!,
    16,
    size, // total number of bytes
  );

  var buffer = <int>[];
  StreamController controller = StreamController<List<int>>();
  var sink = controller.sink as StreamSink<List<int>>;
  var stream = controller.stream as Stream<List<int>>;
  stream.listen((e) {
    var x = e.toList();
    buffer.addAll(x);
  });
  header.write(sink);
  sink.add(inputBuffer);
  await sink.close();
  await controller.close();
  return Uint8List.fromList(buffer);
}