readRawAudio function

List<Float64List> readRawAudio(
  1. Uint8List bytes,
  2. int numChannels,
  3. WavFormat format
)

Reads raw audio samples from a byte buffer.

Raw audio files are essentially Wav files without a format header. The format header tells the reader important metadata like the number of channels and the sample format. As the input won't contain that metadata, the format and number of channels must be must be known by the user, and specified as arguments.

Implementation

List<Float64List> readRawAudio(
  Uint8List bytes,
  int numChannels,
  WavFormat format,
) {
  // Make sure the file size is consistent with the arguments
  final bytesPerSample = format.bytesPerSample;
  if (bytes.length % (bytesPerSample * numChannels) != 0) {
    throw Exception('Unexpected file size. File size should be a multiple of '
        '${bytesPerSample * numChannels} bytes for '
        '${format.bitsPerSample} bit $numChannels channel audio');
  }

  // Calculate the number of samples
  final numSamples = bytes.length ~/ (bytesPerSample * numChannels);

  // Initialise the channels
  final channels = <Float64List>[];
  for (int i = 0; i < numChannels; ++i) {
    channels.add(Float64List(numSamples));
  }

  // Read samples.
  final byteReader = BytesReader(bytes);
  final readSample = byteReader.getSampleReader(format);
  for (int i = 0; i < numSamples; ++i) {
    for (int j = 0; j < numChannels; ++j) {
      channels[j][i] = readSample();
    }
  }
  return channels;
}