I am getting Uint8List from recorder plugin for Android and iOS both. I want to write the data in a local playable audio file whenever I am getting the data in my stream subscription of a mic. Is there any possible way to write the data?
Currently, I am storing the data like
recordedFile.writeAsBytesSync(recordedData, flush: true);
It's writing data to file but not able to play from the file storage. But also if I read the same file and gives it's bytes to plugin it's playing the same buffer.
I have added a WAVE/RIFF Header before writing my bytes into the file which gives the metadata to bytes and file.
I have 16 BIT PCM audio bytes with MONO channel in my stream. I am appending those bytes in a list of bytes when I am receiving the bytes.
List<int> recordedData = [];
recordedData.addAll(value);
Now I have all the recorded bytes on my list. After stopping my recorder I called the below function. Which takes all the data and sample rate for recorded. in my case its 44100.
await save(recordedData, 44100);
Future<void> save(List<int> data, int sampleRate) async {
File recordedFile = File("/storage/emulated/0/recordedFile.wav");
var channels = 1;
int byteRate = ((16 * sampleRate * channels) / 8).round();
var size = data.length;
var fileSize = size + 36;
Uint8List header = Uint8List.fromList([
// "RIFF"
82, 73, 70, 70,
fileSize & 0xff,
(fileSize >> 8) & 0xff,
(fileSize >> 16) & 0xff,
(fileSize >> 24) & 0xff,
// WAVE
87, 65, 86, 69,
// fmt
102, 109, 116, 32,
// fmt chunk size 16
16, 0, 0, 0,
// Type of format
1, 0,
// One channel
channels, 0,
// Sample rate
sampleRate & 0xff,
(sampleRate >> 8) & 0xff,
(sampleRate >> 16) & 0xff,
(sampleRate >> 24) & 0xff,
// Byte rate
byteRate & 0xff,
(byteRate >> 8) & 0xff,
(byteRate >> 16) & 0xff,
(byteRate >> 24) & 0xff,
// Uhm
((16 * channels) / 8).round(), 0,
// bitsize
16, 0,
// "data"
100, 97, 116, 97,
size & 0xff,
(size >> 8) & 0xff,
(size >> 16) & 0xff,
(size >> 24) & 0xff,
...data
]);
return recordedFile.writeAsBytesSync(header, flush: true);
}
And it's creating the playable WAV file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With