sound

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2026 License: Apache-2.0 Imports: 12 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

Index

Examples

Constants

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.

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

Types

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

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 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) 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, and voice limit.

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) 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) 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) 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) 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
}

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 Effect

type Effect struct {
	// Group is the group 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 none but the platform's 32 for all sounds.
	Limit int
	// contains filtered or unexported fields
}

Effect is a short sound played through a mixer, in a group and with a limit of its own.

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, or while the app is in the background, suspended, or the effect's group is paused, 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) 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), returning an ended Playback3D so silent sources never take voice slots or count against s.Limit.

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. The pan and volume hold for the playback's whole length, as audio's playbacks cannot change their pan once started.

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) 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 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
	// 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
}

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
	// 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
}

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) Balance

func (m *Mixer) Balance() float32

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

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) 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) 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) 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) 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) 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) 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 immediately (respecting master/group volumes, pause, suspend, and background muting).

Because NSGo's audio.Playback cannot change stereo pan after a playback starts, Pan() on a live Playback3D reflects the latest computed pan while the backend's active pan stays at its initial value; live distance, rear, and source-cone attenuation update continuously via SetVolume.

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

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
	// 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 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 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 its directional cone via SetOptions, or moving the listener via Mixer.SetListener3D recomputes its spatialization and updates its underlying audio.Playback volume live while honoring the mixer's group volume, master volume, pause, suspend, and background states.

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

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) SetOptions

func (p *Playback3D) SetOptions(opts Spatial3DOptions)

SetOptions updates the playback's per-source 3D spatialization options (such as a rotating directional cone), recomputes spatialization, and updates the underlying audio.Playback volume.

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 playback rate on the underlying audio.Playback when still playing.

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.

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 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 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
	// 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
}

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

Jump to

Keyboard shortcuts

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