sound

package
v0.4.0-rc.3 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 17 Imported by: 4 modules, 3 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 sound provides game audio mixing, sound effects and music, deterministic sound cues, 2D and 3D positional playback, PCM and WAV processing, and configurable DSP effect chains. Set Music.OnError to observe permanent playback failures; its *MusicError identifies the source and unwraps the platform audio error. Autoplay NotAllowed is exposed through Music.Blocked instead.

Index

Examples

Constants

View Source
const (
	// DefaultSpeedOfSound is the default speed of sound in world units per second (343 m/s in dry air at 20°C),
	// used when a listener's SpeedOfSound is <= 0 or non-finite.
	DefaultSpeedOfSound float32 = 343

	// MinDopplerRatio is the lower clamp on Doppler pitch scaling, matching NSGo audio.Voice.Rate's lower bound.
	MinDopplerRatio float32 = 0.5

	// MaxDopplerRatio is the upper clamp on Doppler pitch scaling, matching NSGo audio.Voice.Rate's upper bound.
	MaxDopplerRatio float32 = 2.0
)
View Source
const (
	// DefaultMaxVoices is the default global concurrent voice budget on a Mixer,
	// kept below the platform's 32-voice hardware limit so brief steal fade-outs
	// never cause the backend to hard-drop high-priority sounds.
	DefaultMaxVoices = 30
)
View Source
const DefaultRearGain float32 = 0.7

DefaultRearGain is the default head-shadow gain multiplier a Listener3D applies to a sound directly behind the listener when Listener3D.RearGain is zero, negative, or NaN.

View Source
const DefaultReverbSendBus = "reverb"

DefaultReverbSendBus is the auxiliary send bus name driven by Zone.ReverbSend when Zone.SendBus is empty.

Variables

This section is empty.

Functions

func DecodeWAV

func DecodeWAV(wav []byte) (samples []float64, sampleRate, channels int, err error)

DecodeWAV decodes a 16-bit signed linear PCM RIFF/WAVE buffer into interleaved normalized samples in [-1, 1].

func DistanceCutoffHz

func DistanceCutoffHz(distance, near, far, farCutoffHz float32) float32

DistanceCutoffHz returns the distance low-pass filter cutoff frequency in hertz for a source at distance between near and far, interpolating logarithmically from 20 kHz at near down to farCutoffHz at far and beyond. It returns 0 (filter bypassed) when farCutoffHz <= 0 or non-finite, when farCutoffHz >= 20000, when distance attenuation is off (far <= near), or when distance <= near.

func DopplerFactor2D

func DopplerFactor2D(listenerPos, listenerVel, sourcePos, sourceVel math2d.Vec2, speedOfSound, scale float32) float32

DopplerFactor2D computes the clamped Doppler pitch ratio in [MinDopplerRatio, MaxDopplerRatio] for a 2D source at sourcePos moving at sourceVel relative to a listener at listenerPos moving at listenerVel. A speedOfSound <= 0 or non-finite uses DefaultSpeedOfSound; a scale <= 0 or non-finite defaults to 1.

func DopplerFactor3D

func DopplerFactor3D(listenerPos, listenerVel, sourcePos, sourceVel Vec3, speedOfSound, scale float32) float32

DopplerFactor3D computes the clamped Doppler pitch ratio in [MinDopplerRatio, MaxDopplerRatio] for a 3D source at sourcePos moving at sourceVel relative to a listener at listenerPos moving at listenerVel. A speedOfSound <= 0 or non-finite uses DefaultSpeedOfSound; a scale <= 0 or non-finite defaults to 1. Non-finite coordinates, zero distance, or supersonic approaching speeds are guarded so the returned ratio is always finite and clamped.

func EncodeWAV

func EncodeWAV(samples []float64, sampleRate, channels int) ([]byte, error)

EncodeWAV encodes interleaved normalized samples in [-1, 1] as a canonical 16-bit signed linear PCM RIFF/WAVE buffer.

func ProcessSamples

func ProcessSamples(samples []float64, sampleRate, channels int, chain ...BusEffect)

ProcessSamples runs each non-nil effect in chain in order on interleaved normalized PCM samples in [-1, 1].

Example

ProcessSamples runs a chain of bus effects over samples, as the Mixer does for a group.

package main

import (
	"fmt"
	"math"

	"github.com/nsgo-dev/game/pkg/sound"
)

// tone returns n frames of a mono 440 Hz sine at 8 kHz.
func tone(n int) sound.PCM {
	s := make([]float64, n)
	for i := range s {
		s[i] = 0.5 * math.Sin(2*math.Pi*440*float64(i)/8000)
	}
	return sound.PCM{Samples: s, SampleRate: 8000, Channels: 1}
}

func main() {
	pcm := tone(800)
	peak := func(s []float64) float64 {
		m := 0.0
		for _, v := range s {
			m = max(m, math.Abs(v))
		}
		return m
	}
	before := peak(pcm.Samples)
	sound.ProcessSamples(pcm.Samples, pcm.SampleRate, pcm.Channels, sound.Gain(0.5), sound.LowPass(2000, 0.7))
	fmt.Printf("%.2f -> %.2f\n", before, peak(pcm.Samples))
}
Output:
0.50 -> 0.25

func ProcessWAV

func ProcessWAV(wav []byte, chain ...BusEffect) ([]byte, error)

ProcessWAV decodes a 16-bit PCM WAV buffer, applies chain to its samples, and returns a re-encoded 16-bit PCM WAV buffer.

func RegisterEffect

func RegisterEffect(name string, f EffectFactory) error

RegisterEffect registers a plugin-provided custom BusEffect factory under name, which must be namespaced as "<plugin>.<name>" (such as "dynakit.compressor") and not already registered.

func RegisteredEffects

func RegisteredEffects() []string

RegisteredEffects returns the sorted names of every registered custom bus effect.

func ValidateEffectName

func ValidateEffectName(name string) error

ValidateEffectName checks that name is a valid namespaced custom bus effect name in "<plugin>.<name>" form and does not collide with a built-in effect name.

Types

type BeatTiming

type BeatTiming interface {
	Time(beat float64) time.Duration
	Beat(d time.Duration) float64
	Bar(beat float64) (bar int, inBar float64)
	BeatsPerBar(beat float64) int
}

BeatTiming maps between track time, beats, and bars. *rhythm.Timing implements it directly.

type BoxZone

type BoxZone struct {
	Min, Max Vec3
}

BoxZone is an axis-aligned 3D box from Min to Max (inclusive).

func BoxZoneFromCenterSize

func BoxZoneFromCenterSize(center, size Vec3) BoxZone

BoxZoneFromCenterSize builds a BoxZone centered at center with full extents size.

func (BoxZone) Contains2D

func (b BoxZone) Contains2D(pos math2d.Vec2) bool

Contains2D reports whether pos lies within b's X and Y bounds.

func (BoxZone) Contains3D

func (b BoxZone) Contains3D(pos Vec3) bool

Contains3D reports whether pos lies inside b (inclusive). Non-finite coordinates or inverted bounds return false.

type BusDebug

type BusDebug struct {
	Name         string  `json:"name"`
	ActiveVoices int     `json:"active_voices"`
	DuckGain     float32 `json:"duck_gain"`
}

BusDebug reports active voice count and current ducking gain multiplier for one mixer bus.

type BusDuckRule

type BusDuckRule struct {
	// Bus is the mixer bus (group) whose volume is lowered.
	Bus string
	// By is the triggering mixer bus (or concurrency group name) whose active sounds trigger ducking.
	By string
	// Amount is the volume reduction fraction in [0, 1]: 0 disables ducking, 0.4 lowers Bus by 40% (0.6x gain), and 1 silences Bus.
	Amount float32
	// Attack is how quickly Bus fades down when By starts playing; 0 or negative applies immediately.
	Attack time.Duration
	// Release is how quickly Bus recovers after all sounds on By finish; 0 or negative restores immediately.
	Release time.Duration
}

BusDuckRule lowers Bus's volume while any voice or music plays on By.

type BusEffect

type BusEffect interface {
	ProcessSamples(samples []float64, sampleRate, channels int)
}

BusEffect transforms interleaved normalized PCM samples in [-1, 1] in place. Implementations must keep per-run filter and delay state local to each call so an effect can be reused across buffers, sample rates, and channel layouts.

func BandPass

func BandPass(hz, q float64) BusEffect

BandPass returns a 2nd-order RBJ band-pass filter keeping the octave around hz and attenuating both sides. A non-positive q defaults to Butterworth (1/sqrt(2)).

func Bitcrush

func Bitcrush(bits int, downsample int) BusEffect

Bitcrush returns a retro lo-fi effect that quantizes samples to bits precision (1 to 15; values outside that range leave bit depth unchanged) and holds every downsample-th frame (values <= 1 disable downsampling).

func BuildEffect

func BuildEffect(name string, params map[string]any) (BusEffect, error)

BuildEffect constructs a registered custom BusEffect by name and params. When name is not registered, the error names both the effect and its plugin prefix so a project opened without the plugin reports what is missing.

func Chorus

func Chorus(rateHz, depthMs, mix float64) BusEffect

Chorus returns a modulated-delay chorus: a wet copy of the signal is read rateHz times a second from a delay sweeping around 20ms by depthMs, mixed with the dry signal by mix. A non-positive or non-finite rate, or a non-finite mix, leaves samples unchanged; a negative depth counts as 0.

func Compressor

func Compressor(thresholdDB, ratio, attackMs, releaseMs float64) BusEffect

Compressor returns a feed-forward peak compressor. Above thresholdDB dBFS, each channel's level rises only 1/ratio dB for every dB its input rises. The level it follows moves toward a louder peak over attackMs and back down over releaseMs milliseconds, where 0 or less reacts at once, and starts at silence on every ProcessSamples call like the other effects' state. A ratio of 1 or less, or a NaN or infinite parameter, leaves samples unchanged.

func Delay

func Delay(delay time.Duration, feedback, wet float64) BusEffect

Delay returns a feedback delay line with echo spacing delay, feedback clamped to [0, 0.99], and dry/wet mix wet clamped to [0, 1].

func Distortion

func Distortion(shape DistortionShape, driveDB, mix float64) BusEffect

Distortion returns an overdrive effect that drives every sample by driveDB before shaping it with shape and mixing the result with the dry signal by mix, clamped to [0, 1]: clip hard-clips at full scale, tanh saturates smoothly and fold reflects back at full scale. A non-finite parameter leaves samples unchanged.

func EQ

func EQ(bands ...EQBand) BusEffect

EQ returns a chain of equalizer bands (peaking, low-shelf or high-shelf) applied in order, so one bus effect shapes several frequencies at once. A band with a zero or non-finite gain is skipped.

func Gain

func Gain(factor float64) BusEffect

Gain returns an effect that scales every sample by factor.

func HighPass

func HighPass(cutoffHz, q float64) BusEffect

HighPass returns a 2nd-order RBJ biquad high-pass filter attenuating frequencies below cutoffHz. A non-positive q defaults to Butterworth (1/sqrt(2)).

func HighShelf

func HighShelf(hz, gainDB, q float64) BusEffect

HighShelf returns a 2nd-order RBJ high-shelf filter that raises or lowers everything above hz by gainDB. A non-positive q defaults to Butterworth (1/sqrt(2)).

func Limiter

func Limiter(ceilingDB float64) BusEffect

Limiter returns an effect that clips every sample to ceilingDB dBFS, so no sample's magnitude exceeds it. A NaN ceiling leaves samples unchanged.

func LookaheadLimiter

func LookaheadLimiter(ceilingDB, releaseMs float64) BusEffect

LookaheadLimiter returns a true-peak-safe lookahead brickwall limiter with a 5ms lookahead window and exponential release over releaseMs milliseconds. It detects inter-sample peaks with a 4x polyphase windowed-sinc estimator, smoothly lowers gain across linked channels ahead of peaks, recovers over releaseMs, and clamps output to ceilingDB dBFS so no sample exceeds the ceiling. A non-finite ceilingDB or releaseMs, or a negative releaseMs, leaves samples unchanged.

func LowPass

func LowPass(cutoffHz, q float64) BusEffect

LowPass returns a 2nd-order RBJ biquad low-pass filter attenuating frequencies above cutoffHz. A non-positive q defaults to Butterworth (1/sqrt(2)).

func LowShelf

func LowShelf(hz, gainDB, q float64) BusEffect

LowShelf returns a 2nd-order RBJ low-shelf filter that raises or lowers everything below hz by gainDB. A non-positive q defaults to Butterworth (1/sqrt(2)).

func Notch

func Notch(hz, q float64) BusEffect

Notch returns a 2nd-order RBJ notch filter cutting the band around hz, for hum, feedback and narrow resonances. A non-positive q defaults to Butterworth (1/sqrt(2)).

func Panner

func Panner(pan float64) BusEffect

Panner returns an equal-power stereo panner: pan -1 keeps the left channel, +1 the right, and 0 attenuates both by 3 dB. Mono samples and non-finite pan values leave samples unchanged.

func PeakingEQ

func PeakingEQ(hz, gainDB, q float64) BusEffect

PeakingEQ returns a 2nd-order RBJ peaking equalizer band at hz, boosting or cutting by gainDB. A non-positive q defaults to Butterworth (1/sqrt(2)).

func Phaser

func Phaser(rateHz, mix, feedback float64) BusEffect

Phaser returns a four-stage all-pass phaser: the stages' corner frequency sweeps between 400 Hz and 1600 Hz rateHz times a second, the wet output feeds back by feedback clamped to [0, 0.9] and the result mixes with the dry signal by mix. A non-positive or non-finite rate, or a non-finite mix or feedback, leaves samples unchanged.

func PitchShift

func PitchShift(semitones float64) BusEffect

PitchShift returns a granular pitch shifter that retunes the signal by semitones without changing its duration: 40ms Hann-windowed grains are resampled by the ratio and overlap-added by half a grain, so the output length and timing stay the same. A zero or non-finite shift leaves samples unchanged.

func Reverb

func Reverb(roomSize, damping, wet float64) BusEffect

Reverb returns a Schroeder/Freeverb-style comb and allpass reverb with roomSize, damping, and wet clamped to [0, 1].

func SidechainCompressor

func SidechainCompressor(thresholdDB, ratio, attackMs, releaseMs float64, sidechain string) BusEffect

SidechainCompressor returns a feed-forward peak compressor keyed from another bus named sidechain in SoftwareMixer. When sidechain is empty it behaves like Compressor. In offline ProcessSamples (where no external bus signal is present), a non-empty sidechain keys on silence and leaves samples unchanged.

func StereoWidth

func StereoWidth(width float64) BusEffect

StereoWidth widens or narrows a stereo signal around its mid channel: 0 collapses it to mono, 1 leaves it unchanged and 2 doubles the side signal. Mono samples and non-finite widths leave samples unchanged.

type Caption

type Caption struct {
	Key         string
	Kind        CaptionKind
	MinInterval time.Duration
}

Caption describes the accessibility caption attached to a sound Effect, Cue, or resource.Sound file. Key is an l10n lookup key (or literal fallback label when no catalog entry matches), Kind classifies the cue (defaults to CaptionSFX when empty), and MinInterval sets a per-sound repeat debounce interval (0 uses the receiver's default).

type CaptionEvent

type CaptionEvent struct {
	// Caption is the sound's Caption metadata (from PlayOptions, Effect, or Cue).
	Caption Caption
	// Pan is the listener stereo pan in [-1, 1] (-1 left, 0 center, +1 right),
	// computed before the mixer's mono and balance overrides so captions keep the true direction.
	Pan float32
	// Front is the 3D forward projection dot(dir, forward) in [-1, 1] (+1 directly ahead,
	// -1 directly behind), populated when Has3D is true.
	Front float32
	// Angle is the screen-space bearing in radians from the listener toward the source
	// (0 right, +pi/2 down/behind, pi/-pi left, -pi/2 up/ahead), populated when HasAngle is true.
	Angle float32
	// Loudness is the audible playback level in [0, 1] (voice volume * spatial gain * bus * master).
	Loudness float32
	// Positional reports whether the sound was played with a 2D or 3D world position.
	Positional bool
	// Has3D reports whether the playback used a Listener3D (Front is meaningful).
	Has3D bool
	// HasAngle reports whether Angle carries a meaningful bearing (the source was not
	// directly on top of the listener or purely overhead/underfoot).
	HasAngle bool
}

CaptionEvent reports one played captioned sound to a Mixer's caption handler.

type CaptionKind

type CaptionKind string

CaptionKind classifies a sound's accessibility caption.

const (
	// CaptionSFX is a standard non-speech sound effect cue (footsteps, door, explosion).
	CaptionSFX CaptionKind = "sfx"
	// CaptionImportant is a critical gameplay or hazard audio cue highlighted assertively
	// and shown by visual sound indicators.
	CaptionImportant CaptionKind = "important"
	// CaptionMusic is a musical cue or track mood indicator.
	CaptionMusic CaptionKind = "music"
	// CaptionChatter is ambient or background character speech.
	CaptionChatter CaptionKind = "chatter"
)

type CircleZone

type CircleZone struct {
	Center math2d.Vec2
	Radius float32
}

CircleZone is a 2D circular zone centered at Center with Radius.

func (CircleZone) Contains2D

func (c CircleZone) Contains2D(pos math2d.Vec2) bool

Contains2D reports whether pos lies within c.Radius of c.Center (inclusive).

func (CircleZone) Contains3D

func (c CircleZone) Contains3D(pos Vec3) bool

Contains3D reports whether pos's X and Y lie within c.

type Clip

type Clip struct {
	Name   string
	Effect *Effect
	PCM    PCM
}

Clip is a single sound variant inside a Cue. It may reference a Mixer Effect for engine playback, hold raw PCM samples for pure-Go pitch resampling, or both.

func EffectClip

func EffectClip(effect *Effect) Clip

EffectClip wraps an Effect as a Clip.

func PCMClip

func PCMClip(pcm PCM) Clip

PCMClip wraps a PCM buffer as a Clip.

type ConcurrencyGroup

type ConcurrencyGroup struct {
	// Max is the maximum number of simultaneous active voices in this group (or per owner when Scope is ScopeOwner).
	// Values <= 0 impose no group voice cap (global voice budget, retrigger, and ducking still apply).
	Max int
	// Resolve chooses which voice to drop (or whether to refuse the new sound) when Max is reached.
	// Defaults to ResolveRefuse.
	Resolve ConcurrencyResolve
	// Scope chooses whether Max, Retrigger, and Duck apply globally across the group or independently per owner.
	// Defaults to ScopeGlobal.
	Scope ConcurrencyScope
	// Retrigger is the minimum duration that must elapse between accepted voice starts in this group (or owner).
	// Calls arriving sooner are refused without stopping existing voices.
	Retrigger time.Duration
	// StealFade is the fade-out duration applied to voices stolen by this group's resolution rule before stopping them.
	// 0 or negative stops stolen voices immediately.
	StealFade time.Duration
	// Duck lowers older active voices in the same concurrency scope while newer voices play,
	// ramping in over Duck.Attack and recovering over Duck.Release as newer voices finish.
	Duck DuckEnvelope
}

ConcurrencyGroup defines shared voice limiting, resolution, retrigger cooldown, steal fade-out, and older-voice ducking across all Effects and Cues assigned to a group name.

type ConcurrencyGroupDebug

type ConcurrencyGroupDebug struct {
	Name         string `json:"name"`
	Active       int    `json:"active"`
	Max          int    `json:"max"`
	Resolve      string `json:"resolve"`
	Scope        string `json:"scope"`
	ActiveOwners int    `json:"active_owners,omitempty"`
	Refused      uint64 `json:"refused,omitempty"`
	Stolen       uint64 `json:"stolen,omitempty"`
	Retriggered  uint64 `json:"retriggered,omitempty"`
}

ConcurrencyGroupDebug reports live voice counts, configuration, and counters for one concurrency group.

type ConcurrencyResolve

type ConcurrencyResolve uint8

ConcurrencyResolve chooses how a ConcurrencyGroup resolves a new sound when its Max active voice limit is reached.

const (
	// ResolveRefuse prevents the new sound from playing when the concurrency limit is reached.
	ResolveRefuse ConcurrencyResolve = iota
	// ResolveOldest stops the oldest active voice in the concurrency scope to make room for the new sound.
	ResolveOldest
	// ResolveFarthest stops the farthest active voice when the new sound is at least as close, and refuses the new sound otherwise.
	ResolveFarthest
	// ResolveQuietest stops the quietest active voice when the new sound is at least as loud, and refuses the new sound otherwise.
	ResolveQuietest
	// ResolveLowestPriority stops the lowest-priority active voice (ties broken by oldest) when the new sound's priority is at least as high, and refuses the new sound otherwise.
	ResolveLowestPriority
)

func (ConcurrencyResolve) String

func (r ConcurrencyResolve) String() string

String returns the canonical YAML name of r.

type ConcurrencyScope

type ConcurrencyScope uint8

ConcurrencyScope chooses whether a ConcurrencyGroup's voice limit, retrigger time, and ducking apply across the whole group or independently per owner.

const (
	// ScopeGlobal shares the concurrency limit, retrigger cooldown, and older-voice ducking across every sound in the group.
	ScopeGlobal ConcurrencyScope = iota
	// ScopeOwner scopes the concurrency limit, retrigger cooldown, and older-voice ducking independently per PlayOptions.Owner.
	ScopeOwner
)

func (ConcurrencyScope) String

func (s ConcurrencyScope) String() string

String returns the canonical YAML name of s.

type Cue

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

Cue selects and plays sound variants with deterministic pitch and volume variation and configurable repeat avoidance.

Example

A Cue picks one of several variations of a sound with random pitch and volume, never repeating the last pick, so frequent sounds such as footsteps do not grate.

package main

import (
	"fmt"
	"math"

	"github.com/nsgo-dev/game/pkg/sound"
)

// tone returns n frames of a mono 440 Hz sine at 8 kHz.
func tone(n int) sound.PCM {
	s := make([]float64, n)
	for i := range s {
		s[i] = 0.5 * math.Sin(2*math.Pi*440*float64(i)/8000)
	}
	return sound.PCM{Samples: s, SampleRate: 8000, Channels: 1}
}

func main() {
	cue := sound.NewCue(1, sound.CueOptions{
		Clips: []sound.Clip{
			{Name: "step1", PCM: tone(800)},
			{Name: "step2", PCM: tone(800)},
			{Name: "step3", PCM: tone(800)},
		},
		PitchMin: 0.9, PitchMax: 1.1,
		NoRepeatWindow: 1,
	})
	last := ""
	repeats := 0
	for range 20 {
		p := cue.Pick()
		if p.Clip.Name == last {
			repeats++
		}
		last = p.Clip.Name
		if p.Pitch < 0.9 || p.Pitch > 1.1 {
			fmt.Println("pitch out of range")
		}
	}
	fmt.Println("repeats:", repeats)
}
Output:
repeats: 0

func NewCue

func NewCue(seed uint64, opts CueOptions) *Cue

NewCue creates a Cue seeded with seed and configured by opts.

func (*Cue) Caption

func (c *Cue) Caption() Caption

Caption returns the accessibility caption metadata attached to c.

func (*Cue) LastIndex

func (c *Cue) LastIndex() int

LastIndex returns the index of the most recent pick, or -1 if Pick has not been called since creation or Reset.

func (*Cue) Len

func (c *Cue) Len() int

Len returns the number of clips in the cue.

func (*Cue) NoRepeatWindow

func (c *Cue) NoRepeatWindow() int

NoRepeatWindow returns the effective repeat-avoidance window size (0 when disabled).

func (*Cue) Pick

func (c *Cue) Pick() CuePick

Pick deterministically selects the next clip according to the cue's repeat window and weights, samples Pitch in [PitchMin, PitchMax] and Volume in [VolumeMin, VolumeMax], and updates repeat history. On an empty cue, Pick returns CuePick{Index: -1}.

func (*Cue) PitchRange

func (c *Cue) PitchRange() (min, max float64)

PitchRange returns the normalized inclusive [min, max] pitch range.

func (*Cue) Play

func (c *Cue) Play() (CuePick, bool)

Play selects the next variant via Pick and plays its Effect with the sampled volume and pitch rate, respecting the effect's mixer group volume, master volume, background mute, concurrency group, and voice limit.

func (*Cue) Play2D

func (c *Cue) Play2D(l Listener2D, pos math2d.Vec2) (CuePick, *Playback2D)

Play2D picks the cue's next variant and starts a live 2D playback of its effect at pos as l hears it.

func (*Cue) Play2DOptions

func (c *Cue) Play2DOptions(l Listener2D, pos math2d.Vec2, spatial Spatial2DOptions, opts PlayOptions) (CuePick, *Playback2D)

Play2DOptions behaves like Cue.Play2DWith while also applying per-source 2D spatialization options.

func (*Cue) Play2DWith

func (c *Cue) Play2DWith(l Listener2D, pos math2d.Vec2, opts PlayOptions) (CuePick, *Playback2D)

Play2DWith behaves like Cue.Play2D while applying per-call concurrency, owner, and priority overrides from opts.

func (*Cue) Play3D

func (c *Cue) Play3D(pos Vec3, opts Spatial3DOptions) (CuePick, *Playback3D)

Play3D picks the cue's next variant, as Play does, and starts a live 3D playback of its effect at pos using that effect's mixer's Listener3D and opts. It returns the pick and the Playback3D handle (whose Ended reports true when nothing played).

func (*Cue) Play3DWith

func (c *Cue) Play3DWith(pos Vec3, opts Spatial3DOptions, playOpts PlayOptions) (CuePick, *Playback3D)

Play3DWith behaves like Play3D while applying per-call concurrency, owner, and priority overrides from playOpts.

func (*Cue) PlayAt

func (c *Cue) PlayAt(l Listener2D, pos math2d.Vec2) (CuePick, bool)

PlayAt picks the cue's next variant, as Play does, and plays it at pos in the world as l hears it, as Effect.PlayAt does: at the variant's volume times l.Gain, panned by l.Pan, at the variant's pitch. It reports the pick and whether it played; beyond l's Far it plays nothing, though the pick still counts towards the cue's repeat avoidance.

func (*Cue) PlayAt3D

func (c *Cue) PlayAt3D(l Listener3D, pos Vec3) (CuePick, bool)

PlayAt3D picks the cue's next variant, as Play does, and plays it at pos in the 3D world as l hears it, as Effect.PlayAt3D does: at the variant's volume times l.Gain, panned by l.Pan, at the variant's pitch. It reports the pick and whether it played; beyond l's Far it plays nothing, though the pick still counts towards the cue's repeat avoidance.

func (*Cue) PlayAt3DWith

func (c *Cue) PlayAt3DWith(l Listener3D, pos Vec3, opts PlayOptions) (CuePick, bool)

PlayAt3DWith behaves like PlayAt3D while applying per-call concurrency, owner, and priority overrides from opts.

func (*Cue) PlayAtWith

func (c *Cue) PlayAtWith(l Listener2D, pos math2d.Vec2, opts PlayOptions) (CuePick, bool)

PlayAtWith behaves like PlayAt while applying per-call concurrency, owner, and priority overrides from opts.

func (*Cue) PlayPCM

func (c *Cue) PlayPCM() (CuePick, PCM)

PlayPCM selects the next variant via Pick and returns its resampled and gain-scaled PCM buffer.

func (*Cue) PlayWith

func (c *Cue) PlayWith(opts PlayOptions) (CuePick, bool)

PlayWith behaves like Play while applying per-call concurrency, owner, and priority overrides from opts.

func (*Cue) Reset

func (c *Cue) Reset(seed uint64)

Reset re-seeds the internal generator to seed, restores the internal source, and clears the repeat history for deterministic replay.

func (*Cue) SetCaption

func (c *Cue) SetCaption(caption Caption)

SetCaption updates the accessibility caption metadata attached to c, including any Effects created internally by Mixer.Cue.

func (*Cue) SetSource

func (c *Cue) SetSource(src RandSource)

SetSource replaces the cue's random source. Passing nil restores the internal seeded stream.

func (*Cue) Stop

func (c *Cue) Stop()

Stop stops every Effect referenced by c's clips.

func (*Cue) VolumeRange

func (c *Cue) VolumeRange() (min, max float64)

VolumeRange returns the normalized inclusive [min, max] volume range.

type CueOptions

type CueOptions struct {
	// Clips are the sound variants selected by the cue.
	Clips []Clip

	// PitchMin and PitchMax define the inclusive pitch multiplier range.
	// When both are 0, pitch defaults to [1, 1]. If PitchMin > PitchMax they are swapped.
	PitchMin float64
	PitchMax float64

	// VolumeMin and VolumeMax define the inclusive volume range, clamped to [0, 1].
	// When both are 0, volume defaults to [1, 1]. If VolumeMin > VolumeMax they are swapped.
	VolumeMin float64
	VolumeMax float64

	// NoRepeatWindow is the number of most recent picks excluded from being chosen again.
	// When 0 and AllowRepeat is false, it defaults to 1 (never repeats the same clip twice
	// in a row when len(Clips) >= 2). Values larger than len(Clips)-1 are clamped to len(Clips)-1.
	// Negative values disable repeat avoidance.
	NoRepeatWindow int

	// AllowRepeat disables the default immediate no-repeat behavior when NoRepeatWindow is 0.
	AllowRepeat bool

	// Weights gives optional relative selection weights per clip. When omitted, all clips
	// have equal weight. Missing trailing entries default to 1; non-positive or non-finite
	// entries are treated as 0.
	Weights []float64

	// Source optionally supplies an external deterministic random stream.
	// When nil, Cue uses its internal Xoshiro256** generator seeded with seed.
	Source RandSource

	// Concurrency is the optional concurrency group name applied to Effects created by Mixer.Cue
	// and used as a fallback when playing a Clip whose Effect leaves Concurrency empty.
	Concurrency string

	// Priority is the playback priority applied to Effects created by Mixer.Cue
	// and used as a fallback when playing a Clip whose Effect leaves Priority at 0.
	Priority int

	// Caption is the accessibility caption applied to Effects created by Mixer.Cue
	// and used as a fallback when playing a Clip whose Effect leaves Caption.Key empty.
	Caption Caption
}

CueOptions configures a Cue's clips, pitch and volume randomization ranges, repeat avoidance, relative clip weights, and optional external random source.

type CuePick

type CuePick struct {
	Index  int
	Clip   Clip
	Pitch  float64
	Volume float64
}

CuePick is the outcome of a single Cue.Pick call.

func (CuePick) RenderPCM

func (p CuePick) RenderPCM() PCM

RenderPCM resamples p.Clip.PCM by p.Pitch and scales it by p.Volume.

func (CuePick) RenderWAV

func (p CuePick) RenderWAV() ([]byte, error)

RenderWAV resamples p.Clip.PCM by p.Pitch, scales it by p.Volume, and encodes it as a 16-bit PCM WAV buffer.

func (CuePick) Valid

func (p CuePick) Valid() bool

Valid reports whether p selected a clip.

type DistortionShape

type DistortionShape int

DistortionShape is the transfer curve Distortion applies.

const (
	// DistortionClip hard-clips the driven signal at full scale.
	DistortionClip DistortionShape = iota
	// DistortionTanh saturates the driven signal smoothly.
	DistortionTanh
	// DistortionFold reflects the driven signal back from full scale instead of clipping it.
	DistortionFold
)

type DuckEnvelope

type DuckEnvelope struct {
	// Amount is the volume reduction fraction in [0, 1]: 0 disables ducking (1.0x gain),
	// 0.4 lowers volume by 40% (0.6x gain), and 1 lowers volume to silence (0x gain).
	Amount float32
	// Attack is how quickly the ducking reduction ramps in; 0 or negative applies immediately.
	Attack time.Duration
	// Release is how quickly volume recovers after the ducking sound finishes; 0 or negative restores immediately.
	Release time.Duration
}

DuckEnvelope configures how much and how quickly a ducking reduction engages and releases.

type EQBand

type EQBand struct {
	Hz, GainDB, Q float64
	Kind          EQBandKind
}

EQBand is one band of EQ: the center or corner frequency in hertz, the gain in dB, the resonance (where 0 is Butterworth, 1/sqrt(2)), and optional Kind (defaulting to EQBandPeaking).

type EQBandKind

type EQBandKind int

EQBandKind selects the filter shape of an EQBand.

const (
	// EQBandPeaking boosts or cuts a bell band around Hz (the default).
	EQBandPeaking EQBandKind = iota
	// EQBandLowShelf boosts or cuts everything below Hz.
	EQBandLowShelf
	// EQBandHighShelf boosts or cuts everything above Hz.
	EQBandHighShelf
)

type Effect

type Effect struct {
	// Group is the group (bus) whose volume the sound plays at.
	Group string
	// Limit is the most playbacks of the sound at once, so a burst of it does not take every voice; 0 for no per-effect limit (still subject to any concurrency group and the mixer's global voice budget).
	Limit int
	// Concurrency is the optional name of a shared ConcurrencyGroup registered on the mixer.
	Concurrency string
	// Priority ranks this sound during ResolveLowestPriority and global voice-budget stealing; higher wins.
	Priority int
	// Caption attaches optional accessibility caption metadata (l10n key, kind, and repeat interval)
	// reported to the mixer's caption handler (Mixer.SetCaptionHandler) whenever this effect plays.
	Caption Caption
	// contains filtered or unexported fields
}

Effect is a short sound played through a mixer, in a group, optionally belonging to a shared concurrency group, with a priority and per-sound voice limit.

func (*Effect) Close

func (s *Effect) Close()

Close lets the effect's sound go, as audio.Sound.Close does for a sound passed to Effect or loaded by LoadEffect: the decoded audio goes, ending its playbacks, once no other sound holds it. A closed effect plays nothing. Calling it again does nothing.

func (*Effect) Play

func (s *Effect) Play(v audio.Voice) bool

Play starts a playback of the sound at v's volume times its group's and the master volume, which follows those volumes as they change while it plays. Its pan is centered to 0 when the mixer is in mono mode (SetMono) and otherwise offset by the mixer's balance (SetBalance) and clamped to [-1, 1]. It reports whether it asked for one: false while that volume is 0, as for a Muted voice, while the app is in the background, suspended, or the effect's group is paused, or when refused by a concurrency group, retrigger cooldown, or global voice budget, and true otherwise, even where the backend's playback (audio.Playback) ends at once because it could not start. With Limit playbacks still playing it stops the oldest to make room, so the newest are heard; a playback that cannot start leaves them playing. A backend that cannot address playbacks plays it as it started, outside the limit and the volume changes.

func (*Effect) Play2D

func (s *Effect) Play2D(l Listener2D, pos math2d.Vec2, v audio.Voice) *Playback2D

Play2D starts a live 2D playback of s at pos as l hears it, returning a Playback2D handle whose position, velocity, volume, stereo pan, and Doppler pitch can update while playing and refresh automatically on Mixer.SetListener2D. Like Effect.PlayAt, it starts nothing where silent or refused, returning an ended Playback2D holding no voice.

func (*Effect) Play2DOptions

func (s *Effect) Play2DOptions(l Listener2D, pos math2d.Vec2, v audio.Voice, spatial Spatial2DOptions, opts PlayOptions) *Playback2D

Play2DOptions behaves like Play2DWith while also applying per-source 2D spatialization options such as distance attenuation overrides, Doppler tracking, and a distance low-pass cutoff.

func (*Effect) Play2DWith

func (s *Effect) Play2DWith(l Listener2D, pos math2d.Vec2, v audio.Voice, opts PlayOptions) *Playback2D

Play2DWith behaves like Play2D while applying per-call concurrency, owner, and priority overrides from opts.

func (*Effect) Play3D

func (s *Effect) Play3D(pos Vec3, v audio.Voice, opts Spatial3DOptions) *Playback3D

Play3D starts a live 3D playback of s at pos using s's mixer's Listener3D and opts, returning a Playback3D handle. Like Effect.Play, it starts nothing when the voice is muted, effective gain is 0 (beyond Far, outside a zero-gain cone, zero group/master volume, paused, suspended, or in the background), or refused by a concurrency group, retrigger cooldown, or global voice budget, returning an ended Playback3D so silent or refused sources never take voice slots or count against s.Limit.

func (*Effect) Play3DWith

func (s *Effect) Play3DWith(pos Vec3, v audio.Voice, opts Spatial3DOptions, playOpts PlayOptions) *Playback3D

Play3DWith behaves like Play3D while applying per-call concurrency, owner, and priority overrides from playOpts.

func (*Effect) PlayAt

func (s *Effect) PlayAt(l Listener2D, pos math2d.Vec2, v audio.Voice) bool

PlayAt plays the effect at pos in the world as l hears it: panned by l.Pan (adjusted by the mixer's mono and balance settings) and at v's volume times l.Gain, then the group's and the master volume, as Play does, and reports whether it played. It plays nothing where the effect is silent, beyond l's Far, and replaces v's pan. Use Effect.Play2D with Mixer.SetListener2D for playbacks whose pan, volume, and Doppler pitch follow a moving listener or source.

func (*Effect) PlayAt3D

func (s *Effect) PlayAt3D(l Listener3D, pos Vec3, v audio.Voice) bool

PlayAt3D plays the effect at pos in the 3D world as l hears it: panned by l.Pan (adjusted by the mixer's mono and balance settings) and at v's volume times l.Gain, then the group's and the master volume, as Play does, and reports whether it played. It plays nothing where the effect is silent, beyond l's Far, and replaces v's pan. The pan and volume hold for the playback's whole length; use Effect.Play3D with Mixer.SetListener3D for playbacks whose spatial gain tracks a moving camera or moving source.

func (*Effect) PlayAt3DWith

func (s *Effect) PlayAt3DWith(l Listener3D, pos Vec3, v audio.Voice, opts PlayOptions) bool

PlayAt3DWith behaves like PlayAt3D while applying per-call concurrency, owner, and priority overrides from opts. Distance from l.Position to pos is recorded for ResolveFarthest concurrency groups.

func (*Effect) PlayAtWith

func (s *Effect) PlayAtWith(l Listener2D, pos math2d.Vec2, v audio.Voice, opts PlayOptions) bool

PlayAtWith behaves like PlayAt while applying per-call concurrency, owner, and priority overrides from opts. Distance from l.Position to pos is recorded for ResolveFarthest concurrency groups.

func (*Effect) PlayWith

func (s *Effect) PlayWith(v audio.Voice, opts PlayOptions) bool

PlayWith behaves like Play while applying per-call concurrency, owner, and priority overrides from opts.

func (*Effect) SetCaption

func (s *Effect) SetCaption(label string, callback func(label string, pan float32))

SetCaption installs callback to run with label and the listener pan each time PlayAt, PlayAt3D, or their With and Cue forms start a playback of the effect, so an a11y.CaptionEmitter can show a caption in the direction the player hears without the sound package depending on a11y. A nil callback removes it. Plain Play has no position and does not call it.

func (*Effect) Stop

func (s *Effect) Stop()

Stop stops every playback of the sound, and of every other sound of the same source, as audio.Sound.Stop does.

type EffectChain

type EffectChain []BusEffect

EffectChain applies a sequence of bus effects in order and itself satisfies BusEffect.

func (EffectChain) ProcessSamples

func (c EffectChain) ProcessSamples(samples []float64, sampleRate, channels int)

ProcessSamples runs every non-nil effect in c in order on interleaved samples.

func (EffectChain) ProcessWAV

func (c EffectChain) ProcessWAV(wav []byte) ([]byte, error)

ProcessWAV decodes a 16-bit PCM WAV buffer, runs c over its samples, and re-encodes a 16-bit PCM WAV buffer.

type EffectFactory

type EffectFactory func(params map[string]any) (BusEffect, error)

EffectFactory builds a BusEffect from YAML parameters loaded from a bus layout file or game.yaml. Return an error (optionally a *loaderr.Error whose Field names the offending parameter) when params are missing or out of range.

func LookupEffect

func LookupEffect(name string) (EffectFactory, bool)

LookupEffect returns the EffectFactory registered under name, if any.

type EffectInstance

type EffectInstance interface{ Process(block []float32) }

EffectInstance processes one software-mixer stream and retains state between blocks.

type InteractiveMusic

type InteractiveMusic struct {
	// Group is the mixer bus whose volume, pause state, ducking, and bus effects apply to this piece.
	Group string
	// OnError receives permanent playback or load errors as *MusicError (excluding audio.NotAllowed, which is surfaced via Blocked and retried via Mixer.Unblock).
	OnError func(error)
	// contains filtered or unexported fields
}

InteractiveMusic plays an adaptive MusicPiece through a Mixer: bar-synced and beat-synced transitions, optional stinger (via) clips, lockstep layered stems with per-stem volume fades, deterministic playlists, and beat/bar callbacks.

Where audio.CanSchedule is true and clip sources fit within the engine's SoundLimits, clips and stems are scheduled on audio.Now with audio.Voice.StartAt so transitions land on the exact beat/bar and stems start on the same sample time. Where audio.CanSchedule is false (or a long source exceeds SoundLimits), playback falls back cleanly to audio.Player on the nearest engine frame.

While its group is silenced (Mixer.SetPaused, backgrounding, Mixer.Suspend, or a volume of 0), an audio.Player clip pauses at its position and its beat clock, pending transitions and handoffs freeze with it. A scheduled clip cannot pause, because audio.Playback has no pause or seek, so it plays on in silence like an Effect: its clock, pending transitions and handoffs keep running in step with the audio, and on resume it is heard from where the audio has reached. OnBeat and OnBar callbacks are not delivered while the group is silenced.

Call InteractiveMusic's methods on the engine's goroutine, as Mixer's and audio's are.

func (*InteractiveMusic) Bar

func (im *InteractiveMusic) Bar() (bar int, inBar float64)

Bar returns the current bar index (counted from 0) and beats into that bar.

func (*InteractiveMusic) Beat

func (im *InteractiveMusic) Beat() float64

Beat returns the current beat position from the piece's BeatTiming on audio.Now (0 when stopped).

func (*InteractiveMusic) Blocked

func (im *InteractiveMusic) Blocked() bool

Blocked reports whether any active audio player is waiting for Mixer.Unblock after audio.NotAllowed. Read in a computation, it subscribes to changes like Music.Blocked.

func (*InteractiveMusic) Close

func (im *InteractiveMusic) Close()

Close stops playback immediately, closes all loaded sounds and players, cancels stem fades, and detaches from the mixer.

func (*InteractiveMusic) CurrentClip

func (im *InteractiveMusic) CurrentClip() string

CurrentClip returns the name of the clip currently playing (or queued to start), or empty when stopped.

func (*InteractiveMusic) FadeStemVolume

func (im *InteractiveMusic) FadeStemVolume(clipName string, index int, volume float32, fade time.Duration)

FadeStemVolume smoothly fades stem index's volume on clipName to volume (clamped to [0, 1]) over fade. When fade <= 0, it behaves like SetStemVolume. NaN is ignored.

func (*InteractiveMusic) OnBar

func (im *InteractiveMusic) OnBar(fn func(bar int)) (stop func())

OnBar registers fn to run on each bar downbeat (0, 1, 2, ...) as playback advances. The returned function unregisters fn.

func (*InteractiveMusic) OnBeat

func (im *InteractiveMusic) OnBeat(fn func(beat int)) (stop func())

OnBeat registers fn to run on each whole beat (0, 1, 2, ...) as playback advances. The returned function unregisters fn.

func (*InteractiveMusic) PendingClip

func (im *InteractiveMusic) PendingClip() string

PendingClip returns the target clip name of a pending transition, or empty when no transition is queued.

func (*InteractiveMusic) Play

func (im *InteractiveMusic) Play(clipName string) error

Play starts playing clipName immediately. If clipName is empty and the piece defines a Playlist, Play starts the playlist instead.

func (*InteractiveMusic) PlayPlaylist

func (im *InteractiveMusic) PlayPlaylist() error

PlayPlaylist starts playing the piece's clips in its configured playlist order (linear/sequential or deterministic shuffle) with optional crossfades.

func (*InteractiveMusic) Playing

func (im *InteractiveMusic) Playing() bool

Playing reports whether adaptive music is currently active (playing or starting).

func (*InteractiveMusic) PlaylistOrder

func (im *InteractiveMusic) PlaylistOrder() []string

PlaylistOrder returns a copy of the current playlist clip order for the configured order mode and seed.

func (*InteractiveMusic) SetPlaylistSeed

func (im *InteractiveMusic) SetPlaylistSeed(seed uint64)

SetPlaylistSeed sets the deterministic shuffle seed and recomputes the playlist order.

func (*InteractiveMusic) SetSourceResolver

func (im *InteractiveMusic) SetSourceResolver(fn func(path string) audio.Source)

SetSourceResolver sets how clip source and stem paths are converted into audio.Source values. Call before Play when constructing with Mixer.Interactive.

func (*InteractiveMusic) SetStemVolume

func (im *InteractiveMusic) SetStemVolume(clipName string, index int, volume float32)

SetStemVolume sets stem index's volume on clipName immediately, clamped to [0, 1]. NaN is ignored. Volumes set before clipName starts playing are preserved and applied when it starts.

func (*InteractiveMusic) SetTiming

func (im *InteractiveMusic) SetTiming(t BeatTiming)

SetTiming sets the BeatTiming used for beat/bar alignment and callbacks, such as a *rhythm.Timing from a rhythm.BeatMap.

func (*InteractiveMusic) StemVolume

func (im *InteractiveMusic) StemVolume(clipName string, index int) float32

StemVolume returns stem index's current mix level on clipName in [0, 1] (1 until changed, 0 for unknown clips or indices).

func (*InteractiveMusic) Stop

func (im *InteractiveMusic) Stop(fade time.Duration)

Stop stops playback, fading out over fade (or immediately when fade <= 0) and cancelling any queued transition or playlist auto-advance.

func (*InteractiveMusic) SwitchTo

func (im *InteractiveMusic) SwitchTo(clipName string) error

SwitchTo transitions from the currently playing clip to clipName using the matching rule in the piece's Transitions table (exact from/to first, then "*" wildcard, or bar-synced with zero fade when no rule matches). If nothing is currently playing, SwitchTo starts clipName immediately.

func (*InteractiveMusic) SwitchToWith

func (im *InteractiveMusic) SwitchToWith(clipName string, tr MusicTransition) error

SwitchToWith transitions to clipName using an explicit transition rule tr.

type InteractiveOptions

type InteractiveOptions struct {
	// ResolveSource converts a clip's source or stem path into an audio.Source.
	// When nil, paths without a URI scheme default to audio.Source{URI: "asset:" + path}.
	ResolveSource func(path string) audio.Source
	// Timing overrides the constant-tempo BeatTiming derived from the piece's BPM and BeatsPerBar.
	// *rhythm.Timing implements BeatTiming directly.
	Timing BeatTiming
	// Seed overrides MusicPlaylist.Seed when UseSeed is true (or when Seed is non-zero).
	Seed uint64
	// UseSeed forces Seed to override MusicPlaylist.Seed even when Seed is 0.
	UseSeed bool
}

InteractiveOptions configures an InteractiveMusic created with Mixer.InteractiveWith.

type Listener2D

type Listener2D struct {
	// Position is where the listener is in the world, usually the 2D camera's center, as tilemap.Camera's X and Y.
	Position math2d.Vec2
	// Velocity is the listener's world-space velocity in world units per second, used for Doppler pitch shift when enabled on a Playback2D.
	Velocity math2d.Vec2
	// Rotation turns the listener clockwise in the world, in radians, as tilemap.Camera.Rotation turns the camera, so left and right are the view's; an infinite or NaN one counts as 0.
	Rotation float32
	// Near is the distance up to which an effect plays at full volume; a negative one or NaN counts as 0.
	Near float32
	// Far is the distance at and beyond which an effect is silent. A Far not greater than Near, infinite or NaN turns distance attenuation off, every effect playing at full volume.
	Far float32
	// Rolloff is how the volume falls between Near and Far.
	Rolloff Rolloff
	// PanWidth is how far to the side of the listener, across the view, an effect pans fully left or right, panning in proportion closer in; 0, less or NaN takes Far, and with distance attenuation off every effect plays centered. An effect straight above or below the listener plays centered at any distance.
	PanWidth float32
	// SpeedOfSound is the speed of sound in world units per second used for Doppler pitch shift; <= 0 or non-finite defaults to DefaultSpeedOfSound (343).
	SpeedOfSound float32
	// DopplerScale scales Doppler pitch shift on Play2D sources that opt into Doppler; <= 0 or non-finite defaults to 1.
	DopplerScale float32
}

Listener2D hears effects placed in a 2D world from where the camera looks, so an effect to the left of the camera plays panned left and an effect further away plays quieter. Its zero value hears every effect at full volume and centered.

Distances are in world units, the same as the positions passed to Pan, Gain and Effect.PlayAt; the camera's zoom does not change them.

func (Listener2D) Gain

func (l Listener2D) Gain(pos math2d.Vec2) float32

Gain returns the volume an effect at pos plays at, from 1 within Near to 0 at Far and beyond, falling by Rolloff between them. Rotation does not change it. A pos with a NaN coordinate is silent, and one with an infinite coordinate too unless attenuation is off.

func (Listener2D) Pan

func (l Listener2D) Pan(pos math2d.Vec2) float32

Pan returns where an effect at pos plays from, -1 for fully left through 0 for centered to 1 for fully right, as audio.Voice.Pan takes it: its offset across the view divided by PanWidth, clamped. A pos with a NaN coordinate plays centered.

func (Listener2D) Voice

func (l Listener2D) Voice(pos math2d.Vec2, v audio.Voice) audio.Voice

Voice returns v with its volume scaled by Gain at pos and its pan set to Pan at pos, the voice an effect at pos plays with. Where the effect is silent, its volume is 0 and it is Muted, since audio plays a volume of 0 as full volume.

type Listener3D

type Listener3D struct {
	// Position is where the listener is in the world, such as sound.Vec3(cam.Pos).
	Position Vec3
	// Velocity is the listener's world-space velocity in world units per second, used for Doppler pitch shift when enabled on a Playback3D.
	Velocity Vec3
	// Forward is the direction the listener faces, such as sound.Vec3(cam.Forward()).
	// A zero or non-finite Forward defaults to (0, 0, -1).
	Forward Vec3
	// Up is the listener's up direction, such as sound.Vec3(cam.Up()).
	// A zero, non-finite, or collinear Up defaults to (0, 1, 0) (or (0, 0, 1) when facing along ±Y).
	Up Vec3
	// Near is the distance up to which an effect plays at full distance gain; a negative value or NaN counts as 0.
	Near float32
	// Far is the distance at and beyond which an effect is silent. A Far not greater than Near,
	// infinite, or NaN turns distance attenuation off.
	Far float32
	// Rolloff is how distance gain falls between Near and Far.
	Rolloff Rolloff
	// RolloffFactor shapes the steepness of RolloffInverse (default 1 when <= 0 or non-finite)
	// and RolloffExponential (default 2 when <= 0 or non-finite). Ignored by RolloffLinear.
	RolloffFactor float32
	// RearGain is the gain multiplier for a sound directly behind the listener (dot(dir, forward) == -1),
	// modeling head-shadow attenuation. Effects in front or at the sides receive a multiplier of 1,
	// and effects behind interpolate linearly from 1 at the lateral plane down to RearGain directly behind.
	// Zero, negative, or NaN uses DefaultRearGain (0.7); values above 1 clamp to 1 (disabling rear attenuation).
	RearGain float32
	// PanWidth, when positive and finite, computes pan as the source's lateral offset along the
	// listener's right axis divided by PanWidth, clamped to [-1, 1], matching Listener2D.
	// When 0, negative, or non-finite, pan uses the 3D directional azimuth dot(dir, right),
	// which is 0 directly in front, behind, above, or below, -1 directly left, and +1 directly right.
	PanWidth float32
	// SpeedOfSound is the speed of sound in world units per second used for Doppler pitch shift;
	// <= 0 or non-finite defaults to DefaultSpeedOfSound (343).
	SpeedOfSound float32
	// DopplerScale scales Doppler pitch shift on Play3D sources that opt into Doppler;
	// <= 0 or non-finite defaults to 1.
	DopplerScale float32
}

Listener3D hears effects placed in a right-handed Y-up 3D world (+X right, +Y up, -Z forward) from where the 3D camera looks: an effect to the left of the camera plays panned left, one to the right panned right, one further away plays quieter, and one behind the camera plays quieter than an equidistant effect in front while still panned to its side.

Its zero value sits at the origin facing -Z with +Y up, disables distance attenuation, pans by lateral azimuth, and attenuates effects behind the listener using DefaultRearGain.

Example

Listener3D spatializes 3D positions in right-handed Y-up space (+X right, +Y up, -Z forward): sounds behind the camera play quieter than equidistant sounds in front while staying panned to their side.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/sound"
)

func main() {
	l := sound.Listener3D{
		Position: sound.V3(0, 0, 0),
		Forward:  sound.V3(0, 0, -1),
		Up:       sound.V3(0, 1, 0),
		Near:     2,
		Far:      22,
	}
	frontLeft := l.Spatialize(sound.V3(-6, 0, -6), sound.Spatial3DOptions{})
	behindLeft := l.Spatialize(sound.V3(-6, 0, 6), sound.Spatial3DOptions{})
	fmt.Printf("front-left: gain=%.2f pan=%.2f\n", frontLeft.Gain, frontLeft.Pan)
	fmt.Printf("behind-left: gain=%.2f pan=%.2f\n", behindLeft.Gain, behindLeft.Pan)
}
Output:
front-left: gain=0.68 pan=-0.71
behind-left: gain=0.53 pan=-0.71

func (Listener3D) Gain

func (l Listener3D) Gain(pos Vec3) float32

Gain returns the combined spatial gain for an effect at pos in [0, 1]: distance attenuation from Near to Far times rear head-shadow attenuation when behind the listener. A pos with a NaN coordinate is silent.

func (*Listener3D) LookAt

func (l *Listener3D) LookAt(target, up Vec3)

LookAt orients l at its current Position toward target with world up direction up. If target equals Position or is non-finite, Forward is left unchanged.

func (Listener3D) Pan

func (l Listener3D) Pan(pos Vec3) float32

Pan returns where an effect at pos plays from, -1 for fully left through 0 for centered to 1 for fully right, as audio.Voice.Pan takes it. Effects at the listener, straight ahead, straight behind, straight above/below, or with a NaN coordinate play centered.

func (*Listener3D) SetPose

func (l *Listener3D) SetPose(pos, forward, up Vec3)

SetPose updates l's Position, Forward, and Up without changing its attenuation or pan settings.

func (Listener3D) Spatialize

func (l Listener3D) Spatialize(pos Vec3, opts Spatial3DOptions) Spatial3D

Spatialize computes distance attenuation, rear head-shadow attenuation, optional directional source cone attenuation, and stereo pan for a source at pos relative to l.

func (Listener3D) Voice

func (l Listener3D) Voice(pos Vec3, v audio.Voice) audio.Voice

Voice returns v with its volume scaled by l.Gain(pos) and its pan set to l.Pan(pos). Where the effect is silent, its volume is 0 and it is Muted, since audio plays a volume of 0 as full volume.

func (Listener3D) VoiceWithOptions

func (l Listener3D) VoiceWithOptions(pos Vec3, v audio.Voice, opts Spatial3DOptions) audio.Voice

VoiceWithOptions returns v with its volume scaled by l.Spatialize(pos, opts).Gain and its pan set to l.Spatialize(pos, opts).Pan. Where the effect is silent, its volume is 0 and it is Muted.

type Mixer

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

Mixer sets how loud a game's sounds and music play: a master volume and a volume for each group the app names, such as "effects", "music" and "ui", each from 0 to 1 and 1 until set. It keeps them in the app's storage (core.Storage), so they hold across launches, pauses gameplay groups with SetPaused while letting pause-exempt groups (SetPauseExempt) keep playing, and plays nothing while the app is in the background or suspended.

An effect plays at its own voice's volume times its group's and the master volume, and music at its group's and the master volume; a volume change applies at once to the effects playing, through their audio.Playback, and to music as it plays. An effect whose group or master volume reaches 0 plays on in silence and is heard again as the volume comes back.

The mixer's methods, its effects' and its music's are called on the engine's goroutine, as audio's are.

Example

A Mixer keeps group volumes in the app's storage, so the player's settings survive a restart.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/sound"
	"github.com/nsgo-dev/nsgo/core"
)

func main() {
	root := core.NewRoot(core.RootOptions{})
	defer root.Dispose()

	m := sound.NewMixer(root, "mixer")
	m.SetVolume("music", 0.3)
	m.SetMaster(0.8)

	again := sound.NewMixer(root, "mixer")
	fmt.Println(again.Volume("music"), again.Master(), again.Volume("sfx"))
}
Output:
0.3 0.8 1

func NewMixer

func NewMixer(cx *core.Scope, key string) *Mixer

NewMixer returns a mixer that keeps its volumes in cx's storage under keys starting with key, such as "sound", and lives as long as cx.

The mixer mutes everything while cx's window is in the background (core.Env.Lifecycle), that is hidden, minimized or covered on a desktop and the app in the background on a phone: it silences the effects playing, pauses the music and, as the window shows again, restores the effects still playing and plays the music on from there.

Until SetMono is called, the mixer follows the platform's mono audio setting once NSGo exposes it on core.Env (nsgo-dev/nsgo#2677; false on NSGo v0.3.4).

func (*Mixer) AddBusDucking

func (m *Mixer) AddBusDucking(rule BusDuckRule)

AddBusDucking appends or replaces the bus ducking rule matching rule.Bus and rule.By. Rules with an empty Bus or By, Bus == By, or Amount <= 0 are ignored.

func (*Mixer) Balance

func (m *Mixer) Balance() float32

Balance returns the mixer's stereo left/right balance offset in [-1, 1], 0 until set.

func (*Mixer) BusDucking

func (m *Mixer) BusDucking() []BusDuckRule

BusDucking returns a copy of m's configured bus ducking rules.

func (*Mixer) ClearBusZoneGains

func (m *Mixer) ClearBusZoneGains()

ClearBusZoneGains removes all transient sound-zone bus gain multipliers on m.

func (*Mixer) ConcurrencyGroup

func (m *Mixer) ConcurrencyGroup(name string) (ConcurrencyGroup, bool)

ConcurrencyGroup returns the named ConcurrencyGroup configuration and whether it is registered on m.

func (*Mixer) Cue

func (m *Mixer) Cue(group string, limit int, seed uint64, opts CueOptions, sounds ...*audio.Sound) *Cue

Cue builds a Cue whose sounds play through m in group with per-sound voice limit. Any nil sounds are skipped; any Clips already present in opts are preserved before sounds.

func (*Mixer) DebugSnapshot

func (m *Mixer) DebugSnapshot() MixerDebugSnapshot

DebugSnapshot returns a deterministic snapshot of active voices, global voice budget, per-concurrency-group counts and counters, and per-bus voice counts and ducking gains.

func (*Mixer) Effect

func (m *Mixer) Effect(s *audio.Sound, group string, limit int) *Effect

Effect returns s played through the mixer in group, at most limit at once (0 for no limit of its own). Close s as the app is done with it, as without the mixer.

The group's bus effect chain (SetGroupEffects) does not apply here: s is already decoded, so it plays dry. Load a source through LoadEffect to play it with the chain applied.

func (*Mixer) FollowSystemMono

func (m *Mixer) FollowSystemMono()

FollowSystemMono clears any explicit SetMono override so the mixer follows the platform's mono audio setting (nsgo-dev/nsgo#2677; false on NSGo v0.3.4).

func (*Mixer) GroupEffects

func (m *Mixer) GroupEffects(group string) EffectChain

GroupEffects returns a copy of the DSP bus effect chain configured for group, or nil when none is set.

func (*Mixer) Interactive

func (m *Mixer) Interactive(group string, piece MusicPieceSource) *InteractiveMusic

Interactive returns an InteractiveMusic controller playing piece through m in group. piece may be a sound.MusicPiece, *sound.MusicPiece, or *resource.Music.

func (*Mixer) InteractiveWith

func (m *Mixer) InteractiveWith(group string, piece MusicPieceSource, opts InteractiveOptions) *InteractiveMusic

InteractiveWith returns an InteractiveMusic controller playing piece through m in group with opts.

func (*Mixer) Listener2D

func (m *Mixer) Listener2D() Listener2D

Listener2D returns the mixer's active 2D listener.

func (*Mixer) Listener3D

func (m *Mixer) Listener3D() Listener3D

Listener3D returns the mixer's active 3D listener.

func (*Mixer) LoadEffect

func (m *Mixer) LoadEffect(src audio.Source, group string, limit int, done func(*Effect, error))

LoadEffect loads src as an effect played through the mixer in group, at most limit at once, as Effect does for a sound already loaded, applying group's bus effect chain (SetGroupEffects) first: a source holding in-memory 16-bit PCM WAV data is processed through the chain before loading, and any other source loads unchanged, with one log line per group saying its effects are skipped for it. done receives the effect or why it did not load, as audio.LoadSound's callback does.

func (*Mixer) Master

func (m *Mixer) Master() float32

Master returns the master volume, its default (SetDefaultMaster) or 1 until set. Read in a computation, it subscribes it to changes, as core.Storage does.

func (*Mixer) MaxVoices

func (m *Mixer) MaxVoices() int

MaxVoices returns the mixer's global concurrent voice budget (DefaultMaxVoices until set).

func (*Mixer) Mono

func (m *Mixer) Mono() bool

Mono reports whether mono voice panning is currently active on the mixer, either from SetMono or from the platform's mono audio switch (nsgo-dev/nsgo#2677).

func (*Mixer) Music

func (m *Mixer) Music(group string) *Music

Music returns music played through the mixer in group, which plays nothing until Play.

func (*Mixer) PauseExempt

func (m *Mixer) PauseExempt(group string) bool

PauseExempt reports whether group keeps playing while the mixer is paused with SetPaused.

func (*Mixer) Paused

func (m *Mixer) Paused() bool

Paused reports whether gameplay audio is paused by SetPaused.

func (*Mixer) PlayCue

func (m *Mixer) PlayCue(cue *Cue) (CuePick, bool)

PlayCue plays the next variant of cue through its Mixer Effect.

func (*Mixer) ProcessSource

func (m *Mixer) ProcessSource(group string, src audio.Source) (audio.Source, error)

ProcessSource applies group's configured DSP bus chain to an in-memory 16-bit PCM WAV audio.Source and returns a new audio.Source containing the processed WAV bytes. When group has no effects configured, src is returned unchanged.

func (*Mixer) RemoveConcurrencyGroup

func (m *Mixer) RemoveConcurrencyGroup(name string)

RemoveConcurrencyGroup unregisters the named concurrency group from m. Active voices previously in the group recover from any group ducking immediately.

func (*Mixer) RenderCuePCM

func (m *Mixer) RenderCuePCM(group string, cue *Cue) (CuePick, PCM)

RenderCuePCM picks the next variant of cue, resamples its PCM by the sampled pitch, applies the sampled volume times group's effective mixer gain (0 when muted or in the background), and runs group's configured DSP effect chain if any.

func (*Mixer) SetBalance

func (m *Mixer) SetBalance(balance float32)

SetBalance sets the stereo left/right balance offset in [-1, 1] (-1 full left, 0 centered, +1 full right). Values outside [-1, 1] clamp, and NaN resets to 0.

When mono is off, every voice the mixer starts or updates adds balance to its pan and clamps to [-1, 1]. While mono is on, every voice plays at pan 0 while the configured balance is kept for when mono is turned off.

func (*Mixer) SetBusDucking

func (m *Mixer) SetBusDucking(rules ...BusDuckRule)

SetBusDucking replaces m's bus ducking rules. Rules with an empty Bus or By, Bus == By, or Amount <= 0 are ignored. Existing bus duck animations are reset and recomputed immediately against currently playing sounds and music.

func (*Mixer) SetBusZoneGain

func (m *Mixer) SetBusZoneGain(group string, gain float32)

SetBusZoneGain sets a transient gain multiplier in [0, 1] for group (used by sound zones) without writing to core.Storage. NaN resets to 1.

func (*Mixer) SetCaptionHandler

func (m *Mixer) SetCaptionHandler(fn func(CaptionEvent))

SetCaptionHandler installs fn to receive a CaptionEvent each time a captioned Effect or Cue starts a playback on m. A nil fn removes the handler.

Pair with a11y.BindSoundCaptions to feed an a11y.CaptionTrack (and a11y.SoundIndicatorView) automatically without package sound importing package a11y.

func (*Mixer) SetConcurrencyGroup

func (m *Mixer) SetConcurrencyGroup(name string, cfg ConcurrencyGroup)

SetConcurrencyGroup registers or updates a named shared ConcurrencyGroup on m. Empty names are ignored.

func (*Mixer) SetDefaultMaster

func (m *Mixer) SetDefaultMaster(v float32)

SetDefaultMaster sets the master volume the mixer has until SetMaster keeps one, clamped to 0 to 1, such as a project file's. It keeps nothing in the storage, so a volume the player set wins; set it before the game reads volumes, as it changes no subscribed computation.

func (*Mixer) SetDefaultVolume

func (m *Mixer) SetDefaultVolume(group string, v float32)

SetDefaultVolume sets the volume group has until SetVolume keeps one, clamped to 0 to 1, such as a project file's bus volume. It keeps nothing in the storage, so a volume the player set wins; set it before the game reads volumes, as it changes no subscribed computation.

func (*Mixer) SetGroupEffects

func (m *Mixer) SetGroupEffects(group string, effects ...BusEffect)

SetGroupEffects configures the DSP bus effect chain for group, replacing any previous chain. Passing no effects clears group's chain.

func (*Mixer) SetListener2D

func (m *Mixer) SetListener2D(l Listener2D)

SetListener2D sets the mixer's active 2D listener and refreshes every live Playback2D started through Effect.Play2D or Cue.Play2D: each playback updates its volume, live stereo pan, Doppler pitch rate (when enabled), and distance low-pass cutoff immediately.

func (*Mixer) SetListener3D

func (m *Mixer) SetListener3D(l Listener3D)

SetListener3D sets the mixer's active 3D listener and refreshes every live Playback3D started through Effect.Play3D or Cue.Play3D: each playback recomputes its 3D spatialization against l and updates its underlying audio.Playback volume, stereo pan, Doppler playback rate (when enabled), and distance low-pass cutoff immediately (respecting master/group volumes, ducking, zones, mono/balance, pause, suspend, and background muting).

func (*Mixer) SetMaster

func (m *Mixer) SetMaster(v float32) error

SetMaster sets the master volume, clamped to 0 to 1, and keeps it. It fails with a *core.StorageFullError when the storage is full, keeping the volume it had.

func (*Mixer) SetMaxVoices

func (m *Mixer) SetMaxVoices(maxVoices int)

SetMaxVoices sets the mixer's global concurrent voice budget across all effects and concurrency groups. Values <= 0 reset the budget to DefaultMaxVoices (30). When the budget is reached, higher- or equal-priority sounds steal the lowest-priority (oldest on ties) active voice, while strictly lower-priority sounds are refused.

func (*Mixer) SetMono

func (m *Mixer) SetMono(mono bool)

SetMono explicitly enables or disables mono voice panning on the mixer, overriding the platform's mono audio switch.

While mono is active, every voice the mixer starts (via Effect.Play, Effect.PlayAt, Effect.PlayAt3D, Effect.Play3D, and Cue variants) or updates plays centered at pan 0 while keeping distance, rear, and cone attenuation unchanged, so distance cues remain and listeners still report the true direction for directional captions.

Stereo audio files (such as stereo music or ambiences) keep their channels until NSGo supports mixing the output down to mono (nsgo-dev/nsgo#2676). Call FollowSystemMono to clear the override and follow the platform setting again.

func (*Mixer) SetPauseExempt

func (m *Mixer) SetPauseExempt(group string, exempt bool)

SetPauseExempt sets whether group keeps playing while the mixer is paused with SetPaused, such as a "ui" group for pause-menu sounds. Exempt groups are still silenced while the app is in the background or while the mixer is suspended (Suspend). Changing a group's exemption while paused applies at once to effects and music in that group.

func (*Mixer) SetPaused

func (m *Mixer) SetPaused(paused bool)

SetPaused pauses or resumes gameplay audio on the mixer, as when a pause menu opens or closes. While paused, every group not marked exempt with SetPauseExempt is silenced: effects playing are silenced through their audio.Playback without stopping, new Effect.Play calls play nothing, and music pauses at its current position. Groups marked exempt (such as "ui") keep playing while paused, though they are still silenced in the background or while suspended. When resumed, effects still playing return to their volume and music plays on from where it paused, unless the app is in the background or the mixer is suspended.

Pair with game.Loop.OnPause (loop.OnPause = mixer.SetPaused) so gameplay audio pauses and resumes with the loop while backgrounding pauses and resumes everything in sync through core.Env.Lifecycle.

func (*Mixer) SetVolume

func (m *Mixer) SetVolume(group string, v float32) error

SetVolume sets group's volume, clamped to 0 to 1, and keeps it. It fails with a *core.StorageFullError when the storage is full, keeping the volume it had.

func (*Mixer) SetZones

func (m *Mixer) SetZones(defaultBus string, zones ...Zone) *ZoneRouter

SetZones installs a ZoneRouter on m with defaultBus and zones, applies its initial bus weights, and returns the router.

func (*Mixer) StepZones2D

func (m *Mixer) StepZones2D(pos math2d.Vec2, dt time.Duration) string

StepZones2D updates m's ZoneRouter against the 2D listener position pos over dt, applies the resulting bus crossfade weights to m, and returns the active bus name.

func (*Mixer) StepZones3D

func (m *Mixer) StepZones3D(pos Vec3, dt time.Duration) string

StepZones3D updates m's ZoneRouter against the 3D listener position pos over dt, applies the resulting bus crossfade weights to m, and returns the active bus name.

func (*Mixer) Suspend

func (m *Mixer) Suspend() (resume func())

Suspend silences the mixer until resume is called, as the background does: it silences the sounds playing (including pause-exempt groups), plays no new ones and pauses the music, which plays on from where it paused once every Suspend has been resumed. A game suspends its sound while something else has the speakers, such as a cutscene (cutscene.Player does). Calling resume again does nothing.

func (*Mixer) Suspended

func (m *Mixer) Suspended() bool

Suspended reports whether a Suspend has not been resumed yet.

func (*Mixer) Unblock

func (m *Mixer) Unblock()

Unblock retries any music tracks whose playback was refused with audio.NotAllowed, such as tracks started before the page's first user gesture on the web. Blocked tracks keep their group volume, crossfade level, loop settings and any armed intro handoff, starting from position 0 once audible; tracks in a silent, paused, suspended or backgrounded mixer clear their blocked state and start as soon as the group becomes audible. Calling Unblock when no track is blocked does nothing.

Call Unblock from a press, touch or key handler, or assign the mixer to input.Actions.Mixer so the first press, touch or key press retries automatically until NSGo reports audio unlock directly (nsgo-dev/nsgo#2675).

func (*Mixer) Volume

func (m *Mixer) Volume(group string) float32

Volume returns group's volume: its default (SetDefaultVolume), or 1, for a group never set. Read in a computation, it subscribes it to changes, as core.Storage does.

func (*Mixer) Zones

func (m *Mixer) Zones() *ZoneRouter

Zones returns the ZoneRouter installed on m by SetZones, or nil if none is installed.

type MixerDebugSnapshot

type MixerDebugSnapshot struct {
	// ActiveVoices is the total number of live non-fading effect voices currently playing across the mixer.
	ActiveVoices int `json:"active_voices"`
	// FadingVoices is the number of stolen voices currently fading out before stopping.
	FadingVoices int `json:"fading_voices,omitempty"`
	// MaxVoices is the mixer's global voice budget.
	MaxVoices int `json:"max_voices"`
	// Groups lists concurrency group telemetry sorted by group name.
	Groups []ConcurrencyGroupDebug `json:"groups,omitempty"`
	// Buses lists active bus voice counts and current ducking gain multipliers sorted by bus name.
	Buses []BusDebug `json:"buses,omitempty"`
}

MixerDebugSnapshot summarizes active voice usage, concurrency groups, and bus ducking on a Mixer for debug overlays and MCP inspection.

type Music

type Music struct {
	// Group is the group whose volume the music plays at.
	Group string
	// Loop has each track Play starts after it is set start over at its end.
	Loop bool
	// OnError receives a playback error that permanently ends a track. The error
	// is a *MusicError with the failed source and the underlying audio error.
	// NotAllowed
	// is omitted because it is reported through Blocked and can be retried with
	// Mixer.Unblock. The callback runs on the engine goroutine.
	OnError func(error)
	// contains filtered or unexported fields
}

Music plays long tracks through a mixer, one at a time, each through an audio.Player, crossfading from one to the next.

Example

Music plays one long track at a time through the mixer's "music" group, crossfading into the next. PlayLooped plays a single file once from the start and loops back to a loop point inside the native player; PlayWithIntro pairs separate intro and loop files. Playing needs the platform's audio, so this example is compiled but not run.

package main

import (
	"time"

	"github.com/nsgo-dev/game/pkg/sound"
	"github.com/nsgo-dev/nsgo/audio"
	"github.com/nsgo-dev/nsgo/core"
)

func main() {
	root := core.NewRoot(core.RootOptions{})
	defer root.Dispose()
	mixer := sound.NewMixer(root, "mixer")
	music := mixer.Music("music")

	// The title screen's theme loops; the first level's track plays a 12-second intro once and loops from 12s inside one player.
	music.Loop = true
	music.Play(audio.Source{URI: "asset:music/title.m4a"}, 0)
	music.PlayLooped(audio.Source{URI: "asset:music/level1.m4a"}, 12*time.Second, 2*time.Second)

	// Separate intro and loop assets can use PlayWithIntro when a single file is not available.
	music.PlayWithIntro(sound.SectionedTrack{
		Intro: audio.Source{URI: "asset:music/boss-intro.m4a"},
		Loop:  audio.Source{URI: "asset:music/boss-loop.m4a"},
	}, 2*time.Second)

	// Pausing the game fades the music out.
	music.Stop(500 * time.Millisecond)
}

func (*Music) Blocked

func (mu *Music) Blocked() bool

Blocked reports whether the current track is waiting to retry after the platform refused playback with audio.NotAllowed (such as browser autoplay before the page's first user gesture). Read in a computation, it subscribes it to changes, so a game can show a "tap for sound" hint until Mixer.Unblock retries the track or the track is stopped or replaced.

func (*Music) Play

func (mu *Music) Play(src audio.Source, fade time.Duration)

Play plays src, fading it in over fade as the tracks playing fade out, by the display's frames (core.Scope.Animate), and closing them as they reach silence; it switches at once when fade is 0. A track that fails with audio.NotAllowed stays current and blocked until Mixer.Unblock retries it; any other failure, such as a track the platform cannot decode, ends the track and plays nothing.

When the music's group has a bus effect chain (SetGroupEffects), a src holding in-memory 16-bit PCM WAV data is processed through the chain before playing, as ProcessSource does; any other source, such as an MP3 or AAC file or a URI, plays unchanged, with one log line per group saying its effects are skipped for it.

func (*Music) PlayLooped

func (mu *Music) PlayLooped(src audio.Source, loopStart, fade time.Duration)

PlayLooped plays src from the beginning on the first pass and loops back to loopStart each time it reaches its end, fading in over fade as any previous music fades out. It opens one audio.Player with audio.PlayerOptions.LoopStart so the loop point runs inside the native player with no two-player handoff seam.

Playback always loops regardless of mu.Loop, without changing mu.Loop for subsequent Play calls. A loopStart <= 0 (or >= the track's duration) loops the full track from the start. If src is empty, PlayLooped stops the music over fade.

As with Play, a src holding in-memory 16-bit PCM WAV data is processed through the music's group bus effect chain (SetGroupEffects) before playing.

func (*Music) PlaySections

func (mu *Music) PlaySections(intro, loop audio.Source, fade time.Duration)

PlaySections plays intro once without looping, preloads loop with looping enabled, and hands off to loop at the end of intro, fading in over fade as any previous music fades out. When the backend reports intro's duration and progress, loop is scheduled slightly ahead of intro's end rather than waiting for OnEnd, with OnEnd kept as a fallback when duration is unknown; intro finishes its remaining samples before closing. Because this coordinates two audio.Players across the engine turn, it may still leave a slight seam under load or on the web; prefer PlayLooped with a single file and a loop point where possible. Stopping or starting another track before intro ends cancels loop so it never plays.

If intro is empty, loop plays directly with looping enabled; if loop is empty, intro plays once without looping; if both are empty, PlaySections stops the music over fade.

Each source is processed through the music's group bus effect chain (SetGroupEffects) before playing, as Play does.

func (*Music) PlayWithIntro

func (mu *Music) PlayWithIntro(track SectionedTrack, fade time.Duration)

PlayWithIntro plays track's intro once and hands off to its looping section, fading in over fade as any previous music fades out.

Prefer PlayLooped with a single file and a loop point for a sample-accurate loop seam; PlayWithIntro is for assets split across two files.

func (*Music) Stop

func (mu *Music) Stop(fade time.Duration)

Stop fades the music out over fade, closing its tracks as they reach silence; at once when fade is 0.

type MusicClip

type MusicClip struct {
	Name   string
	Source string
	Stems  []string
	Loop   bool
	Next   string
}

MusicClip is one named section of a MusicPiece: either a single audio Source or several synchronized Stems, whether it loops, and an optional Next clip played after a non-looping clip ends.

type MusicError

type MusicError struct {
	Source audio.Source
	Err    error
}

MusicError identifies the source whose player failed and unwraps the platform's audio error. It is passed to Music.OnError.

func (*MusicError) Error

func (e *MusicError) Error() string

Error returns a message identifying the failed music source and underlying playback error.

func (*MusicError) Unwrap

func (e *MusicError) Unwrap() error

Unwrap returns the underlying platform audio error for errors.Is/errors.As.

type MusicPiece

type MusicPiece struct {
	// Name is an optional human-readable name for the piece.
	Name string
	// BPM is the piece's tempo in beats per minute; defaults to 120 when non-positive or non-finite.
	BPM float32
	// BeatsPerBar is the number of beats in one bar; defaults to 4 when non-positive.
	BeatsPerBar int
	// Clips lists the piece's named clips.
	Clips []MusicClip
	// Transitions lists the rules governing SwitchTo between clips.
	Transitions []MusicTransition
	// Playlist configures automatic playback through the piece's clips.
	Playlist *MusicPlaylist
}

MusicPiece describes an adaptive music piece: its tempo and meter, named clips (single source or synchronized stems), transition table, and optional playlist.

func (MusicPiece) MusicPiece

func (p MusicPiece) MusicPiece() MusicPiece

MusicPiece returns p so both MusicPiece and *MusicPiece satisfy MusicPieceSource.

type MusicPieceSource

type MusicPieceSource interface {
	MusicPiece() MusicPiece
}

MusicPieceSource supplies a MusicPiece to Mixer.Interactive and Mixer.InteractiveWith. MusicPiece, *MusicPiece, and *resource.Music satisfy it.

type MusicPlaylist

type MusicPlaylist struct {
	Order     PlaylistOrder
	Crossfade float32
	Seed      uint64
}

MusicPlaylist configures automatic sequential or seeded-shuffle playback across a piece's clips with an optional crossfade in seconds.

type MusicTransition

type MusicTransition struct {
	From    string
	To      string
	At      TransitionAt
	FadeOut float32
	FadeIn  float32
	Via     string
}

MusicTransition describes how InteractiveMusic switches from From ("*" matches any clip) to To at At, fading the outgoing clip out over FadeOut seconds and the incoming clip in over FadeIn seconds, optionally playing Via once in between.

type PCM

type PCM struct {
	Samples    []float64
	SampleRate int
	Channels   int
}

PCM holds interleaved normalized audio samples in [-1, 1] at a fixed sample rate and channel count.

func ApplyGain

func ApplyGain(pcm PCM, volume float64) PCM

ApplyGain returns a copy of pcm with every sample scaled by volume. Negative volumes clamp to 0; NaN or infinite volumes leave samples unchanged.

func DecodePCM

func DecodePCM(wav []byte) (PCM, error)

DecodePCM decodes a 16-bit signed linear PCM RIFF/WAVE buffer into a PCM buffer.

Example

EncodeWAV and DecodePCM convert between samples and WAV files, and ResamplePitch shifts a sound's pitch by changing its length.

package main

import (
	"fmt"
	"math"

	"github.com/nsgo-dev/game/pkg/sound"
)

// tone returns n frames of a mono 440 Hz sine at 8 kHz.
func tone(n int) sound.PCM {
	s := make([]float64, n)
	for i := range s {
		s[i] = 0.5 * math.Sin(2*math.Pi*440*float64(i)/8000)
	}
	return sound.PCM{Samples: s, SampleRate: 8000, Channels: 1}
}

func main() {
	wav, err := tone(8000).EncodeWAV()
	if err != nil {
		fmt.Println(err)
		return
	}
	pcm, err := sound.DecodePCM(wav)
	fmt.Println(err, pcm.SampleRate, pcm.Channels, pcm.Frames())
	fmt.Println(sound.ResamplePitch(pcm, 2).Frames())
}
Output:
<nil> 8000 1 8000
4000

func ResamplePitch

func ResamplePitch(pcm PCM, pitch float64) PCM

ResamplePitch resamples pcm by pitch using Catmull-Rom cubic interpolation without mutating pcm. A pitch > 1 plays higher and faster (fewer output frames, approximately Frames()/pitch); a pitch < 1 plays lower and slower (more output frames). Invalid non-positive or non-finite pitch defaults to 1.

func (PCM) EncodeWAV

func (p PCM) EncodeWAV() ([]byte, error)

EncodeWAV encodes p as a canonical 16-bit signed linear PCM RIFF/WAVE buffer.

func (PCM) Frames

func (p PCM) Frames() int

Frames returns the number of complete multi-channel frames in p.

type PlayOptions

type PlayOptions struct {
	// Concurrency overrides Effect.Concurrency for this playback when non-empty.
	Concurrency string
	// Owner identifies the sound's emitter (for example an entity ID, string, or pointer) when the
	// concurrency group uses ScopeOwner. Any comparable value may be used; nil or uncomparable values
	// fall back to the shared owner bucket.
	Owner any
	// Priority ranks this playback during ResolveLowestPriority and global voice-budget stealing (higher wins).
	// When HasPriority is true or Priority is non-zero, it overrides Effect.Priority.
	Priority int
	// HasPriority forces Priority (including 0) to override Effect.Priority.
	HasPriority bool
	// Caption overrides Effect.Caption for this playback when Caption.Key is non-empty.
	Caption Caption
}

PlayOptions configures per-playback concurrency and priority settings for Effect.PlayWith, Effect.PlayAtWith, Effect.PlayAt3DWith, Effect.Play3DWith, and their Cue counterparts.

type Playback2D

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

Playback2D is a live 2D-positioned playback started by Effect.Play2D or Cue.Play2D. Moving the source via SetPosition, updating velocity via SetVelocity, or moving the listener via Mixer.SetListener2D recomputes its spatialization and updates its underlying audio.Playback volume, stereo pan, and (when Doppler is enabled) playback rate live while honoring mixer volumes, ducking, zones, mono/balance, pause, suspend, and background states.

All methods on a nil or ended Playback2D are safe no-ops.

func (*Playback2D) CutoffHz

func (p *Playback2D) CutoffHz() float32

CutoffHz returns the latest computed distance low-pass cutoff in hertz (0 when bypassed).

func (*Playback2D) Distance

func (p *Playback2D) Distance() float32

Distance returns the playback's latest computed Euclidean distance to the listener.

func (*Playback2D) Doppler

func (p *Playback2D) Doppler() bool

Doppler reports whether Doppler pitch shifting is enabled on this playback.

func (*Playback2D) Ended

func (p *Playback2D) Ended() bool

Ended reports whether the playback has finished, was stopped, or never started.

func (*Playback2D) FarCutoffHz

func (p *Playback2D) FarCutoffHz() float32

FarCutoffHz returns the configured distance low-pass cutoff at Far (0 when disabled).

func (*Playback2D) Gain

func (p *Playback2D) Gain() float32

Gain returns the playback's latest computed 2D spatial gain in [0, 1].

func (*Playback2D) Options

func (p *Playback2D) Options() Spatial2DOptions

Options returns the playback's per-source 2D spatialization options.

func (*Playback2D) Pan

func (p *Playback2D) Pan() float32

Pan returns the playback's latest computed stereo pan in [-1, 1].

func (*Playback2D) Playing

func (p *Playback2D) Playing() bool

Playing reports whether the playback is currently active.

func (*Playback2D) Position

func (p *Playback2D) Position() math2d.Vec2

Position returns the playback's current 2D world position.

func (*Playback2D) Rate

func (p *Playback2D) Rate() float32

Rate returns the playback's effective playback rate including any active Doppler pitch shift.

func (*Playback2D) SetDoppler

func (p *Playback2D) SetDoppler(enabled bool)

SetDoppler enables or disables Doppler pitch shifting on this playback and refreshes its rate.

func (*Playback2D) SetFarCutoffHz

func (p *Playback2D) SetFarCutoffHz(hz float32)

SetFarCutoffHz sets the distance low-pass cutoff at Far and recomputes CutoffHz.

func (*Playback2D) SetListener

func (p *Playback2D) SetListener(l Listener2D)

SetListener updates the 2D listener used by this playback and refreshes its volume, pan, Doppler rate, and cutoff.

func (*Playback2D) SetOptions

func (p *Playback2D) SetOptions(opts Spatial2DOptions)

SetOptions replaces the playback's per-source 2D spatialization options and refreshes immediately.

func (*Playback2D) SetPosition

func (p *Playback2D) SetPosition(pos math2d.Vec2)

SetPosition moves the playback to pos, recomputes its 2D spatialization, and updates the underlying audio.Playback volume, pan, and (when Doppler is enabled) rate immediately.

func (*Playback2D) SetRate

func (p *Playback2D) SetRate(rate float32)

SetRate updates the playback's base rate and reapplies Doppler scaling when enabled.

func (*Playback2D) SetVelocity

func (p *Playback2D) SetVelocity(vel math2d.Vec2)

SetVelocity updates the playback's 2D world velocity and refreshes its Doppler rate when enabled.

func (*Playback2D) Stop

func (p *Playback2D) Stop()

Stop stops the playback immediately. Calling Stop on a nil or already-ended Playback2D is a no-op.

func (*Playback2D) Velocity

func (p *Playback2D) Velocity() math2d.Vec2

Velocity returns the playback's current 2D world velocity.

type Playback3D

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

Playback3D is a live 3D-positioned playback started by Effect.Play3D or Cue.Play3D. Moving the source via SetPosition, updating velocity via SetVelocity, updating its directional cone or options via SetOptions, or moving the listener via Mixer.SetListener3D recomputes its spatialization and updates its underlying audio.Playback volume, stereo pan, and (when Doppler is enabled) playback rate live while honoring the mixer's group volume, master volume, ducking, zones, mono/balance, pause, suspend, and background states.

All methods on a nil or ended Playback3D are safe no-ops.

func (*Playback3D) CutoffHz

func (p *Playback3D) CutoffHz() float32

CutoffHz returns the latest computed distance low-pass cutoff in hertz (0 when bypassed).

func (*Playback3D) Ended

func (p *Playback3D) Ended() bool

Ended reports whether the playback has finished, was stopped, or never started.

func (*Playback3D) Gain

func (p *Playback3D) Gain() float32

Gain returns the playback's latest computed spatial gain in [0, 1].

func (*Playback3D) Options

func (p *Playback3D) Options() Spatial3DOptions

Options returns the playback's current per-source 3D spatialization options.

func (*Playback3D) Pan

func (p *Playback3D) Pan() float32

Pan returns the playback's latest computed stereo pan in [-1, 1].

func (*Playback3D) Playing

func (p *Playback3D) Playing() bool

Playing reports whether the playback is currently active.

func (*Playback3D) Position

func (p *Playback3D) Position() Vec3

Position returns the playback's current 3D world position.

func (*Playback3D) Rate

func (p *Playback3D) Rate() float32

Rate returns the playback's effective playback rate including any active Doppler pitch shift.

func (*Playback3D) SetOptions

func (p *Playback3D) SetOptions(opts Spatial3DOptions)

SetOptions updates the playback's per-source 3D spatialization options (such as a rotating directional cone, Doppler toggle, or distance low-pass cutoff), recomputes spatialization, and updates the underlying audio.Playback volume, pan, and rate.

func (*Playback3D) SetPosition

func (p *Playback3D) SetPosition(pos Vec3)

SetPosition moves the playback to pos, recomputes its 3D spatialization against its mixer's Listener3D, and updates the underlying audio.Playback volume immediately if still playing.

func (*Playback3D) SetRate

func (p *Playback3D) SetRate(rate float32)

SetRate updates the playback's base playback rate on the underlying audio.Playback when still playing, reapplying Doppler scaling when enabled.

func (*Playback3D) SetVelocity

func (p *Playback3D) SetVelocity(vel Vec3)

SetVelocity updates the playback's 3D world velocity and refreshes its Doppler rate when enabled.

func (*Playback3D) Spatial

func (p *Playback3D) Spatial() Spatial3D

Spatial returns the playback's latest computed 3D spatialization (Gain, Pan, and Distance).

func (*Playback3D) Stop

func (p *Playback3D) Stop()

Stop stops the playback immediately. Calling Stop on a nil or already-ended Playback3D is a no-op.

func (*Playback3D) Velocity

func (p *Playback3D) Velocity() Vec3

Velocity returns the playback's current 3D world velocity.

type PlaylistOrder

type PlaylistOrder string

PlaylistOrder selects how a MusicPlaylist walks through a piece's clips.

const (
	// PlaylistLinear plays clips in declaration order, wrapping back to the first clip after the last.
	PlaylistLinear PlaylistOrder = "linear"
	// PlaylistSequential is an alias for PlaylistLinear.
	PlaylistSequential PlaylistOrder = "sequential"
	// PlaylistShuffle plays clips in a deterministic shuffled order seeded by MusicPlaylist.Seed without immediate repeats across cycles.
	PlaylistShuffle PlaylistOrder = "shuffle"
)

type RandSource

type RandSource interface {
	Uint64() uint64
}

RandSource is a source of uniformly distributed pseudo-random uint64 values. Any seeded stream implementing Uint64() uint64 (such as math/rand/v2.Source or a game/random stream) satisfies RandSource without introducing extra imports.

type RectZone

type RectZone struct {
	X, Y, Width, Height float32
}

RectZone is an axis-aligned 2D rectangle [X, X+Width] x [Y, Y+Height]. Contains3D tests X and Y against the rectangle, ignoring Z.

func (RectZone) Contains2D

func (r RectZone) Contains2D(pos math2d.Vec2) bool

Contains2D reports whether pos lies inside r (inclusive of edges). Non-finite values or non-positive dimensions return false.

func (RectZone) Contains3D

func (r RectZone) Contains3D(pos Vec3) bool

Contains3D reports whether pos's X and Y lie inside r.

type Rolloff

type Rolloff uint8

Rolloff is how an effect's volume falls from Near to Far in a Listener2D or Listener3D.

const (
	// RolloffLinear falls in a straight line from full volume at Near to silence at Far.
	RolloffLinear Rolloff = iota
	// RolloffInverse falls as Near divided by the distance, as sound does in the open, rescaled to reach silence at Far: steep close to Near and gentle towards Far. With a Near of 0 it falls as RolloffLinear.
	RolloffInverse
	// RolloffExponential falls as (Near / distance)^factor (inverse-square by default when factor is 2), rescaled to reach silence at Far: steeper than RolloffInverse close to Near. With a Near of 0 it falls as ((Far - distance) / Far)^factor.
	RolloffExponential
)

type SectionedTrack

type SectionedTrack struct {
	Intro audio.Source
	Loop  audio.Source
}

SectionedTrack pairs an intro section played once with a loop section that repeats indefinitely after the intro ends.

Prefer Music.PlayLooped with a single audio file and a loop point when you control the asset: two-file playback coordinates two audio.Players across an engine turn and may still leave a slight seam depending on the backend and load.

type SidechainEffectInstance

type SidechainEffectInstance interface {
	EffectInstance
	// SidechainBus returns the name of the bus whose audio keys this effect, or "" for self-keying.
	SidechainBus() string
	// ProcessSidechain transforms block in place using key as the external detector signal.
	// A nil or shorter key treats missing samples as silence.
	ProcessSidechain(block, key []float32)
}

SidechainEffectInstance is an optional interface an EffectInstance may implement to key its processing from another bus's audio in SoftwareMixer.

type SoftwareMixer

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

SoftwareMixer mixes interleaved float32 voices through named effect chains on the engine goroutine.

func NewSoftwareMixer

func NewSoftwareMixer(opts SoftwareOptions) *SoftwareMixer

NewSoftwareMixer creates a deterministic CPU mixer. Defaults are 48000 Hz stereo.

func (*SoftwareMixer) BusSend

func (m *SoftwareMixer) BusSend(bus, sendBus string) float32

BusSend returns the configured auxiliary send amount in [0, 1] from bus to sendBus, or 0 if unset.

func (*SoftwareMixer) Channels

func (m *SoftwareMixer) Channels() int

Channels returns the number of interleaved channels the mixer writes.

func (*SoftwareMixer) Mix

func (m *SoftwareMixer) Mix(dst, src []float32, bus string)

Mix adds samples into dst after processing src through a bus. Buffers are interleaved float32. Effects implementing SidechainEffectInstance read the most recently mixed block of their sidechain bus, and bus's processed output is recorded for downstream sidechains. It does nothing when dst is shorter than src or src does not hold whole frames.

func (*SoftwareMixer) MixBuses

func (m *SoftwareMixer) MixBuses(dst []float32, inputs map[string][]float32)

MixBuses mixes one audio block across all supplied buses into dst in deterministic topological sidechain order (key buses before keyed buses, ties broken alphabetically). Buses omitted from inputs (or with empty slices) clear their sidechain tap so keyed compressors release smoothly.

func (*SoftwareMixer) MixVoice

func (m *SoftwareMixer) MixVoice(dst, src []float32, bus string, voice *SoftwareVoice)

MixVoice processes src through voice (applying per-playback gain, stereo pan, and distance low-pass) and then mixes the result through bus (and any configured bus sends) into dst without modifying src.

func (*SoftwareMixer) NewVoice

func (m *SoftwareMixer) NewVoice() *SoftwareVoice

NewVoice creates a SoftwareVoice matching m's sample rate and channel count.

func (*SoftwareMixer) ResetSidechain

func (m *SoftwareMixer) ResetSidechain()

ResetSidechain clears all recorded bus taps used as sidechain keys by subsequent Mix calls.

func (*SoftwareMixer) SampleRate

func (m *SoftwareMixer) SampleRate() int

SampleRate returns the sample rate in hertz the mixer's effect instances were created for.

func (*SoftwareMixer) SetBusEffects

func (m *SoftwareMixer) SetBusEffects(bus string, chain EffectChain)

SetBusEffects replaces a bus's effects with one instance per effect of chain that implements StatefulBusEffect (including every built-in effect). Custom effects that only implement offline BusEffect are skipped.

func (*SoftwareMixer) SetBusSend

func (m *SoftwareMixer) SetBusSend(bus, sendBus string, amount float32)

SetBusSend configures an auxiliary post-effect send from bus to sendBus at amount in [0, 1]. Setting amount <= 0 or NaN removes the send; self-sends (bus == sendBus) are ignored to prevent feedback loops.

type SoftwareOptions

type SoftwareOptions struct {
	SampleRate int
	Channels   int
}

SoftwareOptions configures an in-memory software mixer renderer.

type SoftwareVoice

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

SoftwareVoice applies per-playback gain, equal-power stereo panning, and a live stateful distance low-pass filter to interleaved float32 PCM blocks with zero per-block heap allocations.

func NewSoftwareVoice

func NewSoftwareVoice(sampleRate, channels int) *SoftwareVoice

NewSoftwareVoice creates a stateful per-playback voice processor for sampleRate and channels.

func (*SoftwareVoice) CutoffHz

func (v *SoftwareVoice) CutoffHz() float32

CutoffHz returns the voice's current low-pass cutoff frequency in hertz (0 when bypassed).

func (*SoftwareVoice) Gain

func (v *SoftwareVoice) Gain() float32

Gain returns the voice's current gain multiplier.

func (*SoftwareVoice) Pan

func (v *SoftwareVoice) Pan() float32

Pan returns the voice's current stereo pan in [-1, 1].

func (*SoftwareVoice) Process

func (v *SoftwareVoice) Process(block []float32)

Process applies the voice's gain, stereo pan (for 2-channel blocks), and low-pass filter in place.

func (*SoftwareVoice) Reset

func (v *SoftwareVoice) Reset()

Reset clears the voice's internal filter memory.

func (*SoftwareVoice) SetCutoffHz

func (v *SoftwareVoice) SetCutoffHz(hz float32)

SetCutoffHz updates the voice's live low-pass filter cutoff frequency in hertz without resetting filter delay state, so distance low-pass filtering sweeps smoothly as a source moves. Setting hz <= 0, non-finite, or >= Nyquist bypasses the filter cleanly.

func (*SoftwareVoice) SetGain

func (v *SoftwareVoice) SetGain(gain float32)

SetGain sets the voice's linear gain multiplier (>= 0; NaN or negative clamps to 0).

func (*SoftwareVoice) SetPan

func (v *SoftwareVoice) SetPan(pan float32)

SetPan sets the voice's stereo pan in [-1, 1] (-1 full left, 0 center, +1 full right).

type Spatial2DOptions

type Spatial2DOptions struct {
	// Near overrides Listener2D.Near when > 0 and finite.
	Near float32
	// Far overrides Listener2D.Far when > 0 and finite.
	Far float32
	// HasRolloff selects Rolloff over Listener2D.Rolloff when true.
	HasRolloff bool
	// Rolloff overrides Listener2D.Rolloff when HasRolloff is true.
	Rolloff Rolloff
	// Velocity is the source's initial 2D velocity in world units per second (used when Doppler is true).
	Velocity math2d.Vec2
	// Doppler enables live Doppler pitch shifting based on relative velocity between source and listener.
	Doppler bool
	// DopplerScale overrides Listener2D.DopplerScale when > 0 and finite.
	DopplerScale float32
	// FarCutoffHz is the distance low-pass cutoff frequency in hertz reached at Far; <= 0 disables distance filtering.
	FarCutoffHz float32
}

Spatial2DOptions customizes 2D spatialization for a single live Playback2D, such as per-source distance attenuation overrides, Doppler tracking, and a distance low-pass cutoff.

type Spatial3D

type Spatial3D struct {
	// Gain is the combined spatial attenuation in [0, 1] (distance * rear * source cone).
	Gain float32
	// Pan is the stereo pan in [-1, 1] (-1 full left, 0 centered, +1 full right).
	Pan float32
	// Front is the forward projection dot(dir, forward) in [-1, 1] (+1 directly ahead, -1 directly behind,
	// 0 at the listener or directly sideways/above/below).
	Front float32
	// Distance is the Euclidean distance from the listener to the source in world units (0 when NaN).
	Distance float32
}

Spatial3D holds the computed 3D spatialization for a source relative to a Listener3D.

func Spatialize3D

func Spatialize3D(l Listener3D, pos Vec3, opts Spatial3DOptions) Spatial3D

Spatialize3D computes 3D spatialization for a source at pos relative to l with opts.

type Spatial3DOptions

type Spatial3DOptions struct {
	// Near overrides Listener3D.Near when > 0 and finite.
	Near float32
	// Far overrides Listener3D.Far when > 0 and finite.
	Far float32
	// HasRolloff selects Rolloff over Listener3D.Rolloff when true.
	HasRolloff bool
	// Rolloff overrides Listener3D.Rolloff when HasRolloff is true.
	Rolloff Rolloff
	// RolloffFactor overrides Listener3D.RolloffFactor when > 0 and finite.
	RolloffFactor float32

	// SourceForward is the direction a directional sound source emits toward.
	// When zero or non-finite, or when OuterConeAngle <= 0, the source is omnidirectional.
	SourceForward Vec3
	// InnerConeAngle is the full cone angle in radians (in [0, 2*Pi]) within which the directional
	// source plays at full cone gain (1). Clamped to [0, OuterConeAngle].
	InnerConeAngle float32
	// OuterConeAngle is the full cone angle in radians (in [0, 2*Pi]) beyond which the directional
	// source plays at OuterGain. Between InnerConeAngle and OuterConeAngle, cone gain interpolates
	// linearly from 1 to OuterGain. When <= 0 or NaN, directional cone attenuation is disabled.
	OuterConeAngle float32
	// OuterGain is the cone gain multiplier outside OuterConeAngle, clamped to [0, 1].
	OuterGain float32

	// Velocity is the source's initial 3D velocity in world units per second (used when Doppler is true).
	Velocity Vec3
	// Doppler enables live Doppler pitch shifting based on relative velocity between source and listener.
	Doppler bool
	// DopplerScale overrides Listener3D.DopplerScale when > 0 and finite.
	DopplerScale float32
	// FarCutoffHz is the distance low-pass cutoff frequency in hertz reached at Far; <= 0 disables distance filtering.
	FarCutoffHz float32
}

Spatial3DOptions customizes 3D spatialization for a single sound source, such as per-source distance attenuation overrides or a directional emission cone. Its zero value represents an omnidirectional point source using the listener's attenuation settings.

type SphereZone

type SphereZone struct {
	Center Vec3
	Radius float32
}

SphereZone is a 3D spherical zone centered at Center with Radius.

func (SphereZone) Contains2D

func (s SphereZone) Contains2D(pos math2d.Vec2) bool

Contains2D reports whether pos lies within s's horizontal projection in X and Y.

func (SphereZone) Contains3D

func (s SphereZone) Contains3D(pos Vec3) bool

Contains3D reports whether pos lies within s.Radius of s.Center (inclusive).

type StatefulBusEffect

type StatefulBusEffect interface {
	BusEffect
	Instance(sampleRate, channels int) EffectInstance
}

StatefulBusEffect optionally creates a stateful stream processor for a sample rate and channel count.

type TransitionAt

type TransitionAt string

TransitionAt selects when an adaptive music transition takes effect.

const (
	// TransitionImmediate switches right away without waiting for a beat or bar.
	TransitionImmediate TransitionAt = "immediate"
	// TransitionBeat switches on the next beat boundary.
	TransitionBeat TransitionAt = "beat"
	// TransitionBar switches on the next bar downbeat.
	TransitionBar TransitionAt = "bar"
	// TransitionClipEnd switches when the current clip reaches its end.
	TransitionClipEnd TransitionAt = "clipEnd"
)

type Vec3

type Vec3 struct {
	X, Y, Z float32
}

Vec3 is a 3D point or direction in right-handed Y-up space (+X right, +Y up, -Z forward), matching math3d.Vec3 and scene3d.Camera so callers can convert directly with sound.Vec3(v).

func V3

func V3(x, y, z float32) Vec3

V3 returns a Vec3 with the given coordinates.

type Zone

type Zone struct {
	// Name optionally identifies the zone for debugging.
	Name string
	// Shape tests whether the listener position is inside the zone.
	Shape ZoneShape
	// Bus is the mixer bus (group) activated while the listener is inside the zone.
	Bus string
	// ReverbSend is the target auxiliary reverb send level in [0, 1] while inside the zone.
	ReverbSend float32
	// SendBus names the auxiliary send bus on a SoftwareMixer; empty defaults to DefaultReverbSendBus ("reverb").
	SendBus string
	// Fade is the crossfade duration when entering or leaving the zone; <= 0 switches immediately.
	Fade time.Duration
	// Priority resolves overlapping zones: higher Priority wins, ties broken by registration order.
	Priority int
}

Zone defines a 2D or 3D spatial region that activates Bus and/or drives an auxiliary reverb send while the listener is inside Shape.

type ZoneRouter

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

ZoneRouter evaluates a list of spatial Zones against the listener's 2D or 3D position and smoothly crossfades bus gains and auxiliary reverb send levels over each zone's Fade duration.

Stepping is deterministic on fixed dt and safe against NaN positions or non-positive durations.

func NewZoneRouter

func NewZoneRouter(defaultBus string, zones ...Zone) *ZoneRouter

NewZoneRouter creates a ZoneRouter with defaultBus active outside all zones and the given zones.

func (*ZoneRouter) ActiveBus

func (r *ZoneRouter) ActiveBus() string

ActiveBus returns the target bus for the listener's current zone, or DefaultBus when outside all zones.

func (*ZoneRouter) ActiveZone

func (r *ZoneRouter) ActiveZone() (Zone, bool)

ActiveZone returns the highest-priority zone currently containing the listener, if any.

func (*ZoneRouter) AddZone

func (r *ZoneRouter) AddZone(z Zone)

AddZone appends z to the router.

func (*ZoneRouter) ApplyMixer

func (r *ZoneRouter) ApplyMixer(m *Mixer)

ApplyMixer writes every tracked zone bus's current crossfade weight to m as a transient zone gain multiplier (without modifying persisted core.Storage volumes).

func (*ZoneRouter) ApplySoftware

func (r *ZoneRouter) ApplySoftware(sw *SoftwareMixer, sourceBuses ...string)

ApplySoftware writes every tracked zone's current auxiliary reverb send levels onto sw for each bus in sourceBuses. When sourceBuses is empty, applies sends to DefaultBus and every zone's Bus.

func (*ZoneRouter) BusWeight

func (r *ZoneRouter) BusWeight(bus string) float32

BusWeight returns the current smoothed crossfade weight in [0, 1] for bus.

func (*ZoneRouter) DefaultBus

func (r *ZoneRouter) DefaultBus() string

DefaultBus returns the bus active when the listener is outside every zone.

func (*ZoneRouter) SendAmount

func (r *ZoneRouter) SendAmount(sendBus string) float32

SendAmount returns the current smoothed auxiliary send amount in [0, 1] for sendBus (empty string queries DefaultReverbSendBus, "reverb").

func (*ZoneRouter) SetDefaultBus

func (r *ZoneRouter) SetDefaultBus(bus string)

SetDefaultBus changes the bus active outside every zone.

func (*ZoneRouter) SetZones

func (r *ZoneRouter) SetZones(zones ...Zone)

SetZones replaces all configured zones and initializes bus/send maps while preserving current weights for matching buses.

func (*ZoneRouter) Step2D

func (r *ZoneRouter) Step2D(pos math2d.Vec2, dt time.Duration)

Step2D checks all zones against the 2D listener position pos and advances bus and reverb-send crossfades by dt.

func (*ZoneRouter) Step3D

func (r *ZoneRouter) Step3D(pos Vec3, dt time.Duration)

Step3D checks all zones against the 3D listener position pos and advances bus and reverb-send crossfades by dt.

func (*ZoneRouter) Zones

func (r *ZoneRouter) Zones() []Zone

Zones returns a copy of the router's configured zones.

type ZoneShape

type ZoneShape interface {
	Contains2D(pos math2d.Vec2) bool
	Contains3D(pos Vec3) bool
}

ZoneShape tests whether a 2D or 3D listener position lies inside a sound Zone.

Jump to

Keyboard shortcuts

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