LabDAW

files

Files: an audio file decoded into samples at a context's rate, sound written to WAV, FLAC or MP3, notes read from and written to a MIDI file, and a score read from and written to MusicXML.

pnpm dlx shadcn@latest add @audio-ui/engine-files
import { decodeAudioChannels, decodeAudioSamples, downloadFile, encodeAudio, CHANNEL_LAYOUTS, /* … */ } from "@/lib/engine/files";
Used byaudio-export, sound-operations
audio.js@audio/biquad, @audio/decode-aiff, @audio/decode-caf, @audio/decode-mp4, @audio/effect-noiseshaper, @audio/encode, @audio/midi-parse, @audio/midi-write, @audio/musicxml, @audio/resample-sinc, @audio/shift, @audio/stretch
ExportKindWhat it is
decodeAudioChannelsfunctionDecodes raw audio bytes, such as file.arrayBuffer(), into every channel's PCM samples at the context's sample rate, ready for computePeaks.
decodeAudioSamplesfunctionDecodes raw audio bytes into one channel's PCM samples, ready for downsampleWaveform: decodeAudioChannels, then the channel asked for, or the last there is.
AudioFileFormattypeThe formats encodeAudio writes.
downloadFilefunctionSaves a file through the browser's downloads, named name.
EncodeAudioOptionsinterfaceWhat encodeAudio writes: the format, its bit depth or bitrate, the channels' sample rate, and a callback for its progress.
encodeAudiofunctionEncodes channels of samples, from -1 to 1, as a file.
CHANNEL_LAYOUTSconstThe layouts a sound can be mixed to: one channel, two, or the surround layouts of film.
ChannelLayouttype
LAYOUT_CHANNELSconstHow many channels a layout has.
mixChannelsfunctionThe same sound in another layout: a down-mix folds the centre and the surrounds into the sides at -3 dB and drops the low-frequency channel, and scales so the sum stays at full scale at most; an up-mix keeps the sides where they are, spreads them to the surrounds at -6 dB and leaves the centre and the low-frequency channel silent.
padChannelsfunctionSilence, in samples, added before and after the sound.
repeatChannelsfunctionThe sound played times times in a row, the first included.
resampleChannelsfunctionEvery channel at another sample rate, by a windowed sinc: the same sound, heard as a converter of that rate would give it, over channels.length arrays as long as the new rate needs.
reverseChannelsfunctionEvery channel played backwards: the end first.
downloadMidiFilefunctionSaves the notes as a .mid file, named filename.
MIDI_FILE_ACCEPTconstWhat a file input or a drop zone accepts as a MIDI file.
MidiFileGridinterfaceThe grid notes are read onto: steps a quarter note, the clip's length in steps, and the pitch and tempo ranges it takes.
readMidiFilefunctionReads a MIDI file's notes onto a grid of steps, with the file's own tempo (clamped to the BPM range).
readMidiFilePartsfunctionReads a MIDI file as parts, for a host that lays each on a track of its own: a part per track and channel, named after its track (and its channel, when a track holds several), its notes in beats as they were written, not quantized and not cut, at least a tick long, and the first program its channel plays.
ScoreNoteinterfaceA note of a score in beats: where it starts and how long it lasts, in quarter notes.
ScorePartinterfaceOne part of a score: its name, whether it is drums, and its notes in beats.
writeMidiFilefunctionThe notes as a Standard MIDI File, the inverse of readMidiFile.
downloadMusicXmlFilefunctionSaves the notes as a .musicxml file, named filename.
MUSICXML_FILE_ACCEPTconstWhat a file input or a drop zone accepts as a MusicXML file: a score, or one compressed as .mxl.
MusicXmlFileGridinterfaceThe grid notes are read onto: steps a quarter note, the clip's length in steps, and the pitch and tempo ranges it takes.
readMusicXmlFilefunctionReads a MusicXML score's notes onto a grid of steps, with its first tempo (clamped to the BPM range), every part into the one clip.
readMusicXmlFilePartsfunctionReads a MusicXML score as parts, for a host that lays each on a track of its own: a part each, by its name, its notes in beats as they were written, through changes of tempo, not quantized and not cut.
writeMusicXmlFilefunctionThe notes as a MusicXML score, the inverse of readMusicXmlFile, for a notation app to open: on the grid they sit on, so nothing moves.
DITHER_METHODSconstHow a sound is brought to fewer bits: tpdf adds triangular noise one step wide before rounding, so the error is steady noise instead of distortion that follows the sound; shaped does the same with the error fed back through two delays, which moves the noise up toward the highest frequencies, where the ear hears it least; feedback rounds with the error fed back once (@audio/effect-noiseshaper), with no added noise.
DitherMethodtype
ditherChannelsfunctionEvery channel rounded to bits bits, by one of DITHER_METHODS, the way a sound is mastered to 16 bits or 8: as many steps as that depth has, and the error made into noise by the method.
FilterTypetypeA filter's shape: what it lets through, 12 dB an octave.
filterChannelsfunctionEvery channel through one filter of the cookbook, at frequency in hertz and a q (one over the square root of two by default, the flattest).
gainChannelsfunctionEvery channel, db louder or quieter.
NormalizeTargettypeWhat a sound is normalized to: its loudest sample, or its integrated loudness held under a true-peak ceiling.
normalizeChannelsfunctionThe sound, with one gain on every channel, so the balance between them stays: to a peak in dBFS, or to a loudness in LUFS as far as its true peak stays under ceiling (-1 dBTP by default).
panChannelsfunctionA sound's balance: -1 is all left, 1 all right, 0 as it is.
SHIFT_METHODSconstHow a pitch is shifted: let the library choose from the sound (auto), or a method by name.
ShiftMethodtype
STRETCH_METHODSconstThe ways a sound is stretched in time with its pitch kept, each with what it suits: a phase vocoder that keeps the attacks of drums (transient), one for general music (pvocLock), waveform overlap-add for speech made shorter (wsola) or longer (pvsola), a vocoder with the harmonic and percussive parts apart for full mixes (hybrid), and the extreme stretch of ambient textures (paulstretch).
StretchMethodtype
shiftChannelsfunctionEvery channel semitones higher or lower, its length unchanged.
speedChannelsfunctionThe sound played speed times as fast, its pitch moving with it as on a tape or a record: 2 is twice as fast and an octave up.
stretchChannelsfunctionEvery channel factor times as long, its pitch unchanged: 2 is twice as slow, 0.5 twice as fast.

Audio files

A file's audio as samples at the context's rate, one array per channel: what the browser decodes, and AIFF, CAF or Apple Lossless where it cannot (Chrome does not), with audio.js decoders.

import { decodeAudioChannels } from "@/lib/engine/files";

const channels = await decodeAudioChannels(ctx, await file.arrayBuffer());

The samples are at the context's sample rate, so they play as they are and computePeaks (from @/lib/engine/analysis) draws them. The waveform player and the arrangement decode dropped files this way.

Writing a file

Sound saved as a file: WAV (16 or 24-bit, or 32-bit float), FLAC or MP3 at a bitrate, encoded in chunks with its progress, from what an OfflineAudioContext rendered or a recording kept.

import { downloadFile, encodeAudio } from "@/lib/engine/files";

const file = await encodeAudio(channels, { bitDepth: 24, format: "wav", sampleRate, onProgress: (done) => setProgress(done) });
downloadFile(file, "mix.wav");

audio-export adds loudness normalization on top of it.

MIDI files

The midi-file library reads a .mid file onto the roll's steps and writes one back.

import { downloadMidiFile, MIDI_FILE_ACCEPT, readMidiFile } from "@/lib/engine/files";

<input
  accept={MIDI_FILE_ACCEPT}
  onChange={async (event) => {
    const file = event.target.files?.[0];
    if (file) {
      const { bpm, notes } = await readMidiFile(file, {
        duration: 64,
        maxPitch: 84,
        minPitch: 36,
      });
      setNotes(notes);
      setBpm(bpm);
    }
  }}
  type="file"
/>
<Button onClick={() => downloadMidiFile(notes, { bpm, filename: "clip.mid" })}>
  Export
</Button>

readMidiFile puts each note on the nearest step, at least one step long, drops the notes starting past duration, keeps the pitches between minPitch and maxPitch and returns the file's tempo, kept between minBpm and maxBpm (20 and 200 by default). It takes any File or Blob, so a drop works the same as an input. writeMidiFile goes the other way, at 480 ticks a quarter note, and leaves deactivated notes out; downloadMidiFile writes the file and saves it. A step is a sixteenth note: set stepsPerQuarter on both sides for another grid.

For a host that lays each part on a track of its own, such as a DAW, readMidiFileParts(file) reads a file as parts instead: one per track and channel, named after its track, with the General MIDI program it asks for and whether it is the drums of channel 10, its notes in beats as they were written, not quantized. The file is parsed by @audio/midi-parse.

MusicXML files

A MusicXML score onto a roll's steps, a part at a time, and notes back out as a score: what notation software reads and writes.

import { downloadMusicXmlFile, readMusicXmlFile } from "@/lib/engine/files";

const { bpm, notes } = await readMusicXmlFile(file, { duration: 64, maxPitch: 84, minPitch: 36 });
downloadMusicXmlFile(notes, { bpm, filename: "clip.musicxml" });

readMusicXmlFileParts gives each part on its own; writeMusicXmlFile the score as a string. For a .mid file, see midi-file.

Built by Ouest Labs, the source code is available on GitHub.
RSS