pcmToWave
pcmToWave method
Converts a raw PCM file to a WAVE file.
Add a WAVE header in front of the PCM data This verb is usefull to convert a Raw PCM file to a Wave file. It adds a Wave
envelop to the PCM file, so that the file can be played back with startPlayer()
.
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.
Parameters
- inputFile: is a file path to your input file
- outputFile: is a path to your output file
- numChannels: is the number of channels of your file
- sampleRate is the sample rate of your data
- codec is either FSCodec.Codec.pcm16 or FSCodec.Codec.pcmFloat32
Example
FlutterSoundHelper().pcmToWave (
inputFile: 'foo.pcm',
outputFile: 'foo.wav',
numChannels: 2 // stereo
samplerate: 48000,
codec: FSCodec.Codec.pcm16
);
Implementation
Future<void> pcmToWave({
required String inputFile,
required String outputFile,
int numChannels = 1,
int sampleRate = 16000,
FSCodec.Codec codec = FSCodec.Codec.pcm16,
}) async {
if (codec != FSCodec.Codec.pcm16 && codec != FSCodec.Codec.pcmFloat32) {
throw (Exception('Bad codec'));
}
var filIn = File(inputFile);
var filOut = File(outputFile);
var size = filIn.lengthSync();
logger.i(
'pcmToWave() : input = $inputFile, output = $outputFile, size = $size',
);
var sink = filOut.openWrite();
var header = WaveHeader(
codec == FSCodec.Codec.pcm16
? WaveHeader.formatInt
: WaveHeader.formatFloat,
numChannels = numChannels, //
sampleRate = sampleRate,
codec == FSCodec.Codec.pcm16 ? 16 : 32, // 16 bits per byte
size, // total number of bytes
);
header.write(sink);
await filIn.open();
var buffer = filIn.readAsBytesSync();
sink.add(buffer.toList());
await sink.close();
}