wasmal

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Jun 12, 2026 License: MIT Imports: 2 Imported by: 0

README

wasmal

Go WASM bindings for the W3C Web Audio API 1.1.

The library is a thin, direct mapping over JavaScript via syscall/js. All audio processing takes place in the browser's audio engine — no audio work happens in Go itself.

Warning: The project is in early development and the API may change in backward-incompatible ways.

Requirements

  • Compiled with GOOS=js GOARCH=wasm
  • A browser environment that supports the Web Audio API

If you are new to Go and WebAssembly, see the official WebAssembly with Go documentation.

Installation

go get github.com/mokiat/wasmal@latest

Usage

Create an AudioContext, build a node graph, and connect it to the destination:

ctx := wasmal.NewAudioContext()

osc := ctx.CreateOscillator()
osc.Frequency().SetValue(440) // A4

gain := ctx.CreateGain()
gain.Gain().SetValue(0.5)

osc.Connect(gain)
gain.Connect(ctx.Destination())
osc.Start(0)

Asynchronous operations return a Promise[T]. Register callbacks and call the returned CleanupFunc when they are no longer needed to release the underlying JavaScript function object:

cleanup := ctx.Resume().Then(func(_ struct{}) {
    // audio is now playing
})
defer cleanup()

Supported API

Interface Factory
AudioContext / BaseAudioContext NewAudioContext()
AudioDestinationNode ctx.Destination()
AudioBufferSourceNode ctx.CreateBufferSource()
OscillatorNode ctx.CreateOscillator()
GainNode ctx.CreateGain()
BiquadFilterNode ctx.CreateBiquadFilter()
ConvolverNode ctx.CreateConvolver()
DelayNode ctx.CreateDelay(maxDelay)
DynamicsCompressorNode ctx.CreateDynamicsCompressor()
PannerNode ctx.CreatePanner()
StereoPannerNode ctx.CreateStereoPanner()
AudioBuffer ctx.CreateBuffer(channels, length, sampleRate)
AudioParam exposed as fields on each node
AudioListener ctx.Listener()

Documentation

Overview

Package wasmal provides Go WASM bindings for the W3C Web Audio API 1.1.

It is a thin, direct mapping over JavaScript via syscall/js; all audio processing takes place in the browser's audio engine, not in Go. The package must be compiled with GOOS=js GOARCH=wasm.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AudioBuffer

type AudioBuffer interface {

	// SampleRate is the sample rate of the PCM audio data in the buffer, in samples per second.
	SampleRate() float32

	// Length is the length of the PCM audio data in the buffer, in sample-frames.
	Length() uint32

	// Duration is the duration of the PCM audio data in the buffer, in seconds.
	Duration() float64

	// NumberOfChannels is the number of discrete audio channels described by the buffer.
	NumberOfChannels() uint32

	// GetChannelData returns a Float32Array containing the PCM audio data associated with the specified channel.
	GetChannelData(channel uint32) Float32Array
	// contains filtered or unexported methods
}

AudioBuffer as described here: https://www.w3.org/TR/webaudio-1.1/#AudioBuffer

type AudioBufferSourceNode

type AudioBufferSourceNode interface {
	AudioScheduledSourceNode

	// Buffer returns the AudioBuffer that is being used as the source of the audio data.
	Buffer() AudioBuffer

	// SetBuffer sets the AudioBuffer that is being used as the source of the audio data.
	SetBuffer(buffer AudioBuffer)

	// PlaybackRate returns an AudioParam that controls the rate at which the audio is played back.
	PlaybackRate() AudioParam

	// Detune returns an AudioParam that controls the detuning of the audio source in cents.
	Detune() AudioParam

	// Loop returns a boolean indicating whether the audio source should loop within
	// [AudioBufferSourceNode.LoopStart] and [AudioBufferSourceNode.LoopEnd].
	Loop() bool

	// SetLoop sets a boolean indicating whether the audio source should loop.
	SetLoop(loop bool)

	// LoopStart returns the time in seconds within the audio buffer at which the
	// loop should start.
	LoopStart() float64

	// SetLoopStart sets the time in seconds within the audio buffer at which the
	// loop should start.
	SetLoopStart(start float64)

	// LoopEnd returns the time in seconds within the audio buffer at which the
	// loop should end.
	LoopEnd() float64

	// SetLoopEnd sets the time in seconds within the audio buffer at which the
	// loop should end.
	SetLoopEnd(end float64)

	// StartOffset starts playback of the audio source at the specified time and
	// with the specified offset.
	StartOffset(when, offset float64)

	// StartOffsetDuration starts playback of the audio source at the specified
	// time, with the specified offset and duration.
	StartOffsetDuration(when, offset, duration float64)
}

AudioBufferSourceNode as described here: https://www.w3.org/TR/webaudio-1.1/#AudioBufferSourceNode

type AudioContext

type AudioContext interface {
	BaseAudioContext

	// BaseLatency returns the base latency of the audio context in seconds.
	// This is the amount of time that elapses between the moment an audio signal
	// is generated and the moment it is heard at the destination.
	BaseLatency() float64

	// OutputLatency returns the output latency of the audio hardware in seconds.
	OutputLatency() float64

	// Close closes the audio context, releasing any system audio resources that
	// it uses.
	Close() Promise[struct{}]

	// Resume resumes the progression of time in the audio context, allowing audio
	// to play if it was previously suspended.
	Resume() Promise[struct{}]

	// Suspend suspends the progression of time in the audio context, pausing
	// audio playback and processing until Resume() is called.
	Suspend() Promise[struct{}]
}

AudioContext as described here: https://www.w3.org/TR/webaudio-1.1/#AudioContext

func NewAudioContext

func NewAudioContext() AudioContext

type AudioContextState

type AudioContextState string

AudioContextState as described here: https://www.w3.org/TR/webaudio-1.1/#enumdef-audiocontextstate

const (
	AudioContextStateSuspended AudioContextState = "suspended"
	AudioContextStateRunning   AudioContextState = "running"
	AudioContextStateClosed    AudioContextState = "closed"
)

type AudioDestinationNode

type AudioDestinationNode interface {
	AudioNode

	// MaxChannelCount returns the maximum number of channels that the
	// destination node can handle.
	MaxChannelCount() uint32
}

AudioDestinationNode as described here: https://www.w3.org/TR/webaudio-1.1/#AudioDestinationNode

type AudioListener

type AudioListener interface {

	// PositionX returns an AudioParam representing the x coordinate of the
	// position of the listener.
	PositionX() AudioParam

	// PositionY returns an AudioParam representing the y coordinate of the
	// position of the listener.
	PositionY() AudioParam

	// PositionZ returns an AudioParam representing the z coordinate of the
	// position of the listener.
	PositionZ() AudioParam

	// ForwardX returns an AudioParam representing the x coordinate of the
	// forward orientation of the listener.
	ForwardX() AudioParam

	// ForwardY returns an AudioParam representing the y coordinate of the
	// forward orientation of the listener.
	ForwardY() AudioParam

	// ForwardZ returns an AudioParam representing the z coordinate of the
	// forward orientation of the listener.
	ForwardZ() AudioParam

	// UpX returns an AudioParam representing the x coordinate of the up
	// orientation of the listener.
	UpX() AudioParam

	// UpY returns an AudioParam representing the y coordinate of the up
	// orientation of the listener.
	UpY() AudioParam

	// UpZ returns an AudioParam representing the z coordinate of the up
	// orientation of the listener.
	UpZ() AudioParam
	// contains filtered or unexported methods
}

AudioListener as described here: https://www.w3.org/TR/webaudio-1.1/#AudioListener

type AudioNode

type AudioNode interface {

	// Context returns the AudioContext which owns this node.
	Context() BaseAudioContext

	// NumberOfInputs returns the number of inputs feeding into this node.
	NumberOfInputs() uint32

	// NumberOfOutputs returns the number of outputs leading out of this node.
	NumberOfOutputs() uint32

	// ConnectToNode connects this node to another AudioNode.
	ConnectToNode(destination AudioNode)

	// ConnectToParam connects this node to an AudioParam.
	ConnectToParam(destination AudioParam)

	// Disconnect disconnects this node from all outputs.
	Disconnect()

	// DisconnectFromNode disconnects this node from the specified destination node.
	DisconnectFromNode(destination AudioNode)

	// DisconnectFromParam disconnects this node from the specified destination param.
	DisconnectFromParam(destination AudioParam)
	// contains filtered or unexported methods
}

AudioNode as described here: https://www.w3.org/TR/webaudio-1.1/#AudioNode

type AudioParam

type AudioParam interface {

	// Value is the current value of the AudioParam.
	Value() float32

	// SetValue sets the value of the AudioParam.
	SetValue(value float32)

	// DefaultValue is the default value of the AudioParam.
	DefaultValue() float32

	// MinValue is the minimum value of the AudioParam.
	MinValue() float32

	// MaxValue is the maximum value of the AudioParam.
	MaxValue() float32

	// SetValueAtTime schedules a parameter change at a specific time.
	SetValueAtTime(value float32, startTime float64)

	// LinearRampToValueAtTime schedules a parameter change to a value at a
	// specific time, following a linear ramp.
	LinearRampToValueAtTime(value float32, endTime float64)

	// ExponentialRampToValueAtTime schedules a parameter change to a value at a
	// specific time, following an exponential ramp.
	ExponentialRampToValueAtTime(value float32, endTime float64)

	// SetTargetAtTime schedules a parameter change to a target value at a specific
	// time, following an exponential approach.
	SetTargetAtTime(target float32, startTime float64, timeConstant float32)

	// CancelScheduledValues cancels all scheduled parameter changes with a start time
	// greater than or equal to the given time.
	CancelScheduledValues(cancelTime float64)

	// CancelAndHoldAtTime cancels all scheduled parameter changes with a start
	// time greater than or equal to the given time, and holds the parameter value
	// at the value it had at the given time until the next scheduled change.
	CancelAndHoldAtTime(cancelTime float64)
	// contains filtered or unexported methods
}

AudioParam as described here: https://www.w3.org/TR/webaudio-1.1/#AudioParam

type AudioScheduledSourceNode

type AudioScheduledSourceNode interface {
	AudioNode

	// Start starts playback of the audio source at the specified time.
	//
	// If it is zero or before [AudioContext.CurrentTime], the audio will start immediately.
	Start(when float64)

	// Stop stops playback of the audio source at the specified time.
	//
	// If it is zero or before [AudioContext.CurrentTime], the audio will stop immediately.
	Stop(when float64)

	// SetOnEnded sets a callback that will be called when the audio source has finished playing.
	//
	// The returned CleanupFunc is not per spec but is needed due to the way Go's js.Func works.
	// It should be called when the callback is no longer needed to release resources. Each
	// invocation of SetOnEnded will replace the previous callback, so you should call the returned
	// CleanupFunc before calling SetOnEnded again to avoid leaking resources.
	SetOnEnded(onEnded func()) CleanupFunc
}

AudioScheduledSourceNode as described here: https://www.w3.org/TR/webaudio-1.1/#AudioScheduledSourceNode

type BaseAudioContext

type BaseAudioContext interface {

	// Destination is a read-only property that returns an AudioDestinationNode
	// representing the final destination of all audio in the context.
	Destination() AudioDestinationNode

	// SampleRate returns the sample rate (in samples per second) at which the
	// AudioContext handles audio.
	SampleRate() float32

	// CurrentTime returns the current time of the audio context in seconds.
	CurrentTime() float64

	// Listener returns an AudioListener object which can be used to control the
	// position and orientation of the listener in 3D space.
	Listener() AudioListener

	// State returns the current state of the audio context.
	State() AudioContextState

	// CreateBiquadFilter creates a BiquadFilterNode, which can be used to apply a
	// biquad filter effect to the audio signal.
	CreateBiquadFilter() BiquadFilterNode

	// CreateBuffer creates an empty AudioBuffer with the specified number of
	// channels, length in sample-frames, and sample rate.
	CreateBuffer(numChannels, length uint32, sampleRate float32) AudioBuffer

	// CreateBufferSource creates an AudioBufferSourceNode, which can be used to
	// play audio data contained within an AudioBuffer.
	CreateBufferSource() AudioBufferSourceNode

	// CreateConvolver creates a ConvolverNode, which can be used to apply a
	// convolution effect given an impulse response.
	CreateConvolver() ConvolverNode

	// CreateDelay creates a DelayNode, which can be used to delay the incoming
	// audio signal by a certain amount of time.
	CreateDelay(maxDelayTime float64) DelayNode

	// CreateDynamicsCompressor creates a DynamicsCompressorNode, which can be used
	// to apply dynamic range compression to the audio signal.
	CreateDynamicsCompressor() DynamicsCompressorNode

	// CreateGain creates a GainNode, which can be used to control the volume of the
	// audio signal.
	CreateGain() GainNode

	// CreateIIRFilter creates an IIRFilterNode, which can be used to apply an
	// infinite impulse response (IIR) filter effect to the audio signal.
	CreateIIRFilter(feedforward, feedback []float64) IIRFilterNode

	// CreateOscillator creates an OscillatorNode, which can be used to generate
	// periodic waveforms such as sine, square, sawtooth, and triangle waves.
	CreateOscillator() OscillatorNode

	// CreatePanner creates a PannerNode, which can be used to spatialize the
	// audio signal in 3D space.
	CreatePanner() PannerNode

	// CreateStereoPanner creates a StereoPannerNode, which can be used to pan the
	// audio signal left or right in the stereo field.
	CreateStereoPanner() StereoPannerNode

	// DecodeAudioData takes raw data representing an audio file and decodes it
	// asynchronously, returning a Promise that resolves to an AudioBuffer
	// containing the decoded audio data.
	DecodeAudioData(data []byte) Promise[AudioBuffer]
	// contains filtered or unexported methods
}

BaseAudioContext as described here: https://www.w3.org/TR/webaudio-1.1/#BaseAudioContext

type BiquadFilterNode added in v0.2.0

type BiquadFilterNode interface {
	AudioNode

	// Type returns the type of the filter.
	Type() BiquadFilterType

	// SetType sets the type of the filter.
	SetType(typ BiquadFilterType)

	// Frequency returns the AudioParam representing the frequency of the filter.
	Frequency() AudioParam

	// Detune returns the AudioParam representing the detune of the filter.
	Detune() AudioParam

	// Q returns the AudioParam representing the Q factor of the filter.
	Q() AudioParam

	// Gain returns the AudioParam representing the gain of the filter.
	Gain() AudioParam
}

BiquadFilterNode as described here: https://www.w3.org/TR/webaudio-1.1/#BiquadFilterNode

type BiquadFilterType added in v0.2.0

type BiquadFilterType string

BiquadFilterType as described here: https://www.w3.org/TR/webaudio-1.1/#enumdef-biquadfiltertype

const (
	BiquadFilterTypeLowpass   BiquadFilterType = "lowpass"
	BiquadFilterTypeHighpass  BiquadFilterType = "highpass"
	BiquadFilterTypeBandpass  BiquadFilterType = "bandpass"
	BiquadFilterTypeLowshelf  BiquadFilterType = "lowshelf"
	BiquadFilterTypeHighshelf BiquadFilterType = "highshelf"
	BiquadFilterTypePeaking   BiquadFilterType = "peaking"
	BiquadFilterTypeNotch     BiquadFilterType = "notch"
	BiquadFilterTypeAllpass   BiquadFilterType = "allpass"
)

type CleanupFunc added in v0.2.0

type CleanupFunc func()

CleanupFunc is a function that must be called to release resources. This is specific to the WebAssembly adapter and is not part of the official API.

type ConvolverNode

type ConvolverNode interface {
	AudioNode

	// Buffer returns the AudioBuffer containing the impulse response used by this
	// ConvolverNode.
	Buffer() AudioBuffer

	// SetBuffer sets the AudioBuffer containing the impulse response used by this
	// ConvolverNode.
	SetBuffer(buffer AudioBuffer)

	// Normalize returns whether the impulse response is scaled by an equal-power
	// normalization.
	Normalize() bool

	// SetNormalize sets whether the impulse response is scaled by an equal-power
	// normalization.
	SetNormalize(normalize bool)
}

ConvolverNode as described here: https://www.w3.org/TR/webaudio-1.1/#ConvolverNode

type DataTypes added in v0.3.0

type DataTypes interface {
	~int8 | ~uint8 | ~int16 | ~uint16 | ~int32 | ~uint32 | ~float32 | ~float64
}

DataTypes represents allowed data slice types.

type DelayNode

type DelayNode interface {
	AudioNode

	// DelayTime returns the delay time parameter of this DelayNode.
	DelayTime() AudioParam
}

DelayNode as described here: https://www.w3.org/TR/webaudio-1.1/#DelayNode

type DistanceModelType added in v0.2.0

type DistanceModelType string

DistanceModelType as described here: https://www.w3.org/TR/webaudio-1.1/#enumdef-distancemodeltype

const (
	DistanceModelTypeLinear      DistanceModelType = "linear"
	DistanceModelTypeInverse     DistanceModelType = "inverse"
	DistanceModelTypeExponential DistanceModelType = "exponential"
)

type DynamicsCompressorNode

type DynamicsCompressorNode interface {
	AudioNode

	// Threshold is the decibel value above which the compression will start
	// taking effect.
	Threshold() AudioParam

	// Knee is the decibel value representing the range above the threshold where
	// the curve smoothly transitions to the compressed portion.
	Knee() AudioParam

	// Ratio is the amount of change, in dB, needed in the input for a 1 dB change
	// in the output.
	Ratio() AudioParam

	// Reduction is the amount of gain reduction currently applied by the compressor
	// to the signal, in dB.
	Reduction() float32

	// Attack is the amount of time, in seconds, required to reduce the gain by 10 dB.
	Attack() AudioParam

	// Release is the amount of time, in seconds, required to increase the gain by 10 dB.
	Release() AudioParam
}

DynamicsCompressorNode as described here: https://www.w3.org/TR/webaudio-1.1/#DynamicsCompressorNode

type Float32Array added in v0.2.0

type Float32Array interface {
	Get(index int) float32
	Set(index int, value float32)
	CopyFrom(data []float32) // not per spec
}

Float32Array as described here: https://webidl.spec.whatwg.org/#idl-Float32Array

type GainNode

type GainNode interface {
	AudioNode

	// Gain returns an AudioParam representing the amount of gain to apply.
	Gain() AudioParam
}

GainNode as described here: https://www.w3.org/TR/webaudio-1.1/#GainNode

type IIRFilterNode added in v0.3.0

type IIRFilterNode interface {
	AudioNode
}

IIRFilterNode as described here: https://www.w3.org/TR/webaudio-1.1/#IIRFilterNode

type OscillatorNode

type OscillatorNode interface {
	AudioScheduledSourceNode

	// Type returns the type of the oscillator. The default value is "sine".
	Type() OscillatorType

	// SetType sets the type of the oscillator.
	SetType(oType OscillatorType)

	// Frequency returns an AudioParam representing the frequency of the oscillator.
	Frequency() AudioParam

	// Detune returns an AudioParam representing the detuning of the oscillator in cents.
	Detune() AudioParam
}

OscillatorNode as described here: https://www.w3.org/TR/webaudio-1.1/#OscillatorNode

type OscillatorType

type OscillatorType string

OscillatorType as described here: https://www.w3.org/TR/webaudio-1.1/#enumdef-oscillatortype

const (
	OscillatorTypeSine     OscillatorType = "sine"
	OscillatorTypeSquare   OscillatorType = "square"
	OscillatorTypeSawtooth OscillatorType = "sawtooth"
	OscillatorTypeTriangle OscillatorType = "triangle"
	OscillatorTypeCustom   OscillatorType = "custom"
)

type PannerNode

type PannerNode interface {
	AudioNode

	// PanningModel returns the current panning model used by the PannerNode.
	PanningModel() PanningModelType

	// SetPanningModel sets the panning model used by the PannerNode. The default
	// value is "equalpower".
	SetPanningModel(model PanningModelType)

	// PositionX returns an AudioParam representing the x-axis position of the
	// audio source in 3D space.
	PositionX() AudioParam

	// PositionY returns an AudioParam representing the y-axis position of the
	// audio source in 3D space.
	PositionY() AudioParam

	// PositionZ returns an AudioParam representing the z-axis position of the
	// audio source in 3D space.
	PositionZ() AudioParam

	// OrientationX returns an AudioParam representing the x-axis orientation of the
	// audio source in 3D space.
	OrientationX() AudioParam

	// OrientationY returns an AudioParam representing the y-axis orientation of the
	// audio source in 3D space.
	OrientationY() AudioParam

	// OrientationZ returns an AudioParam representing the z-axis orientation of the
	// audio source in 3D space.
	OrientationZ() AudioParam

	// DistanceModel returns the current distance model used by the PannerNode.
	DistanceModel() DistanceModelType

	// SetDistanceModel sets the distance model used by the PannerNode. The default
	// value is "inverse".
	SetDistanceModel(model DistanceModelType)

	// RefDistance returns the reference distance for reducing volume as the audio
	// source moves further from the listener. The default value is 1.
	RefDistance() float64

	// SetRefDistance sets the reference distance for reducing volume as the audio
	// source moves further from the listener. The default value is 1.
	SetRefDistance(distance float64)

	// MaxDistance returns the maximum distance between the audio source and the
	// listener, after which the volume will not be reduced any further.
	MaxDistance() float64

	// SetMaxDistance sets the maximum distance between the audio source and the
	// listener, after which the volume will not be reduced any further.
	SetMaxDistance(distance float64)

	// RolloffFactor returns the rolloff factor for reducing volume as the audio
	// source moves further from the listener. The default value is 1.
	RolloffFactor() float64

	// SetRolloffFactor sets the rolloff factor for reducing volume as the audio
	// source moves further from the listener. The default value is 1.
	SetRolloffFactor(factor float64)

	// ConeInnerAngle returns the inner angle of the cone in degrees.
	// The default value is 360.
	ConeInnerAngle() float64

	// SetConeInnerAngle sets the inner angle of the cone in degrees.
	// The default value is 360.
	SetConeInnerAngle(angle float64)

	// ConeOuterAngle returns the outer angle of the cone in degrees. The default
	// value is 360.
	ConeOuterAngle() float64

	// SetConeOuterAngle sets the outer angle of the cone in degrees. The default
	// value is 360.
	SetConeOuterAngle(angle float64)

	// ConeOuterGain returns the gain outside the outer angle of the cone. The
	// default value is 0.
	ConeOuterGain() float64

	// SetConeOuterGain sets the gain outside the outer angle of the cone. The
	// default value is 0.
	SetConeOuterGain(gain float64)
}

PannerNode as described here: https://www.w3.org/TR/webaudio-1.1/#PannerNode

type PanningModelType added in v0.2.0

type PanningModelType string

PanningModelType as described here: https://www.w3.org/TR/webaudio-1.1/#enumdef-panningmodeltype

const (
	PanningModelTypeEqualPower PanningModelType = "equalpower"
	PanningModelTypeHRTF       PanningModelType = "HRTF"
)

type Promise

type Promise[T any] interface {

	// Then registers a callback to be called when the Promise is resolved with
	// a value of type T.
	//
	// If the Promise is rejected, the callback is not invoked and the rejection
	// is silently discarded. Register a callback through Catch to observe errors.
	//
	// The returned CleanupFunc must be called to release resources associated
	// with the callback, regardless of whether the Promise is resolved or rejected.
	Then(cb func(value T)) CleanupFunc

	// Catch registers a callback to be called when the Promise is rejected with
	// an error.
	//
	// The returned CleanupFunc must be called to release resources associated
	// with the callback, regardless of whether the Promise is resolved or rejected.
	Catch(cb func(err error)) CleanupFunc
}

Promise represents a JavaScript Promise object in Go.

type StereoPannerNode

type StereoPannerNode interface {
	AudioNode

	// Pan returns an AudioParam representing the left-to-right pan control.
	Pan() AudioParam
}

StereoPannerNode as described here: https://www.w3.org/TR/webaudio-1.1/#stereopannernode

Jump to

Keyboard shortcuts

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