mbaudio

    Unified wasm-first audio parsing API for MoonBit

    audio
    decoder
    wasm
    wav
    flac
    mp3
    ogg
    opus
    Download zip
    Author
    Version
    0.0.1
    License
    Apache-2.0
    Last updated
    7 hours ago
    Downloads
    7

    #OrisGo/mbaudio

    A wasm-first, backend-agnostic audio parsing API for MoonBit. Existing pure MoonBit decoders are wrapped behind one AudioBuffer / AudioError model, with buffered, streaming, and metadata entry points.

    #Packages

    PackagePurpose
    OrisGo/mbaudioCore types, sniff, buffered AudioDecoder
    OrisGo/mbaudio/backend/moonaudioWAV / AIFF / AU / native FLAC adapter
    OrisGo/mbaudio/backend/mp3MP3 adapter
    OrisGo/mbaudio/backend/vorbisOgg Vorbis adapter
    OrisGo/mbaudio/backend/opusOgg Opus adapter (CELT-only mono)
    OrisGo/mbaudio/backend/ffmpegOptional broad backend: ADTS AAC, AAC in M4A/MP4, ALAC, Ogg FLAC, multichannel Opus
    OrisGo/mbaudio/metadataUnified tag reader backed by moontag
    OrisGo/mbaudio/allLightweight auto-detect, buffered and streaming decode
    OrisGo/mbaudio/fullall plus an FFmpeg fallback

    #Supported formats

    #Lightweight all

    FormatBackendNotes
    WAV, AIFF/AIFC, AU, FLACSakuraqwq1/moonaudioPCM/float, μ-law/A-law, WAVE_FORMAT_EXTENSIBLE, RIFX/RF64; native FLAC only
    MP3enanandesu/mp3MPEG-1/2/2.5 Layer III
    Ogg VorbisLL728/moonvorbisOgg container + Vorbis
    Ogg OpusLL728/moonopusCELT-only, mono, fullband config 28–31

    #Optional full

    FormatHow
    AAC in raw ADTS (.aac)libavcodec ADTS splitter + AAC-LC decoder
    AAC in M4A / MP4libavformat facade (Mov demuxer)
    ALAC in M4A / MOVlibavformat.MediaFile packets + libavcodec ALAC decoder
    Ogg FLACav_ogg_flac_open reassembled to native FLAC + FLAC decoder
    Stereo / multichannel Ogg Opuslibavformat facade fallback; the lightweight Opus backend is mono-only

    full tries the lightweight backend first and falls back to FFmpeg when the lighter decoder cannot handle the stream. Unknown magic bytes go straight to FFmpeg. The generic facade wires AAC, Opus, and 16-bit PCM; ADTS AAC, ALAC, and Ogg FLAC use dedicated paths in backend/ffmpeg. sniff reports Ogg FLAC as OggFlac; the lightweight all package returns UnsupportedFormat for it, while full decodes it through the dedicated path.

    The optional full package depends on milkbobo/ffmpeg-moonbit (LGPL-2.1-or-later), which carries a patent notice for AAC/H.264/HEVC. Evaluate this dependency before commercial distribution. The lightweight all package does not import or link the FFmpeg backend.

    #Buffered decode

    Import only the backend you need, or use all / full for auto-detection:

    ///|
    // moon.pkg
    import {
    "OrisGo/mbaudio",
    "OrisGo/mbaudio/all", // or "OrisGo/mbaudio/full"
    }

    ///|
    fn show_audio(bytes : Bytes) -> Unit {
    match @all.decode(bytes) {
    Ok(audio) =>
    println(
    "\{audio.sample_rate} Hz, \{audio.channels} ch, \{audio.frames()} frames",
    )
    Err(error) => println(error.message())
    }
    }

    Swap @all for @full to enable the FFmpeg fallback. Inspect the format without decoding:

    match @mbaudio.sniff(bytes) {
    Some(format) => println(format.to_name())
    None => println("unrecognised audio format")
    }

    #Unified decoder

    @all.decoder and @full.decoder return an AudioDecoder with the same interface for every format:

    ///|
    fn read_in_chunks(bytes : Bytes) -> Unit {
    match @all.decoder(bytes) {
    Ok(decoder) => {
    let info = decoder.info()
    println(
    "\{info.sample_rate} Hz, \{info.channels} ch, \{info.frames} frames",
    )
    while !decoder.is_done() {
    match decoder.next(1024) {
    Some(samples) =>
    // Interleaved f32 samples for up to 1024 frames.
    ignore(samples)
    None => break
    }
    }
    }
    Err(error) => println(error.message())
    }
    }

    AudioDecoder is buffered: opening it decodes the whole input once, then next(max_frames) walks a frame cursor over the PCM. seek(frame), reset(), position(), remaining_frames(), and next_buffer(max_frames) are also available.

    #Streaming decoder

    @all.streaming_decoder is a push-based decoder for code that receives compressed bytes incrementally:

    ///|
    fn stream_audio(chunks : Array[Bytes]) -> Unit {
    let decoder = @all.streaming_decoder(None) // or Some(format)
    for chunk in chunks {
    match decoder.push(chunk) {
    Ok(_) => ()
    Err(error) => println(error.message())
    }
    match decoder.next(1024) {
    Ok(Some(samples)) =>
    // Interleaved f32 frames; Ok(Some([])) means "need more input".
    ignore(samples)
    Ok(None) => break
    Err(error) => println(error.message())
    }
    }
    match decoder.finish() {
    Ok(_) => ()
    Err(error) => println(error.message())
    }
    }

    • True incremental decoding: MP3 and Ogg Vorbis.
    • Buffered fallback: WAV, AIFF, AU, native FLAC, and Ogg Opus accumulate input and decode on finish; they are not low-memory streaming.
    • next returns Ok(Some([])) when no frame is currently available, Ok(None) after finish when fully drained, and typed errors for malformed or truncated streams.
    • info().frames and duration_seconds are 0 for truly streamed formats; total length is unknown until the end. format() may be None while sniffing is undecided.

    #Metadata

    The optional metadata package reads ID3v2/APEv2, Vorbis Comment, and MP4 ilst tags through cp15695540483/moontag:

    ///|
    // moon.pkg: "OrisGo/mbaudio/metadata" @metadata
    fn show_tags(bytes : Bytes) -> Unit {
    match @metadata.read(bytes) {
    Ok(metadata) => {
    match metadata.title {
    Some(title) => println(title)
    None => println("untitled")
    }
    if metadata.has_cover {
    println("cover art present")
    } else {
    println("no cover art")
    }
    }
    Err(error) => println(error.message())
    }
    }

    TrackMetadata exposes format, title, artist, album, comment, date, genre, track, and has_cover. Untagged but recognised files return Ok with empty fields. moontag reports a single Ogg format, which maps to OggVorbis; use @mbaudio.sniff when the exact Ogg codec matters.

    #Canonical sample format

    AudioBuffer stores interleaved f32 samples normalised to [-1.0, 1.0]. Frame f, channel c is at samples[f * channels + c]. This is the common denominator of the wasm-compatible backends; 32-bit integer PCM may lose its lowest bits when converted to f32.

    #Verification

    moon test moon test --target wasm moon test --target wasm-gc moon build --target wasm

    The wasm compatibility matrix for the ecosystem libraries lives in docs/format-support.md.

    AudioBuffer

    pub struct AudioBuffer {
    sample_rate : Int
    channels : Int
    samples : Array[Float]
    }

    Canonical decoded audio.

    Samples are interleaved and normalised to [-1.0, 1.0]: frame f, channel c lives at samples[f * channels + c]. Float (f32) is the common denominator of the wasm-compatible decoders in this module; 32-bit integer PCM can lose its lowest bits when converted, which is documented per backend rather than silently pretending to be lossless.

    AudioBuffer::duration_seconds

    fn AudioBuffer::duration_seconds(self : AudioBuffer) -> Double

    Duration in seconds, or 0.0 when the buffer has no sample rate.

    AudioBuffer::empty

    fn AudioBuffer::empty() -> AudioBuffer

    An empty buffer with no format information.

    AudioBuffer::frames

    fn AudioBuffer::frames(self : AudioBuffer) -> Int

    Number of sample frames (samples per channel).

    AudioBuffer::new

    fn AudioBuffer::new(sample_rate : Int, channels : Int, samples : Array[Float]) -> AudioBuffer

    Build an audio buffer from interleaved samples.

    AudioDecoder

    pub struct AudioDecoder {
    // private fields
    }

    A format-agnostic, pull-based decoder over an already decoded buffer.

    Every backend produces an AudioBuffer; this type gives all of them the same info() / next(max_frames) / seek() interface. The first version buffers the whole input. True streaming adapters can be added behind the same methods once a backend exposes incremental PCM.

    AudioDecoder::info

    fn AudioDecoder::info(self : AudioDecoder) -> AudioInfo

    Stream information.

    AudioDecoder::is_done

    fn AudioDecoder::is_done(self : AudioDecoder) -> Bool

    Whether the cursor has reached the end.

    AudioDecoder::new

    fn AudioDecoder::new(format : AudioFormat?, buffer : AudioBuffer) -> AudioDecoder

    Build a decoder over a decoded buffer.

    AudioDecoder::next

    fn AudioDecoder::next(self : AudioDecoder, max_frames : Int) -> Array[Float]?

    Return at most max_frames interleaved samples and advance the cursor.

    None means the cursor is at the end, or max_frames <= 0.

    AudioDecoder::next_buffer

    fn AudioDecoder::next_buffer(self : AudioDecoder, max_frames : Int) -> AudioBuffer?

    Like [AudioDecoder::next], but wraps the chunk in an AudioBuffer.

    AudioDecoder::position

    fn AudioDecoder::position(self : AudioDecoder) -> Int

    Current position in frames.

    AudioDecoder::remaining_frames

    fn AudioDecoder::remaining_frames(self : AudioDecoder) -> Int

    Frames left before the end.

    AudioDecoder::reset

    fn AudioDecoder::reset(self : AudioDecoder) -> Unit

    Rewind to the first frame.

    AudioDecoder::seek

    fn AudioDecoder::seek(self : AudioDecoder, frame : Int) -> Unit

    Move the cursor to frame, clamped to [0, frames].

    AudioError

    pub(all) enum AudioError {
    UnsupportedFormat(AudioFormat)
    UnknownFormat
    InvalidData(String)
    DecodeFailed(String)
    } derive(Eq,
    Debug
    )

    Failure modes shared by every backend.

    AudioError::message

    fn AudioError::message(self : AudioError) -> String

    Human-readable explanation of an [AudioError].

    AudioFormat

    pub(all) enum AudioFormat {
    Wav
    Aiff
    Au
    Flac
    Mp3
    OggVorbis
    OggOpus
    OggFlac
    Aac
    Mp4
    } derive(Eq,
    Debug
    )

    Audio container or codec format recognised by [sniff].

    The enum deliberately separates containers that carry a single codec (Wav, Aiff, Au, Flac, Mp3) from Ogg streams, because Ogg needs a second sniffing step to tell Vorbis, Opus, and FLAC apart. Mp4 is reported for ISO-BMFF containers such as .m4a; the codec still has to be inspected by the backend that decodes it.

    AudioFormat::extension

    fn AudioFormat::extension(self : AudioFormat) -> String

    Conventional file extension for an [AudioFormat].

    AudioFormat::to_name

    fn AudioFormat::to_name(self : AudioFormat) -> String

    Stable lowercase name for an [AudioFormat].

    AudioInfo

    pub struct AudioInfo {
    format : AudioFormat?
    sample_rate : Int
    channels : Int
    frames : Int
    duration_seconds : Double
    } derive(Eq,
    Debug
    )

    Static description of a decoded stream.

    AudioInfo::from_buffer

    fn AudioInfo::from_buffer(format : AudioFormat?, buffer : AudioBuffer) -> AudioInfo

    Build stream information from a decoded buffer.

    sniff

    fn sniff(bytes : Bytes) -> AudioFormat?

    Detect a supported audio format from its leading bytes.

    This is a pure magic-number check: it never allocates, never reads beyond the input, and is safe on truncated files. Ogg streams additionally look for OpusHead, the RFC 5334 \x7fFLAC mapping marker, or vorbis in the first 256 bytes.

    Source Files