webaudio

package
v0.1.0-alpha Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 14, 2026 License: Apache-2.0 Imports: 4 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package webaudio implements the Web Audio rendering graph in pure Go: nodes, AudioParam automation, channel mixing and the DSP kernels. The JS-visible API (AudioContext, nodes, params) lives in the engine prelude and drives a Context through string commands.

Index

Constants

View Source
const Quantum = quantum

Quantum is the render quantum size in frames.

Variables

This section is empty.

Functions

This section is empty.

Types

type Buffer

type Buffer struct {
	Rate float64
	Data [][]float32
}

Buffer is audio data held by the graph (AudioBuffer contents, IRs).

func (*Buffer) Frames

func (b *Buffer) Frames() int

type Context

type Context struct {
	SampleRate float64
	Offline    bool
	Frame      int64

	Dest *Node

	Output [][]float32 // offline destination capture
	// Sink, when set on a real-time context, receives the destination's output (one slice per channel,
	// valid only during the call) after every render quantum.
	Sink func(channels [][]float32)

	Ended    []int
	Buffers  map[int]*Buffer
	Listener *Listener
	// contains filtered or unexported fields
}

Context is a Web Audio graph plus its render clock.

func NewContext

func NewContext(sampleRate float64, offline bool, channels, frames int) *Context

NewContext creates a context. For offline contexts frames is the length.

func (*Context) AddNode

func (c *Context) AddNode(typ string, o map[string]any) (int, error)

AddNode creates a node of the given type (lower-case names such as "gain", "oscillator", "biquad"). It returns the node id.

func (*Context) AnalyserByteFreq

func (c *Context) AnalyserByteFreq(id int) []uint8

AnalyserByteFreq scales dB magnitudes into 0..255.

func (*Context) AnalyserByteTime

func (c *Context) AnalyserByteTime(id int) []uint8

AnalyserByteTime maps samples to 0..255 around 128.

func (*Context) AnalyserFloatFreq

func (c *Context) AnalyserFloatFreq(id int) []float32

AnalyserFloatFreq returns dB magnitudes.

func (*Context) AnalyserFloatTime

func (c *Context) AnalyserFloatTime(id int) []float32

AnalyserFloatTime returns the latest fftSize samples.

func (*Context) CompressorReduction

func (c *Context) CompressorReduction(id int) float64

CompressorReduction returns the current gain reduction in dB.

func (*Context) Connect

func (c *Context) Connect(from, out, to, in int) error

Connect wires output `out` of from to input `in` of to.

func (*Context) ConnectParam

func (c *Context) ConnectParam(from, out, to int, param string) error

ConnectParam wires an output to an AudioParam.

func (*Context) Disconnect

func (c *Context) Disconnect(from, out, to, in int, param string)

Disconnect removes connections from `from`. to < 0 removes every outgoing connection; out/in < 0 are wildcards; a non-empty param targets only that AudioParam of node `to`.

func (*Context) Done

func (c *Context) Done() bool

Done reports whether an offline context has produced all of its frames.

func (*Context) FrequencyResponse

func (c *Context) FrequencyResponse(id int, freqs []float64) (mag, phase []float64)

FrequencyResponse evaluates a biquad at the given frequencies (Hz). Values outside [0, nyquist] give NaN, as in the spec.

func (*Context) HasExternal

func (c *Context) HasExternal() bool

HasExternal reports whether host-driven nodes (worklets) exist.

func (*Context) ListenerNode

func (c *Context) ListenerNode() int

ListenerNode returns the id of the node holding listener params.

func (*Context) Lock

func (c *Context) Lock()

Lock and Unlock serialise access to the graph between the page's host calls and a render goroutine.

func (*Context) Node

func (c *Context) Node(id int) *Node

Node returns a node by id.

func (*Context) ParamBlock

func (c *Context) ParamBlock(p *Param) []float32

ParamBlock evaluates a parameter for the current quantum: 128 values for a-rate/automated params, otherwise a single value.

func (*Context) Provide

func (c *Context) Provide(n *Node, out [][]float32)

Provide sets the output of an external node for the current quantum.

func (*Context) RemoveNode

func (c *Context) RemoveNode(id int)

RemoveNode detaches every connection of a node (used on GC/close).

func (*Context) Render

func (c *Context) Render(frames int)

Render advances the graph by `frames` frames (rounded up to quanta); offline contexts accumulate destination samples in c.Output.

func (*Context) Set

func (c *Context) Set(id int, key string, v any) error

Set assigns a non-AudioParam attribute (type, loop, curve, ...).

func (*Context) SetBuffer

func (c *Context) SetBuffer(id int, rate float64, data [][]float32)

SetBuffer stores audio data (AudioBuffer contents) under id.

func (*Context) SetStreamIn

func (c *Context) SetStreamIn(id int, r *Ring) error

SetStreamIn gives a MediaStreamAudioSourceNode its audio: every quantum takes what the ring holds.

func (*Context) SetTap

func (c *Context) SetTap(id int, f func(ch [][]float32)) error

SetTap installs a function called after every quantum with what a MediaStreamAudioDestinationNode received (the slices are only valid during the call).

func (*Context) SetWave

func (c *Context) SetWave(id int, real, imag []float64, disableNorm bool)

SetWave registers a custom PeriodicWave under id.

func (*Context) Start

func (c *Context) Start(id int, when, offset, duration float64, hasDur bool) error

Start/Stop schedule a source node.

func (*Context) Step

func (c *Context) Step() (*Node, [][][]float32)

Step advances externally-driven rendering. It returns the next external node needing input (with its mixed input) or nil when the quantum is complete (and the clock has advanced).

func (*Context) Stop

func (c *Context) Stop(id int, when float64) error

func (*Context) TakeEnded

func (c *Context) TakeEnded() []int

TakeEnded returns and clears the list of source nodes that finished.

func (*Context) Time

func (c *Context) Time() float64

Time is the current context time in seconds.

func (*Context) Unlock

func (c *Context) Unlock()

type Event

type Event struct {
	Type     EventType
	Time     float64 // seconds
	Value    float64
	TimeCst  float64   // SetTarget
	Duration float64   // Curve
	Curve    []float32 // Curve
}

Event is one automation event.

type EventType

type EventType int

EventType is an AudioParam automation event kind.

const (
	EvSetValue EventType = iota
	EvLinear
	EvExponential
	EvSetTarget
	EvCurve
)

type Listener

type Listener struct {
	// contains filtered or unexported fields
}

Listener is the AudioListener state (params live on a hidden node).

type Node

type Node struct {
	ID   int
	Type string

	Params map[string]*Param

	ChCount  int
	ChMode   string // "max", "clamped-max", "explicit"
	ChInterp string // "speakers", "discrete"

	Props map[string]any
	// Tap, when set on a MediaStreamAudioDestinationNode, receives each quantum it passes on.
	Tap func(ch [][]float32)
	// contains filtered or unexported fields
}

Node is one AudioNode.

func (*Node) AddParam

func (n *Node) AddParam(name string, def, min, max float64, arate bool) *Param

AddParam registers an extra AudioParam on a node (AudioWorklet descriptors).

type Param

type Param struct {
	Name     string
	Default  float64
	Min, Max float64
	Value    float64 // intrinsic value (used before the first event)
	ARate    bool    // a-rate (per frame) or k-rate
	Events   []Event
	// contains filtered or unexported fields
}

Param is an AudioParam.

func (*Param) AddEvent

func (p *Param) AddEvent(e Event)

AddEvent inserts an event keeping the timeline sorted (stable by time).

func (*Param) CancelAndHold

func (p *Param) CancelAndHold(t float64)

CancelAndHold freezes the value the timeline has at t.

func (*Param) CancelScheduled

func (p *Param) CancelScheduled(t float64)

CancelScheduled removes events at or after t.

func (*Param) ValueAt

func (p *Param) ValueAt(t float64) float64

ValueAt evaluates the automation timeline at time t.

type PeriodicWave

type PeriodicWave struct {
	// contains filtered or unexported fields
}

PeriodicWave mirrors Chromium's band-limited wavetable design: 36 ranges (three per octave) of 4096-sample tables, normalised on the first range.

func NewPeriodicWave

func NewPeriodicWave(rate float64, real, imag []float64, disableNorm bool) *PeriodicWave

NewPeriodicWave builds the tables from Fourier coefficients (real = cos terms, imag = sin terms; index 0 ignored).

type Ring

type Ring struct {
	// contains filtered or unexported fields
}

Ring is a first-in first-out buffer of planar float32 audio between a producer that is not tied to the render clock (a microphone, a remote WebRTC track, an AudioData generator) and the render thread that consumes it a quantum at a time. When it is full the oldest audio is dropped (a live source never waits for its reader); when it runs dry the reader gets silence.

func NewRing

func NewRing(frames, channels int) *Ring

NewRing creates a ring holding up to frames frames of channels channels.

func (*Ring) Channels

func (r *Ring) Channels() int

Channels is the channel count of the audio in the ring.

func (*Ring) Len

func (r *Ring) Len() int

Len is the number of frames waiting.

func (*Ring) Pop

func (r *Ring) Pop(dst [][]float32, frames int) int

Pop fills dst (one slice per channel, each at least frames long) and returns how many frames were real audio; the rest of the block is zeroed.

func (*Ring) Push

func (r *Ring) Push(p [][]float32)

Push appends planar audio (one slice per channel, equal lengths). A source with fewer channels than the ring repeats its last channel; one with more drops the extra ones.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL