Copy to Clipboardpnpm dlx shadcn@latest add @audio-ui/engine-files
Copy to Clipboardimport { decodeAudioChannels, decodeAudioSamples, downloadFile, encodeAudio, CHANNEL_LAYOUTS, /* … */ } from "@/lib/engine/files";
| Export | Kind | What it is |
|---|---|---|
decodeAudioChannels | function | Decodes raw audio bytes, such as file.arrayBuffer(), into every channel's PCM samples at the context's sample rate, ready for computePeaks. |
decodeAudioSamples | function | Decodes raw audio bytes into one channel's PCM samples, ready for downsampleWaveform: decodeAudioChannels, then the channel asked for, or the last there is. |
AudioFileFormat | type | The formats encodeAudio writes. |
downloadFile | function | Saves a file through the browser's downloads, named name. |
EncodeAudioOptions | interface | What encodeAudio writes: the format, its bit depth or bitrate, the channels' sample rate, and a callback for its progress. |
encodeAudio | function | Encodes channels of samples, from -1 to 1, as a file. |
CHANNEL_LAYOUTS | const | The layouts a sound can be mixed to: one channel, two, or the surround layouts of film. |
ChannelLayout | type | |
LAYOUT_CHANNELS | const | How many channels a layout has. |
mixChannels | function | The 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. |
padChannels | function | Silence, in samples, added before and after the sound. |
repeatChannels | function | The sound played times times in a row, the first included. |
resampleChannels | function | Every 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. |
reverseChannels | function | Every channel played backwards: the end first. |
downloadMidiFile | function | Saves the notes as a .mid file, named filename. |
MIDI_FILE_ACCEPT | const | What a file input or a drop zone accepts as a MIDI file. |
MidiFileGrid | interface | The grid notes are read onto: steps a quarter note, the clip's length in steps, and the pitch and tempo ranges it takes. |
readMidiFile | function | Reads a MIDI file's notes onto a grid of steps, with the file's own tempo (clamped to the BPM range). |
readMidiFileParts | function | Reads 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. |
ScoreNote | interface | A note of a score in beats: where it starts and how long it lasts, in quarter notes. |
ScorePart | interface | One part of a score: its name, whether it is drums, and its notes in beats. |
writeMidiFile | function | The notes as a Standard MIDI File, the inverse of readMidiFile. |
downloadMusicXmlFile | function | Saves the notes as a .musicxml file, named filename. |
MUSICXML_FILE_ACCEPT | const | What a file input or a drop zone accepts as a MusicXML file: a score, or one compressed as .mxl. |
MusicXmlFileGrid | interface | The grid notes are read onto: steps a quarter note, the clip's length in steps, and the pitch and tempo ranges it takes. |
readMusicXmlFile | function | Reads 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. |
readMusicXmlFileParts | function | Reads 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. |
writeMusicXmlFile | function | The 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_METHODS | const | How 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. |
DitherMethod | type | |
ditherChannels | function | Every 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. |
FilterType | type | A filter's shape: what it lets through, 12 dB an octave. |
filterChannels | function | Every 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). |
gainChannels | function | Every channel, db louder or quieter. |
NormalizeTarget | type | What a sound is normalized to: its loudest sample, or its integrated loudness held under a true-peak ceiling. |
normalizeChannels | function | The 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). |
panChannels | function | A sound's balance: -1 is all left, 1 all right, 0 as it is. |
SHIFT_METHODS | const | How a pitch is shifted: let the library choose from the sound (auto), or a method by name. |
ShiftMethod | type | |
STRETCH_METHODS | const | The 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). |
StretchMethod | type | |
shiftChannels | function | Every channel semitones higher or lower, its length unchanged. |
speedChannels | function | The 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. |
stretchChannels | function | Every 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.
Copy to Clipboardimport { 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.
Copy to Clipboardimport { 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.
Copy to Clipboardimport { 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.
Copy to Clipboardimport { 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.