decodeAudioBytes function

AudioData decodeAudioBytes(
  1. Uint8List bytes, {
  2. AudioFormat? format,
})

Decodes in-memory audio bytes into mono AudioData, entirely in Dart.

This is the entry point for converting audio loaded at runtime — a user-picked or uploaded file, a network download, a bundled asset — with no file path, no dart:io, and no ffmpeg. It works on every platform, including Flutter web.

WAV and MP3 are supported. When format is omitted it is detected from the leading bytes. Throws an AudioDecodeException when the bytes are not a supported format or cannot be decoded.

final bytes = await pickedFile.readAsBytes(); // Uint8List
final audio = decodeAudioBytes(bytes);
final pattern = const AudioAnalyzer().analyze(audio);
final ahap = pattern.toAhap();

Implementation

AudioData decodeAudioBytes(Uint8List bytes, {AudioFormat? format}) {
  final resolved = format ?? _sniffFormat(bytes);
  if (resolved == null) {
    throw AudioDecodeException(
      'Unrecognized audio format. Only WAV and MP3 bytes can be decoded '
      'in-memory; pass the `format` argument if the data has no recognizable '
      'header, or convert other formats to WAV first.',
    );
  }
  switch (resolved) {
    case AudioFormat.wav:
      return _decodeWavBytes(bytes);
    case AudioFormat.mp3:
      return decodeMp3Bytes(bytes);
  }
}