React Native and WAV export
Play the same sounds in React Native with the built-in Expo module, or render them to WAV files for any native app or video soundtrack.
React Native
@bloxwap/sfx runs in React Native with the same import and the same API as the web:
npx expo install @bloxwap/sfx
npx expo prebuild # or rebuild your dev client / EAS buildimport { play, preload, setVolume } from '@bloxwap/sfx';
preload(['press', 'release', 'tick', 'success']); // optional, see below
play('success');
play('payout', { volume: 0.35, pan: -0.2 });
// A tap: release 90 ms after press, scheduled natively.
play('press');
play('release', { delay: 0.09 });Metro picks the native entry through the package's react-native export condition, so shared code that imports @bloxwap/sfx works on web, iOS, and Android. You can also import @bloxwap/sfx/native explicitly.
How it plays
Native platforms have no Web Audio, so the package bakes every recipe to PCM at build time (48 kHz, 16-bit, mono unless the recipe pans) and ships a small Expo module that plays it. The files are rendered in Chromium from the same recipes the web synthesizes, and a test fails if a recipe changes without a re-bake, so the two platforms can't drift.
- iOS: one
AVAudioEngine. Each sound is decoded once into a float32 buffer and played on a pooledAVAudioPlayerNode. The engine pauses after 3 s of silence, and decoded buffers are dropped on a memory warning and reload on their next play. - Android: one
SoundPoolreading the sounds straight from the APK, with noExoPlayeror media session. - Every play is one synchronous native call on the JS thread. There is no seek, promise, or bridge round trip.
- Memory grows only with the sounds you use: a sound is decoded on its first play, or ahead of time by
preload(). The whole catalog is about 2 MB decoded on iOS. Passpreload()only the sounds you use to keep it smaller.
Platform behavior
- On iOS the audio session is set to ambient: it respects the silent switch and mixes with other apps' audio. Apps that also play media can pass
configure({ audioSession: 'manual' })before the first sound and manage the session themselves. Android's SoundPool never takes audio focus. - Nothing plays or keeps sounding while the app is in the background.
maxVoicesdefaults to 16 on native, andconfigure()applies it when the engine starts, so call it before the first sound (or afterdispose()).minInterval, volumes, categories,delay,pan, andsignalwork as on the web.rateworks from 0.25 to 4 on iOS and from 0.5 to 2 on Android.- No user gesture is needed, so
forcehas no effect. - Web-only APIs have inert stand-ins, so shared code still runs:
bind()returns a no-op,renderTo()returnsfalse,renderBuffer()andgetOutput()returnnull, and sounds registered withdefine()are validated but stay silent. - Expo Go, Jest, and binaries built before the package was installed have no native module. There every call is a silent no-op.
The native module needs a development build (Expo SDK 52 or later, iOS 15.1+); it does not run in Expo Go.
WAV export for other native apps
For SwiftUI, Kotlin, desktop, or game engines, render the recipes offline to WAV files instead, so every app sounds identical.
The sfx-wav CLI
The package ships an sfx-wav command. It renders with node-web-audio-api, an optional peer dependency, so install both:
npm install --save-dev @bloxwap/sfx node-web-audio-api
npx sfx-wav --out assets/sfx --sounds tick,toggle,success,errorThat writes one file per sound and prints a summary:
file duration ms peak dBFS
tick.wav 119 -17.1
toggle.wav 145 -16.5
success.wav 1004 -15.5
error.wav 344 -15.0
Wrote 4 files to /path/to/assets/sfxEach file lasts the sound's duration() plus a 0.1 s tail. The peak is measured on what is written, after any mono downmix, and reads -inf for silence. Sounds with noise layers start from a random point in the noise, so their peak can vary by several dB between runs (tick and tap by 5 dB or more). Treat it as a rough check, not a level reference.
| Flag | Default | Meaning |
|---|---|---|
--out <dir> | ./sfx | Output directory, created if missing. |
--sounds <a,b,c> | all built-in sounds | Sounds to render. Pass "" to render only --combo files. |
--sample-rate <hz> | 48000 | A whole number from 3000 to 768000. |
--bit-depth <16|24|32> | 16 | 16- or 24-bit integer PCM, or 32-bit float. |
--channels <1|2> | 2 | Mono averages both channels. |
--trim | off | Cuts the tail below -60 dB, keeping 20 ms. |
--combo <name=sound@s,...> | none | Mixes sounds into one file. Repeatable. |
-h, --help | Prints usage and the sound list. |
The command exits with 0 on success, 1 if rendering or writing fails or node-web-audio-api can't be loaded, and 2 for bad flags. Flags are checked before any audio is rendered, so a typo such as an unknown sound writes nothing.
Combos: the tap sound
On the web, a button plays press on pointer down and release on pointer up. A native tap handler often fires once, so bake both into one file with --combo:
npx sfx-wav --out assets/sfx --sounds "" --combo tap=press@0,release@0.09tap.wav holds press at 0 s and release at 90 ms. Each part is sound@seconds; the offset defaults to 0 and can be up to 10. The name before = becomes the file name, so it may only use letters, digits, _, -, and ., and can't start with a dot. Two outputs with the same name are an error, and names are compared ignoring case, because macOS and Windows file systems would write Tap.wav and tap.wav to the same file.
This is the same as play('press'); play('release', { delay: 0.09 }) on the web. See Sound design.
Trimming and formats
Recipes leave room for their echo to decay, so the end of a file is often near-silent. --trim cuts everything after the last sample within 60 dB of the peak and keeps 20 ms after it. success.wav drops from 1004 ms to about 570 ms, and tap.wav from 247 ms to about 220 ms. It never trims the start, so timing stays exact.
Pick the format your platform prefers:
- 16-bit is the smallest and plays everywhere. It's the default.
- 24-bit keeps more detail in quiet tails, if you plan to process the files further.
- 32-bit float keeps the render's full precision. Some older players and decoders don't support it.
Use --channels 1 if your app only plays mono. Many sounds pan their layers, so mono loses that width. Set --sample-rate to your audio engine's output rate to skip resampling at runtime.
From code
The WAV encoder lives at @bloxwap/sfx/wav, a separate entry point with no dependencies. It runs in browsers and Node, and takes any AudioBuffer. In a browser, pair it with renderBuffer() to offer a download:
import { renderBuffer } from '@bloxwap/sfx';
import { encodeWav, trimSilence } from '@bloxwap/sfx/wav';
const buffer = await renderBuffer('success', { sampleRate: 44100 });
if (buffer) {
const wav = encodeWav(trimSilence(buffer), { bitDepth: 24 });
const url = URL.createObjectURL(new Blob([wav], { type: 'audio/wav' }));
Object.assign(document.createElement('a'), { href: url, download: 'success.wav' }).click();
URL.revokeObjectURL(url);
}renderBuffer() needs a global OfflineAudioContext. Node doesn't have one, so in a Node script use node-web-audio-api and renderTo(), which takes the context directly:
import { OfflineAudioContext } from 'node-web-audio-api';
import { writeFile } from 'node:fs/promises';
import { duration, renderTo } from '@bloxwap/sfx';
import { encodeWav } from '@bloxwap/sfx/wav';
const sampleRate = 48000;
const ctx = new OfflineAudioContext(2, Math.ceil((duration('payout') + 0.1) * sampleRate), sampleRate);
renderTo(ctx, 'payout');
await writeFile('payout.wav', new Uint8Array(encodeWav(await ctx.startRendering())));Bake a soundtrack into a video
Screen recordings and product videos often need interface sounds on exact frames. Render them with renderTo() into an OfflineAudioContext as long as the video, then add the WAV as the audio track.
delay is capped at 10 s. For longer timelines, pause the render near each cue with suspend() and schedule from there:
import { renderTo } from '@bloxwap/sfx';
import { encodeWav } from '@bloxwap/sfx/wav';
// Cues from your edit, in seconds.
const cues = [
{ at: 0.4, sound: 'press' },
{ at: 0.49, sound: 'release' },
{ at: 6.2, sound: 'success' },
{ at: 14.8, sound: 'payout' },
] as const;
const sampleRate = 48000;
const ctx = new OfflineAudioContext(2, Math.ceil(18 * sampleRate), sampleRate); // an 18 s video
// Group cues into 5 s windows, well inside the 10 s delay cap.
for (const [start, group] of Map.groupBy(cues, (cue) => Math.floor(cue.at / 5) * 5)) {
const schedule = () => {
for (const cue of group) renderTo(ctx, cue.sound, { delay: cue.at - ctx.currentTime });
};
if (start === 0) schedule();
else ctx.suspend(start).then(() => { schedule(); return ctx.resume(); });
}
const wav = encodeWav(await ctx.startRendering());Then mux it with the video, for example with ffmpeg:
ffmpeg -i video.mp4 -i soundtrack.wav -map 0:v -map 1:a -c:v copy -c:a aac -shortest out.mp4renderTo() bypasses the engine, so the master volume and limiter don't apply. If cues overlap and clip, lower their volume, or pass a destination that runs through your own DynamicsCompressorNode.
Approved HIG asset subset
From this repository (Node 24, pinned lockfile), run npm ci && npm run export:hig.
It exports only tick, toggle, success, error to packages/sfx/assets/hig:
48 kHz, mono, 16-bit PCM, -60 dB tail trim plus 20 ms padding. The manifest records
package/renderer versions, exact flags, full source recipes and their hashes, artifact hashes,
frame durations, peak and RMS levels, and the versioned semantic mapping. Noise layers use
random samples; repeated exports can change hashes, levels and trim durations. Regeneration
validates finite trailing envelopes, audible levels below full scale, and bounded duration;
review the versioned artifacts rather than expecting cross-platform byte identity.
The package includes this subset under @bloxwap/sfx/assets/hig/*. Metro/native hosts should
require WAV assets directly and read the manifest; they must not import the SFX synthesis engine,
CLI or optional node-web-audio-api renderer. Keep one asset owner and reuse the subset.
HIG's native audio adapter owns preload/cache, rate limits, mute/volume, players and disposal,
background/interruption/audio-session/silent-mode behavior and missing asset handling.
SDK compilation and lifecycle tests do not certify device latency, silent mode, interruptions or background transitions. Verify those behaviors in an iPhone/Android development build.
Playback lifecycle and validation
Abort subscriptions are released by native voice-end notifications, including cancellation, stealing, backgrounding and disposal. iOS uses AVAudioPlayerNode completion; SoundPool has no completion callback, so Android schedules retirement from the successful native start using the full PCM length and actual clamped rate. Decode time is not subtracted from a voice's lifetime. Master-volume changes also update active Android streams.
Native PCM is baked at twice nominal gain with verified headroom, and both native mixers divide the requested 0–2 gain by two. The native files are engine assets; the assets/hig exports retain nominal gain for external players. Asset manifests fingerprint the renderer and encoder as well as the recipes.
Run npm run test:native from the repository root to type-check iOS and Android engines against their SDKs and run the Android lifecycle tests. It requires Xcode and Android Studio on macOS, or explicit SFX_KOTLINC, SFX_JAVA, and ANDROID_HOME paths for Android. Physical device playback is still a separate check.