Skip to content

About

A MiniAudio extension module for Rebol3

Topics

Resources

Stars

2 stars

Watchers

1 watching

Forks

Repository files navigation

rebol-miniaudio

Rebol-MiniAudio CI Gitter Zulip

Rebol/MiniAudio

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.

Usage

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 1

Playing a sound held in memory

Encoded 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 sound

The 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.

Using a data-source node...

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                                                                                            
    ]
]

Playing your own samples

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 buffer

Like 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.

Generating audio as it plays

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.5

write 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.

Placing sounds in space

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 sound

Grouping sounds

A 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 group

Routing a sound through an effect

echo: audio/make-delay-node 0:0:0.25 60%  ;; delay time and feedback decay
sound/output: echo
audio/play sound

Using a waveform to play a morse sound

with 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 dot

Release the playback device (and all resources)

release device

Building

The 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 --readme

That 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.

Testing

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 audio

test.r3 asserts and exits non-zero on failure; demo.r3 is the same ground covered as a readable walk-through instead.

Extension commands:

version

Native MiniAudio version

get-devices

Retrive playback/capture device names

init-playback :index

Initialize a playback device

  • index [integer!]
  • /pause Don't start it automatically
  • /channels The number of channels to use for playback
  • number [integer!] When set to 0 the device's native channel count will be used
  • /period Hint for making up the device's entire buffer
  • size [integer!] The desired size of a period in milliseconds
  • /callback On-data callback (two args.. buffer frames, and engine total frames)
  • context [object!] The function's context
  • word [word!] The function's name

load :sound

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!]
  • /group Group of sounds which have their own effect processing and volume control
  • node [handle!] ma-group handle

play :sound

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
  • /stream Do not load the entire sound into memory
  • /loop Turn looping on
  • /volume
  • vol [percent! decimal!]
  • /fade
  • in [integer! time!] PCM frames or time
  • /group Group of sounds which have their own effect processing and volume control
  • node [handle!] ma-group handle

pause :sound

Pause sound playback

  • sound [handle!]

start :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
  • /loop Turn looping on (only for sounds)
  • /seek Starting position (only for sounds)
  • frames [integer! time!] PCM frames or time
  • /fade Fade in the sound
  • in [integer! time!] PCM frames or time
  • /at Absolute engine time when the sound should be started
  • time [integer! time!] PCM frames or time

stop :handle

Stop sound, group or device playback

  • handle [handle!] ma-sound, ma-group or ma-engine handle
  • /fade
  • out [integer! time!] PCM frames or time (not for the device)

fade :sound :frames :start :end

Fade sound volume

  • sound [handle!]
  • frames [integer! time!]
  • start [percent! decimal!]
  • end [percent! decimal!]

seek :sound :frames

Seek to specified position

  • sound [handle!]
  • frames [integer! time!]
  • /relative Relative to the current sound position

make-noise-node :type :amplitude

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
  • /seed Optional random seed
  • val [integer!]
  • /format The sample format (default is 2 = signed 16bit integer)
  • frm [integer!] Value betweem 1 - 5

make-waveform-node :type :amplitude :frequency

Creates a sound waveform node

  • type [integer!] The type of waveform to generate (0 - 3)
  • amplitude [decimal!] The peak amplitude of the waveform
  • frequency [decimal!] The frequency of the waveform in Hertz (Hz)
  • /format The sample format (default is 2 = signed 16bit integer)
  • frm [integer!] Value betweem 1 - 5

make-delay-node :delay :decay

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.
  • /dry The mix level of the dry (original) sound
  • d [decimal! percent!]
  • /wet The mix level of the wet (delayed) sound
  • w [decimal! percent!]

make-buffer-node :data

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
  • /channels Number of interleaved channels (default is 1)
  • count [integer!]
  • /rate Samples per second (default is the engine's, else 48000)
  • hz [integer!]
  • /format Sample format of a binary (default is 2 = signed 16bit integer)
  • frm [integer!] Value betweem 1 - 5

make-stream-node :frames

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)
  • /channels Number of interleaved channels (default is 1)
  • count [integer!]
  • /rate Samples per second (default is the engine's, else 48000)
  • hz [integer!]
  • /format The sample format (default is 2 = signed 16bit integer)
  • frm [integer!] Value betweem 1 - 5

write :stream :data

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 handle
  • data [vector! binary!] Interleaved PCM samples

make-group-node

Creates a sound group node

volume :sound :volume

Set the volume

  • sound [handle!]
  • volume [percent! decimal!]

volume? :sound

Get the volume

  • sound [handle!]

pan :sound :pan

Set the pan

  • sound [handle!]
  • pan [decimal!]

pan? :sound

Get the pan

  • sound [handle!]

pitch :sound :pitch

Set the pitch

  • sound [handle!]
  • pitch [decimal!]

pitch? :sound

Get the pitch

  • sound [handle!]

looping :sound :value

Set the looping

  • sound [handle!]
  • value [logic!]

looping? :sound

Get the looping

  • sound [handle!]

end? :sound

Return true if sound ended

  • sound [handle!]

Used handles and its getters / setters

MA-SOUND - MiniAudio sound object

;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)"

MA-GROUP - MiniAudio sound group

;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..)"

MA-ENGINE - MiniAudio device engine

;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"

MA-LISTENER - MiniAudio spatialization listener

;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"

MA-NOISE - MiniAudio noise generator

;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"

MA-WAVEFORM - MiniAudio sine, square, triangle and sawtooth waveforms generator

;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"

MA-BUFFER - MiniAudio buffer of raw PCM samples

;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"

MA-STREAM - MiniAudio ring buffer of PCM samples, written while it plays

;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"

MA-DELAY - MiniAudio delay node

;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"

Other extension values:

;; 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

About

A MiniAudio extension module for Rebol3

Topics

Resources

Stars

2 stars

Watchers

1 watching

Forks

Releases

Sponsor this project

Packages

Used by

Contributors

Languages