The ecosystem · audio
A sound from a handler, in one line
Audio.play!("/sounds/eat.wav") plays a sound when someone clicks, presses a key or wins a game: any file the browser can play (WAV, MP3, Ogg), from your site or any URL, with nothing to load in advance. The showcase's games play their sounds this way.
Audio is the module you call. Both halves of an app compile it, so a component that plays a sound type-checks on the server too. AudioPlayer is a plugin that serves the player, a small script every page loads. An app that plays no sound doesn't list it, and its pages load no player.
Installing it#
Name the package in your app's header, and list the plugin in your program:
app [program] { …, audio: "../packages/audio/main.roc", …, pf: platform "../server/platform/main.roc", … }import audio.AudioPlayer
…
program = App.program({
…
plugins: [AudioPlayer.plugin({})],
})Playing a sound#
Import audio.Audio in any component, page or module, and call it from a handler:
import audio.Audio
<button on:click={|| Audio.play!("/sounds/eat.wav")}>Eat</button>
<button on:click={|| Audio.play_with!("/sounds/pop.wav", { volume: 0.5, rate: 2.0 })}>Pop</button>Audio.play! plays a file at its own volume and speed. Audio.play_with! takes a volume from 0 to 1 and a rate: 2.0 plays twice as fast and an octave higher, so one short file can be a whole scale, as the showcase's flock plays its birds. A path starting with / is your site's; a whole URL plays from anywhere. The whole module:
import pf.Browser
## Sound files, from a handler: `Audio.play!("/sounds/eat.wav")` plays any file the browser can
## (WAV, MP3, Ogg, …). A path beginning with `/` is the site's, under its base, as a request's is;
## a whole URL is anywhere. Nothing is prepared in advance: the browser fetches a file the first
## time it plays it, and keeps it.
##
## A play is a `Browser.call!("audio.play", { url, volume, rate })`: once the handler is done and
## the page is patched, and once for a handler that waits for the server and runs again. The
## player is the audio plugin's script (`AudioPlayer.plugin({})` in the app's plugins), which every
## page loads. Only a handler plays; while computing, and on the server, it fails. Browsers keep a
## page quiet until the reader has done something on it: until then, nothing plays. A file that
## can't be played is told on the console.
Audio := [].{
## Plays the sound file at `url`, at its own volume and speed.
play! : Str => {}
play! = |url| Audio.play_with!(url, { volume: 1.0, rate: 1.0 })
## The same, at a `volume` (0 to 1), and a `rate`: 2.0 is twice as fast, and an octave up.
play_with! : Str, { volume : F64, rate : F64 } => {}
play_with! = |url, { volume, rate }| Browser.call!("audio.play", { url, volume: number(volume), rate: number(rate) })
}
## A number JSON has, that a sound could use (0 to 1000); else (NaN, an infinity, below 0) 1.
number : F64 -> F64
number = |x| if (x >= 0.0 and x <= 1000.0) x else 1.0
expect number(0.5) == 0.5
expect number(-1.0) == 1.0
expect number(2000.0) == 1.0When a sound plays#
A play is a Browser.call!, a call to the page's own JavaScript, and follows its rules:
- It runs once the handler is done and the page shows what it wrote. A handler that waits for the server runs twice, but plays once.
- Only a handler plays: an event's handler, a timer, or an effect's apply. Calling it while a hole, a memo or a component's body is computed is an error, and so is calling it on the server.
- Browsers keep a page silent until the reader has clicked or typed on it. Until then nothing plays, and no error is reported.
- A file that can't be played is reported on the browser's console. So is a play when the app doesn't list the plugin: "no effect is called audio.play: the audio plugin's script registers it: is the audio plugin in the app's plugins?"
How the player works#
The plugin serves its script at /rocx/plugins/audio/audio.js. Every page loads it before start.js, so it is ready before the page wakes. It registers the browser effect audio.play on window.rocxEffects, where Browser.call! looks. Each play makes an HTML Audio element, sets its volume and rate (kept between 0 and 1, and between 1/16 and 16), and plays it. The browser fetches a file on its first play, and caches it.
under, which the runtime gives every effect, puts a path starting with / under the site's base: /sounds/eat.wav becomes /rocx/sounds/eat.wav when your site is served at /rocx/.
// The audio plugin's script (packages/audio): the player. Every page loads it before start.js, so
// the effect it registers is there before the page wakes: `audio.play`, which `Audio.play!` calls
// (`Browser.call!("audio.play", { url, volume, rate })`), once the handler is done and the page is
// patched. A sound file, any the browser can, fetched the first time and kept by it, at a volume
// and a rate, its pitch moving with its speed. A URL that begins with `/` is the site's, under its
// base (`under`, which the runtime gives every effect). Until the reader has done something on the
// page the browser refuses to play it, and that is no failure.
function play({ url, volume = 1, rate = 1 }, { under = (path) => path } = {}) {
if (typeof Audio === "undefined") return;
const sound = new Audio(under(url));
sound.volume = Math.min(Math.max(volume, 0), 1);
sound.preservesPitch = false;
sound.playbackRate = Math.min(Math.max(rate, 0.0625), 16);
sound.play()?.catch((error) => {
if (error?.name !== "NotAllowedError") console.error(`audio: the sound ${url} can't be played: ${error?.message ?? error}`);
});
}
window.rocxEffects = { ...window.rocxEffects, "audio.play": play };On the Android host no script is needed: the phone's own handler for audio.play plays the file, fetched from your app's server, at the same volume and rate. The pomodoro example plays its chime this way.
Sound files#
The package brings no sounds. Your app serves its own, like any static file (--static). This site's are a few KB each, chiptune notes made by site/sounds.mjs; the quiz and pomodoro examples make theirs the same way.
Not yet#
- A sound can't be stopped, paused or looped.
- A play answers nothing: your code can't tell when a sound ends, or whether it played.
- No loading ahead: the first play waits for the download.
The package's README.md (packages/audio/) has the full reference.