write method

Uint8List write()

Write the Wav to a byte buffer.

If your audio samples exceed [-1, 1], they will be clamped (unless you're using float32 or float64 format). If your channels are different lengths, they will be padded with zeros.

Implementation

Uint8List write() {
  // Calculate sizes etc.
  final bitsPerSample = format.bitsPerSample;
  final isFloat = format == WavFormat.float32 || format == WavFormat.float64;
  final bytesPerSample = bitsPerSample ~/ 8;
  final numChannels = channels.length;
  int numSamples = 0;
  for (final channel in channels) {
    if (channel.length > numSamples) numSamples = channel.length;
  }
  final bytesPerSampleAllChannels = bytesPerSample * numChannels;
  final dataSize = numSamples * bytesPerSampleAllChannels;
  final bytesPerSecond = bytesPerSampleAllChannels * samplesPerSecond;
  var fileSize = _kFileSizeWithoutData + roundUpToEven(dataSize);
  if (isFloat) {
    fileSize += _kFloatFmtExtraSize;
  }

  // Write metadata.
  final bytes = BytesWriter()
    ..writeString(_kStrRiff)
    ..writeUint32(fileSize)
    ..writeString(_kStrWave)
    ..writeString(_kStrFmt)
    ..writeUint32(_kFormatSize)
    ..writeUint16(isFloat ? _kFloat : _kPCM)
    ..writeUint16(numChannels)
    ..writeUint32(samplesPerSecond)
    ..writeUint32(bytesPerSecond)
    ..writeUint16(bytesPerSampleAllChannels)
    ..writeUint16(bitsPerSample);
  if (isFloat) {
    bytes
      ..writeString(_kStrFact)
      ..writeUint32(_kFactSize)
      ..writeUint32(numSamples);
  }
  bytes
    ..writeString(_kStrData)
    ..writeUint32(dataSize);

  // Write samples.
  final writeSample = bytes.getSampleWriter(format);
  for (int i = 0; i < numSamples; ++i) {
    for (int j = 0; j < numChannels; ++j) {
      double sample = i < channels[j].length ? channels[j][i] : 0;
      writeSample(sample);
    }
  }
  if (dataSize % 2 != 0) {
    bytes.writeUint8(0);
  }
  return bytes.takeBytes();
}