pcmToWaveBuffer
pcmToWaveBuffer method
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,
FSCodec.Codec codec = FSCodec.Codec.pcm16,
//int bitsPerSample,
}) async {
if (codec != FSCodec.Codec.pcm16 && codec != FSCodec.Codec.pcmFloat32) {
throw (Exception('Bad codec'));
}
var size = inputBuffer.length;
var header = WaveHeader(
codec == FSCodec.Codec.pcm16
? WaveHeader.formatInt
: WaveHeader.formatFloat,
numChannels,
sampleRate,
codec == FSCodec.Codec.pcm16
? 16
: 32, // 16 bits per sample for int16. 32 bits per sample for float32
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);
}