toWavBytes static method

Uint8List toWavBytes({
  1. required Uint8List pcmData,
  2. int sampleRate = 8000,
  3. int bitsPerSample = 16,
  4. int channels = 1,
})

Create the contents of a WAV files corresponding to the provided pcmData

Implementation

static Uint8List toWavBytes({required Uint8List pcmData, int sampleRate = 8000, int bitsPerSample = 16, int channels = 1}) {
  int byteRate = sampleRate * channels * bitsPerSample ~/ 8;
  int dataSize = pcmData.length;
  int fileSize = 36 + dataSize;

  // WAV Header
  List<int> header = [
    // "RIFF" chunk descriptor
    0x52, 0x49, 0x46, 0x46, // "RIFF" in ASCII
    fileSize & 0xff, (fileSize >> 8) & 0xff, (fileSize >> 16) & 0xff, (fileSize >> 24) & 0xff, // Chunk size
    0x57, 0x41, 0x56, 0x45, // "WAVE" in ASCII

    // "fmt " sub-chunk
    0x66, 0x6d, 0x74, 0x20, // "fmt " in ASCII
    16, 0x00, 0x00, 0x00,   // Subchunk1Size (16 for PCM)
    0x01, 0x00,             // AudioFormat (1 for PCM)
    channels & 0xff, 0x00,   // NumChannels
    sampleRate & 0xff, (sampleRate >> 8) & 0xff, (sampleRate >> 16) & 0xff, (sampleRate >> 24) & 0xff, // SampleRate
    byteRate & 0xff, (byteRate >> 8) & 0xff, (byteRate >> 16) & 0xff, (byteRate >> 24) & 0xff, // ByteRate
    (channels * bitsPerSample ~/ 8) & 0xff, 0x00, // BlockAlign
    bitsPerSample & 0xff, 0x00, // BitsPerSample

    // "data" sub-chunk
    0x64, 0x61, 0x74, 0x61, // "data" in ASCII
    dataSize & 0xff, (dataSize >> 8) & 0xff, (dataSize >> 16) & 0xff, (dataSize >> 24) & 0xff, // Subchunk2Size
  ];

  // Combine header and PCM data
  return Uint8List.fromList(header + pcmData);
}