pcmToWaveBuffer method

Future<Uint8List> pcmToWaveBuffer({
  1. required Uint8List inputBuffer,
  2. int numChannels = 1,
  3. int sampleRate = 16000,
})

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().

Note: the parameters numChannels and sampleRate are mandatory, and must match the actual PCM data. See here a discussion about Raw PCM and WAVE file format.

Implementation

Future<Uint8List> pcmToWaveBuffer({
  required Uint8List inputBuffer,
  int numChannels = 1,
  int sampleRate = 16000,
  //int bitsPerSample,
}) async {
  var size = inputBuffer.length;
  var header = WaveHeader(
    WaveHeader.formatPCM,
    numChannels,
    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);
}