MiniAudio extension for Rebol3 (version 3.22.5 and higher)
Plays sounds - from files, from memory, or from samples computed in Rebol - on its own audio thread, so the interpreter stays free while they play. Sounds can be grouped, faded, routed through effects, placed in 3D space and generated as they are heard.
Everything is reached through handles whose fields are read and written as
paths: sound/volume, sound/is-playing, device/sample-rate. The full list
is in the reference at the bottom of this file.
audio: import 'miniaudio
;; list all available devices:
print audio/get-devices
;; init a playback device (first available)...
;; keep the reference to the device handle, else it will be released by GC!
device: audio/init-playback 1
;; load a sound for later use...
sound: audio/load %assets/zblunk_02.wav
;; play a looping sound...
drums: audio/play/loop %assets/drumloop.wav
;; list resources linked with the playback device...
print ["Available sounds:" mold device/resources]
;; work in Rebol as usually, the audio has own thread
wait 0:0:1
;; stop the music with a fade 5 seconds...
audio/stop/fade :drums 0:0:5
;; wait for the sound to fade out...
wait 5
;; play already loaded sound...
audio/play :sound
wait 1
sound/pan: -1.0
audio/play :device/resources/1
wait 1Encoded audio does not have to come from a file - a binary! works too, so a
sound may be played straight out of a zip, a database or a HTTP response.
data: read %assets/zblunk_02.wav
sound: audio/load data
audio/play soundThe data is decoded where it lies rather than copied, so the series is locked
against resizing for as long as the session lasts - append data #{00} will
error. Use copy data if a mutable version is needed. Note that play itself
takes a file or a handle: encoded data goes through load first.
a: 0
b: PI
with audio [
probe wave: make-waveform-node type_sine 0.5 440.0
print ["amplitude:" wave/amplitude "frequency:" wave/frequency]
probe sound: play/fade wave 0:0:3 ;; start playing with a fade..
;; modify the wave's parameters while playing...
loop 500 [
a: a + 0.01
b: b + 0.006
wave/frequency: 440.0 + (220.0 * ((sin a) * cos b))
wait 0.01
]
stop/fade sound 0:0:2
loop 400 [
a: a + 0.02
b: b + 0.003
wave/frequency: 440.0 + (220.0 * ((sin a) * cos b))
wait 0.005
]
]A vector of samples can be played directly. Its element type decides the
sample format - int16! is s16, float32! is f32, uint8! is u8 and
int32! is s32 - so there is nothing else to declare.
;; one second of a 440 Hz sine wave...
rate: 44100
samples: make vector! reduce ['int16! rate]
repeat i rate [
samples/:i: to integer! 12000 * sine/radians (2 * pi * 440 * (i - 1) / rate)
]
buffer: audio/make-buffer-node/rate samples rate
print ["buffer:" buffer/frames "frames," buffer/duration]
audio/play bufferLike a loaded binary, the samples are used in place and the vector is locked against resizing. Individual samples may still be rewritten, so a playing buffer can be reshaped under the playhead.
A binary! of raw sample bytes works as well, but then the format has to be
given: audio/make-buffer-node/format data audio/format_s16.
A buffer is a fixed block of samples. For audio which is computed as it is heard, a stream is a ring buffer: Rebol writes into one end while the audio thread reads from the other.
rate: device/sample-rate
stream: audio/make-stream-node 0:0:0.5 ;; half a second of slack
chunk: make vector! [int16! 2048]
phase: 0.0
fill: does [
repeat i 2048 [
chunk/:i: to integer! 8000 * sine/radians phase
phase: phase + (2 * pi * 330 / rate)
]
audio/write stream chunk
]
fill ;; prime it before starting
hum: audio/play stream
loop 200 [
;; top it up whenever there is room for another chunk
if stream/available >= 2048 [fill]
wait 0.01
]
audio/stop/fade hum 0:0:0.5write returns how many frames it actually took, which is fewer than offered
when the buffer is full - so a feed loop can simply write what it has and look
at the result. stream/pending says how much is still queued.
A stream which runs dry plays silence rather than ending, so falling behind is heard as a gap and not as the sound stopping. The other side of that is that a stream never finishes by itself: it has to be stopped.
Each sound has a position, the engine has a listener, and how quickly distance makes a sound quieter is up to you.
sound: audio/load %assets/zblunk_02.wav
sound/spatialize: true
sound/x: 5.0 ;; five units to the right of the listener
sound/attenuation: 'inverse ;; or none to switch attenuation off
sound/rolloff: 1.0
sound/min-distance: 1.0
sound/max-distance: 20.0
listener: device/listener
listener/position: 0x0 ;; x and y; use /z for the third axis
audio/play soundA group is a bus with its own volume, pan, pitch and effects, applied to every sound loaded into it.
music: audio/make-group-node
drums: audio/load/group %assets/drumloop.wav music
music/volume: 50% ;; affects the whole group
audio/play drums
wait 2
audio/stop/fade music 0:0:1 ;; fades out everything in the groupecho: audio/make-delay-node 0:0:0.25 60% ;; delay time and feedback decay
sound/output: echo
audio/play soundwith audio [
;; initialize an audio device...
device: init-playback 1
;; create a waveform
wave: make-waveform-node type_sine 0.5 500.0
;; start the sound to be reused for the beep (paused)
stop snd: play :wave
;; beep function accepting time how long
beep: function[time [decimal! time!]][
start :snd
wait time
stop :snd
wait 0.1
]
dot: does[beep 0.1]
dash: does[beep 0.3]
]
dot dot dot dash dash dash dot dot dotrelease deviceThe C sources are compiled with the Siskin builder
from Rebol-MiniAudio.nest, which defines one build target (egg) per platform.
Two of the sources - and the reference sections at the bottom of this file -
are generated from the declarative specification
src/miniaudio.reb and are not edited by hand:
r3 -s make-extension.r3 src/miniaudio.reb --readmeThat writes src/gen-miniaudio.h, src/gen-miniaudio.c and everything in
this file below Extension commands. The nest file runs it itself, so a
normal build needs nothing extra.
r3 test.r3 ;; full run, plays audio
r3 test.r3 --quick ;; skip the audible, timed parts
r3 test.r3 --null ;; allow the dummy device, for machines without audiotest.r3 asserts and exits non-zero on failure; demo.r3 is the
same ground covered as a readable walk-through instead.
Native MiniAudio version
Retrive playback/capture device names
Initialize a playback device
index[integer!]/pauseDon't start it automatically/channelsThe number of channels to use for playbacknumber[integer!]When set to 0 the device's native channel count will be used/periodHint for making up the device's entire buffersize[integer!]The desired size of a period in milliseconds/callbackOn-data callback (two args.. buffer frames, and engine total frames)context[object!]The function's contextword[word!]The function's name
Loads a file or encoded audio data and returns sound's handle. A binary is used in place and so is locked against resizing for good - use copy if a mutable version is needed.
sound[file! binary!]/groupGroup of sounds which have their own effect processing and volume controlnode[handle!]ma-group handle
Loads a file (if not already loaded) and starts playing it. Returns a sound handle.
sound[file! handle!]Source file or a ma-sound handle/streamDo not load the entire sound into memory/loopTurn looping on/volumevol[percent! decimal!]/fadein[integer! time!]PCM frames or time/groupGroup of sounds which have their own effect processing and volume controlnode[handle!]ma-group handle
Pause sound playback
sound[handle!]
Start sound, group or device playback. A sound is restarted from its beginning (use /seek to start elsewhere) and its looping state is taken from /loop, so a plain start turns looping off.
handle[handle!]ma-sound, ma-group or ma-engine handle/loopTurn looping on (only for sounds)/seekStarting position (only for sounds)frames[integer! time!]PCM frames or time/fadeFade in the soundin[integer! time!]PCM frames or time/atAbsolute engine time when the sound should be startedtime[integer! time!]PCM frames or time
Stop sound, group or device playback
handle[handle!]ma-sound, ma-group or ma-engine handle/fadeout[integer! time!]PCM frames or time (not for the device)
Fade sound volume
sound[handle!]frames[integer! time!]start[percent! decimal!]end[percent! decimal!]
Seek to specified position
sound[handle!]frames[integer! time!]/relativeRelative to the current sound position
Creates a noise node for generating random noise
type[integer!]The type of noise to generate (0 - 2)amplitude[decimal!]The peak amplitude of the noise/seedOptional random seedval[integer!]/formatThe sample format (default is 2 = signed 16bit integer)frm[integer!]Value betweem 1 - 5
Creates a sound waveform node
type[integer!]The type of waveform to generate (0 - 3)amplitude[decimal!]The peak amplitude of the waveformfrequency[decimal!]The frequency of the waveform in Hertz (Hz)/formatThe sample format (default is 2 = signed 16bit integer)frm[integer!]Value betweem 1 - 5
Creates a delay (echo) sound node
delay[decimal! integer! time!]The time before the echo is heard. Seconds, PCM frames or time.decay[decimal! percent!]Feedback decay (0.0 - 1.0). Affects how quickly or gradually the echoes fade away. 0 means no feedback./dryThe mix level of the dry (original) soundd[decimal! percent!]/wetThe mix level of the wet (delayed) soundw[decimal! percent!]
Creates a data source node from raw PCM samples. The samples are used in place, so the series is locked against resizing for good - use copy if a mutable version is needed. A vector's element type decides the sample format: uint8! u8, int16! s16, int32! s32, float32! f32; any other vector type is refused. A binary is raw sample bytes and needs /format.
data[vector! binary!]Interleaved PCM samples/channelsNumber of interleaved channels (default is 1)count[integer!]/rateSamples per second (default is the engine's, else 48000)hz[integer!]/formatSample format of a binary (default is 2 = signed 16bit integer)frm[integer!]Value betweem 1 - 5
Creates a data source node fed with samples while it plays, for audio generated as it is heard. Use write to keep it filled; a stream which runs dry plays silence rather than ending, so the sound keeps going and only the gap is heard.
frames[integer! time!]Capacity of the ring buffer (PCM frames or time)/channelsNumber of interleaved channels (default is 1)count[integer!]/rateSamples per second (default is the engine's, else 48000)hz[integer!]/formatThe sample format (default is 2 = signed 16bit integer)frm[integer!]Value betweem 1 - 5
Writes PCM samples into a stream node. Returns the number of frames written, which is less than the input when the buffer is full. A vector's element type must match the stream's sample format.
stream[handle!]ma-stream handledata[vector! binary!]Interleaved PCM samples
Creates a sound group node
Set the volume
sound[handle!]volume[percent! decimal!]
Get the volume
sound[handle!]
Set the pan
sound[handle!]pan[decimal!]
Get the pan
sound[handle!]
Set the pitch
sound[handle!]pitch[decimal!]
Get the pitch
sound[handle!]
Set the looping
sound[handle!]value[logic!]
Get the looping
sound[handle!]
Return true if sound ended
sound[handle!]
;Refinement Gets Sets Description
/volume decimal! [integer! decimal! percent!] "Sound volume"
/gain-db decimal! [integer! decimal!] "Sound volume in decibels (the same value as volume, logarithmic)"
/fade-volume decimal! none "Volume of a running fade, 1.0 when no fade is active"
/pan decimal! decimal! "Stereo panning (from -1.0 to 1.0)"
/pan-mode word! word! "balance (default, attenuates one side) or pan (moves the sound across)"
/pitch decimal! decimal! "Sound pitch"
/position pair! pair! "Sound position (x and y for now) relative to the listener"
/cursor integer! [integer! time!] "Sound playback position in PCM frames"
/time time! time! "Sound playback position as time"
/duration time! none "Sound duration in time"
/frames integer! none "Sound length in PCM frames"
/sample-rate integer! none "Number of samples per second"
/spatialize logic! logic! "3D spatialization state"
/is-looping logic! logic! "Whether sound is looping"
/is-playing logic! logic! "Whether sound is playing"
/at-end logic! none "Whether sound is at end"
/start integer! [integer! time!] "Absolute timer when the sound should be started (frames or time)"
/stop integer! [integer! time!] "Absolute timer when the sound should be stopped (frames or time)"
/x decimal! [integer! decimal!] "Sound X position"
/y decimal! [integer! decimal!] "Sound Y position"
/z decimal! [integer! decimal!] "Sound Z position"
/source [file! binary! handle!]none "Sound source as a loaded file, encoded data or a data source node"
/rolloff decimal! [integer! decimal!] "How quickly the sound gets quieter with distance"
/min-distance decimal! [integer! decimal!] "Distance below which no attenuation is applied"
/max-distance decimal! [integer! decimal!] "Distance above which no further attenuation is applied"
/min-gain decimal! [integer! decimal!] "Lower bound of the attenuated gain"
/max-gain decimal! [integer! decimal!] "Upper bound of the attenuated gain"
/doppler-factor decimal! [integer! decimal!] "Strength of the doppler effect, 0 disables it"
/attenuation [word! none!] [word! none!] "inverse, linear, exponential or none to disable it"
/positioning word! word! "absolute or relative (to the listener)"
/outputs integer! none "Number of output buses"
/output none [handle! none!] "Output bus node (write only)";Refinement Gets Sets Description
/volume decimal! [integer! decimal! percent!] "Sound volume"
/gain-db decimal! [integer! decimal!] "Sound volume in decibels (the same value as volume, logarithmic)"
/fade-volume decimal! none "Volume of a running fade, 1.0 when no fade is active"
/pan decimal! decimal! "Stereo panning (from -1.0 to 1.0)"
/pan-mode word! word! "balance (default, attenuates one side) or pan (moves the sound across)"
/pitch decimal! decimal! "Sound group pitch"
/position pair! pair! "Sound group position (x and y for now) relative to the listener"
/time time! none "Time the group has been playing"
/sample-rate integer! none "Number of samples per second"
/spatialize logic! logic! "3D spatialization state"
/is-playing logic! logic! "Whether sound is playing"
/start integer! [integer! time!] "Absolute timer when the sound should be started (frames or time)"
/stop integer! [integer! time!] "Absolute timer when the sound should be stopped (frames or time)"
/x decimal! [integer! decimal!] "Sound group X position"
/y decimal! [integer! decimal!] "Sound group Y position"
/z decimal! [integer! decimal!] "Sound group Z position"
/outputs integer! none "Number of output buses"
/output none [handle! none!] "Output bus node (write only)"
/resources block! none "Used group resources (sounds, nodes..)";Refinement Gets Sets Description
/volume decimal! [integer! decimal! percent!] "Global volume"
/frames integer! [integer! time!] "Engine playback position in PCM frames"
/time time! time! "Engine playback position as time"
/resources block! none "Used engine resources (sounds, nodes..)"
/channels integer! none "Number of output channels"
/sample-rate integer! none "Ouput device sample rate per second"
/gain-db decimal! [integer! decimal!] "The amplification factor in decibels"
/listener handle! none "The first listener as a ma-listener handle"
/listeners block! none "All listeners of the engine as ma-listener handles";Refinement Gets Sets Description
/index integer! none "Index of the listener in its engine"
/enabled logic! logic! "Whether the listener is enabled"
/position pair! pair! "Listener position (x and y)"
/x decimal! [integer! decimal!] "Listener X position"
/y decimal! [integer! decimal!] "Listener Y position"
/z decimal! [integer! decimal!] "Listener Z position";Refinement Gets Sets Description
/amplitude decimal! decimal! "Maximum value of the noise signal"
/format word! none "u8, s16, s24, s32 or f32"
/type word! none "white, pink or brownian";Refinement Gets Sets Description
/amplitude decimal! decimal! "Signal amplitude"
/frequency decimal! decimal! "Signal frequency in hertzs"
/format word! none "u8, s16, s24, s32 or f32"
/type word! none "sine, square, triangle or sawtooth";Refinement Gets Sets Description
/data [vector! binary!] none "The samples themselves, used in place"
/format word! none "u8, s16, s24, s32 or f32"
/channels integer! none "Number of interleaved channels"
/sample-rate integer! none "Number of samples per second"
/frames integer! none "Length in PCM frames"
/duration time! none "Length as time"
/cursor integer! [integer! time!] "Playback position in PCM frames";Refinement Gets Sets Description
/format word! none "u8, s16, s24, s32 or f32"
/channels integer! none "Number of interleaved channels"
/sample-rate integer! integer! "Number of samples per second"
/frames integer! none "Capacity in PCM frames"
/duration time! none "Capacity as time"
/pending integer! none "Frames written but not played yet"
/available integer! none "Frames which can be written right now";Refinement Gets Sets Description
/delay integer! none "PCM frames"
/decay decimal! [decimal! percent!] "Value between 0.0 and 1.0"
/dry decimal! [decimal! percent!] "The mix level of the dry (original) sound"
/wet decimal! [decimal! percent!] "The mix level of the wet (delayed) sound";; Waveform types
type_sine: 0
type_square: 1
type_triangle: 2
type_sawtooth: 3
;; Sample data formats
format_u8: 1
format_s16: 2 ;; Seems to be the most widely supported format.
format_s24: 3 ;; Tightly packed. 3 bytes per sample.
format_s32: 4
format_f32: 5