Module ztcl::audio
ztcl::audio plays sounds on a phone, and sets its audio session.
# A WAV of 0.2 s: 8-bit PCM at 8,000 Hz, one channel.
set pcm [string repeat [binary format c4 {0 60 0 -60}] 400]
set wav [binary format a4ia4a4issiissa4ia* RIFF 1636 WAVE "fmt " 16 1 1 8000 8000 1 8 data 1600 $pcm]
ztcl::audio play -data $wav -command {apply {{d} {
puts "the sound ended: [dict get $d status]"
set ::done 1
}}}
vwait ::done
the sound ended: done
This example runs with ztcl --allow audio,event --fake-device: the fake host of the ztcl program ends each sound at once. On a phone, the same script plays the tone, and the end comes when it stops.
How the end of a sound arrives
ztcl::audio play FILE -command SCRIPT or play -data BYTES -command SCRIPT starts the sound and gives a handle such as audio1 at once. The player of the phone plays it on a thread of the OS, and at its end sends one event to the event loop of the interpreter. The event loop then runs SCRIPT one time with one more argument, a dict with the one key status, so SCRIPT is a command prefix that takes one argument, such as apply {{d} {...}} or the name of a proc.
So the end does not arrive while the event loop does not run: a script needs vwait, update, or the event loop of Tk. The sound itself plays with no event loop. ztcl::audio stop HANDLE ends a sound at once, and its SCRIPT gets status stopped. A sound with no -command sends nothing.
The end
| Key | Value | Meaning |
|---|---|---|
status |
done |
The sound played to its end, as many times as -loop asked. |
status |
stopped |
ztcl::audio stop ended it. |
status |
error |
The player could not decode or play the bytes. |
When there is no sound
| Case | What the script gets |
|---|---|
The capability audio is off |
The command does not exist: invalid command name "ztcl::audio", with the errorCode TCL LOOKUP COMMAND ztcl::audio. |
The host has no audio (the ztcl program on a desktop, iOS and macOS in this version) |
play gives the error audio is not available on this platform, and session KIND the audio session is not available on this platform, with the errorCode ZTCL AUDIO UNAVAILABLE. |
| The bytes are no sound that the player reads | play gives the error the sound did not play with the errorCode ZTCL AUDIO FAILED, or the sound ends with status error. |
play FILE with no capability channels |
The error a sound file needs the capability channels: use -data, with the errorCode ZTCL AUDIO FILE. |
| The permission of the user | Sounds need none. |
Sessions, volume, and the battery
ztcl::audio session KIND sets how the app shares the speaker. ambient, the default, mixes with the audio of other apps. playback plays also when the phone is set to silent, on a platform that has a silent switch. solo stops the audio of other apps: on Android it holds the audio focus. -volume and ztcl::audio volume HANDLE V set the volume of one sound, from 0.0 to 1.0, under the volume of the device. A sound of -loop 0 plays until stop, and keeps the speaker on: stop it when the app does not need it.
Platforms
| Platform | The player |
|---|---|
| Android (ztk) | MediaPlayer: WAV, MP3, AAC, Ogg, and the other formats of Android |
| iOS and macOS (ztk) | none in this version: ZTCL AUDIO UNAVAILABLE |
The ztcl program, Linux, Windows |
none |
| The web | none |
The ztcl program has no player; --fake-device gives it the fake host of the examples (src/device_fake.zig). docs/dev/audio-engine.md of the repository is the design of an audio engine with exact timing, for each platform.
Commands
| Command | Description |
|---|---|
ztcl::audio session ?KIND? |
Gives the audio session, or sets it: ambient, playback, or solo. |
ztcl::audio play FILE ?OPTION VALUE ...? |
Plays an audio file, such as WAV, MP3, or AAC, and gives a handle such as audio1. |
ztcl::audio play -data BYTES ?OPTION VALUE ...? |
Plays the bytes of an audio file, such as the result of read or of binary. |
ztcl::audio stop HANDLE |
Stops a sound. A handle that ended is no error. |
ztcl::audio volume HANDLE ?VALUE? |
Gives the volume of a sound that plays, or sets it, from 0.0 to 1.0. |
The options of play:
| Option | Description |
|---|---|
-volume V |
The volume, from 0.0 to 1.0. The default is 1.0. |
-loop COUNT |
Plays the sound COUNT times, 1 to 1,000, or until stop with 0. The default is 1. |
-command SCRIPT |
Runs SCRIPT at the end of the sound, with the dict of the end. |
ztcl reads FILE with the open and read of the script, so a file follows the root folder of the interpreter and needs the capability channels. The host gets only the bytes, at most 64 MiB, and opens no path.
The command is not a package: it exists when the embedder turns on the capability audio, and it is absent otherwise. A child interp has it only when its parent has it. While a sound plays, the event loop wakes at least every 20 milliseconds. The interpreter stops each sound when it ends. A WebAssembly module gets the same sounds through the import family audio (the device APIs for WebAssembly).
The audio engine
The engine mixes sounds in ztcl, with its own clock of frames, so a voice starts at an exact frame. It has stages 1 and 2 of docs/dev/audio-engine.md: the device offline, which needs no sound card and gives the bytes of the sound with render, the same on each platform, and the sequencer of patterns. The device default plays on the sound card of the host. On Windows the ztcl program has it: the default output of the system, in shared mode (WASAPI), with a latency of about 20 ms. When that output goes away, such as a headset unplugged, the engine gets {route other reason old lead L} and pauses; configure -device default plays again on the new default output. On the other systems the ztcl program gives ZTCL AUDIO UNAVAILABLE for the device default in this version.
ztcl::audio configure -device offline -rate 48000
set click [ztcl::audio load -wave square -freq 1500 -length 30 -decay 25 -sustain 0]
foreach beat {0 1 2 3} {
ztcl::audio play $click -at [expr {$beat * 24000}] -gain [expr {$beat ? 0.6 : 1.0}]
}
set bytes [ztcl::audio render 2000] ;# 2 s at 120 BPM: 4 clicks, 16-bit stereo
| Command | Description |
|---|---|
ztcl::audio configure ?OPTION VALUE ...? |
The options of the engine, as a widget: -device (none, offline, or default), -rate (Hz), -latency (ms), -command, -interruption (pause or resume), and -nowplaying (a dict of title, artist, album, and duration for the lock screen). |
ztcl::audio cget OPTION |
One option of the engine. |
ztcl::audio load FILE|-data BYTES|-wave SHAPE ?OPTION VALUE ...? |
Makes a sound: a WAV file decoded and resampled to the rate, or a wave (sine, square, saw, noise) with -freq, -length, and an envelope (-attack, -decay, -sustain, -release). Gives an id such as sound1. |
ztcl::audio unload SOUND |
Frees a sound, and stops its voices. |
ztcl::audio play SOUND ?OPTION VALUE ...? |
Starts a voice -in MS from now or -at FRAME, with -gain, -pan, -choke GROUP, and -command. Gives an id such as voice2. |
ztcl::audio pattern TRACKS ?OPTION VALUE ...? |
Starts a pattern of steps with -tempo, -meter, -subdivision, -swing, -accent, -loop, -gap, -countin, -in or -at, and -command. Gives an id such as pattern3. |
ztcl::audio tempo PATTERN BPM ?-bar N|-at FRAME? |
Changes the tempo at once, on the first step of bar N, or at a frame. |
ztcl::audio stop VOICE|PATTERN ?-in MS|-at FRAME? |
Stops a voice with a short fade, or a pattern. An id that ended is no error, as for after cancel. |
ztcl::audio configure ID ?OPTION VALUE ...?, cget ID OPTION |
The options of a sound (-gain, -frames, -length), of a voice (-gain, -pan, -sound), or of a pattern (the options of pattern, and -tracks). |
ztcl::audio position ?-heard? ?PATTERN? |
The clock: frame, ms, and time (ns). With PATTERN: bar, beat, step, and muted. |
ztcl::audio render MS ?-format s16|f32? |
With the device offline: mixes MS milliseconds and gives the bytes. |
ztcl::audio info ?ID? |
The live ids, as after info, or the facts of one id. |
Patterns
A pattern is a Tcl list of SOUND STEPS pairs. A step is X (an accent), x (a hit at the gain of -accent), . (a rest), a gain from 0 to 1, or {X TICKS} with an offset in ticks (960 for each quarter note). The first element of a pair can have options of the track: [list $hat -choke 1 -gain 0.7 -pan 0.3]. A track can hold several whole bars, and a shorter track repeats inside the cycle of the longest one. This example plays two bars of a drum pattern in sixteenths with swing, changes the tempo exactly at bar 2, and reads each beat:
ztcl::audio configure -device offline -rate 48000
set kick [ztcl::audio load -wave sine -freq 60 -length 120 -decay 110 -sustain 0]
set snare [ztcl::audio load -wave noise -length 90 -decay 80 -sustain 0]
set open [ztcl::audio load -wave noise -length 300 -decay 250 -sustain 0]
set hat [ztcl::audio load -wave noise -length 30 -decay 25 -sustain 0]
set p [ztcl::audio pattern [list \
$kick {X . . . . . . . X . x . . . . .} \
$snare {. . . . X . . . . . . . X . . {x 60}} \
[list $open -choke 1 -gain 0.6] {. . . . . . . X} \
[list $hat -choke 1 -gain 0.5 -pan 0.3] {x x x x x x x .}] \
-tempo 96 -subdivision 4 -swing 0.333 -loop 2 \
-command {apply {{b} {
if {[dict get $b beat] == 1} { puts "bar [dict get $b bar] at frame [dict get $b frame]" }
}}}]
ztcl::audio tempo $p 120 -bar 2
set bytes [ztcl::audio render 5000]
update
puts "[string length $bytes] bytes, [ztcl::audio info]"
bar 1 at frame 0
bar 2 at frame 120000
960000 bytes, sound1 sound2 sound3 sound4
At 96 BPM a bar is 120,000 frames at 48 kHz, and bar 2 plays at 120 BPM. The swing of 0.333 delays each second sixteenth by a third of a step, a triplet feel. With -loop 2 the pattern ends after bar 2, so info lists only the sounds. configure $p -tracks NEW changes the steps at the next step, and the other options of configure change at the next bar.
The ids behave as the ids of after. A -command gets one dict appended, as fileevent and trace do: {status done} or {status stopped} for a voice, and {bar B beat N step S accent 0|1 muted 0|1 frame F} at each beat of a pattern. The -command of the engine gets the events of the audio session of the device default: {interruption began}, {interruption ended resume 1}, {route headphones reason old lead 12} when an output goes away, and {remote toggle} from the lock screen. An interruption and a lost output pause the output, and -interruption resume starts it again at the end of an interruption. The errors are those of Tcl: sound "sound9" doesn't exist, with the errorCode TCL LOOKUP AUDIO sound9. The PCM of each sound counts in the memory limit of the interpreter, and render spends compute units.
The host
An embedder gives the functions session, play, volume, and stop of Interp.device_host. play gets a Sink, a handle, and the bytes, the volume, and the count of plays; it posts the end of the sound to the sink as a sound reading, from any thread. A sound is a handle of the same table as the watches of ztcl::device, ztcl::location, and ztcl::motion. After stop of a handle, the interpreter ignores its end.