Справочник API собран из Go doc-комментариев в исходном коде и написан на английском языке.
package sound
import "github.com/nsgo-dev/game/pkg/sound"Указатель
- Константы
- func DecodeWAV(wav []byte) (samples []float64, sampleRate, channels int, err error)
- func EncodeWAV(samples []float64, sampleRate, channels int) ([]byte, error)
- func ProcessSamples(samples []float64, sampleRate, channels int, chain ...BusEffect)
- func ProcessWAV(wav []byte, chain ...BusEffect) ([]byte, error)
- type BusEffect
- type Clip
- type Cue
- func NewCue(seed uint64, opts CueOptions) *Cue
- func (c *Cue) LastIndex() int
- func (c *Cue) Len() int
- func (c *Cue) NoRepeatWindow() int
- func (c *Cue) Pick() CuePick
- func (c *Cue) PitchRange() (min, max float64)
- func (c *Cue) Play() (CuePick, bool)
- func (c *Cue) Play3D(pos Vec3, opts Spatial3DOptions) (CuePick, *Playback3D)
- func (c *Cue) PlayAt(l Listener2D, pos math2d.Vec2) (CuePick, bool)
- func (c *Cue) PlayAt3D(l Listener3D, pos Vec3) (CuePick, bool)
- func (c *Cue) PlayPCM() (CuePick, PCM)
- func (c *Cue) Reset(seed uint64)
- func (c *Cue) SetSource(src RandSource)
- func (c *Cue) Stop()
- func (c *Cue) VolumeRange() (min, max float64)
- type CueOptions
- type CuePick
- type Effect
- type EffectChain
- type Listener2D
- type Listener3D
- func (l Listener3D) Gain(pos Vec3) float32
- func (l *Listener3D) LookAt(target, up Vec3)
- func (l Listener3D) Pan(pos Vec3) float32
- func (l *Listener3D) SetPose(pos, forward, up Vec3)
- func (l Listener3D) Spatialize(pos Vec3, opts Spatial3DOptions) Spatial3D
- func (l Listener3D) Voice(pos Vec3, v audio.Voice) audio.Voice
- func (l Listener3D) VoiceWithOptions(pos Vec3, v audio.Voice, opts Spatial3DOptions) audio.Voice
- type Mixer
- func NewMixer(cx *core.Scope, key string) *Mixer
- func (m *Mixer) Cue(group string, limit int, seed uint64, opts CueOptions, sounds ...*audio.Sound) *Cue
- func (m *Mixer) Effect(s *audio.Sound, group string, limit int) *Effect
- func (m *Mixer) GroupEffects(group string) EffectChain
- func (m *Mixer) Listener3D() Listener3D
- func (m *Mixer) Master() float32
- func (m *Mixer) Music(group string) *Music
- func (m *Mixer) PauseExempt(group string) bool
- func (m *Mixer) Paused() bool
- func (m *Mixer) PlayCue(cue *Cue) (CuePick, bool)
- func (m *Mixer) ProcessSource(group string, src audio.Source) (audio.Source, error)
- func (m *Mixer) RenderCuePCM(group string, cue *Cue) (CuePick, PCM)
- func (m *Mixer) SetDefaultMaster(v float32)
- func (m *Mixer) SetDefaultVolume(group string, v float32)
- func (m *Mixer) SetGroupEffects(group string, effects ...BusEffect)
- func (m *Mixer) SetListener3D(l Listener3D)
- func (m *Mixer) SetMaster(v float32) error
- func (m *Mixer) SetPauseExempt(group string, exempt bool)
- func (m *Mixer) SetPaused(paused bool)
- func (m *Mixer) SetVolume(group string, v float32) error
- func (m *Mixer) Suspend() (resume func())
- func (m *Mixer) Suspended() bool
- func (m *Mixer) Volume(group string) float32
- type Music
- type PCM
- type Playback3D
- func (p *Playback3D) Ended() bool
- func (p *Playback3D) Gain() float32
- func (p *Playback3D) Options() Spatial3DOptions
- func (p *Playback3D) Pan() float32
- func (p *Playback3D) Playing() bool
- func (p *Playback3D) Position() Vec3
- func (p *Playback3D) SetOptions(opts Spatial3DOptions)
- func (p *Playback3D) SetPosition(pos Vec3)
- func (p *Playback3D) SetRate(rate float32)
- func (p *Playback3D) Spatial() Spatial3D
- func (p *Playback3D) Stop()
- type RandSource
- type Rolloff
- type SectionedTrack
- type Spatial3D
- type Spatial3DOptions
- type Vec3
Константы
const DefaultRearGain float32 = 0.7DefaultRearGain 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.
Функции
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(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(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].
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.
Типы
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(bits int, downsample int) BusEffectBitcrush 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(delay time.Duration, feedback, wet float64) BusEffectDelay 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(factor float64) BusEffectGain returns an effect that scales every sample by factor.
func HighPass(cutoffHz, q float64) BusEffectHighPass 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(cutoffHz, q float64) BusEffectLowPass 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(roomSize, damping, wet float64) BusEffectReverb returns a Schroeder/Freeverb-style comb and allpass reverb with roomSize, damping, and wet clamped to [0, 1].
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.
type Cue struct {
// contains filtered or unexported fields
}Cue selects and plays sound variants with deterministic pitch and volume variation and configurable repeat avoidance.
func NewCue(seed uint64, opts CueOptions) *CueNewCue creates a Cue seeded with seed and configured by opts.
func (c *Cue) LastIndex() intLastIndex returns the index of the most recent pick, or -1 if Pick has not been called since creation or Reset.
func (c *Cue) NoRepeatWindow() intNoRepeatWindow returns the effective repeat-avoidance window size (0 when disabled).
func (c *Cue) Pick() CuePickPick 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 (c *Cue) PitchRange() (min, max float64)PitchRange returns the normalized inclusive [min, max] pitch range.
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 (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 (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 (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 (c *Cue) PlayPCM() (CuePick, PCM)PlayPCM selects the next variant via Pick and returns its resampled and gain-scaled PCM buffer.
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 (c *Cue) SetSource(src RandSource)SetSource replaces the cue's random source. Passing nil restores the internal seeded stream.
func (c *Cue) VolumeRange() (min, max float64)VolumeRange returns the normalized inclusive [min, max] volume range.
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 struct {
Index int
Clip Clip
Pitch float64
Volume float64
}CuePick is the outcome of a single Cue.Pick call.
func (p CuePick) RenderPCM() PCMRenderPCM resamples p.Clip.PCM by p.Pitch and scales it by p.Volume.
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.
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 (s *Effect) Play(v audio.Voice) boolPlay 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. 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 (s *Effect) Play3D(pos Vec3, v audio.Voice, opts Spatial3DOptions) *Playback3DPlay3D 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 (s *Effect) PlayAt(l Listener2D, pos math2d.Vec2, v audio.Voice) boolPlayAt plays the effect at pos in the world as l hears it: panned by l.Pan 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 (s *Effect) PlayAt3D(l Listener3D, pos Vec3, v audio.Voice) boolPlayAt3D plays the effect at pos in the 3D world as l hears it: panned by l.Pan 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 (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 []BusEffectEffectChain applies a sequence of bus effects in order and itself satisfies BusEffect.
func (c EffectChain) ProcessSamples(samples []float64, sampleRate, channels int)ProcessSamples runs every non-nil effect in c in order on interleaved samples.
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 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 (l Listener2D) Gain(pos math2d.Vec2) float32Gain 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 (l Listener2D) Pan(pos math2d.Vec2) float32Pan 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 (l Listener2D) Voice(pos math2d.Vec2, v audio.Voice) audio.VoiceVoice 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 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.
func (l Listener3D) Gain(pos Vec3) float32Gain 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 (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 (l Listener3D) Pan(pos Vec3) float32Pan 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 (l *Listener3D) SetPose(pos, forward, up Vec3)SetPose updates l's Position, Forward, and Up without changing its attenuation or pan settings.
func (l Listener3D) Spatialize(pos Vec3, opts Spatial3DOptions) Spatial3DSpatialize computes distance attenuation, rear head-shadow attenuation, optional directional source cone attenuation, and stereo pan for a source at pos relative to l.
func (l Listener3D) Voice(pos Vec3, v audio.Voice) audio.VoiceVoice 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 (l Listener3D) VoiceWithOptions(pos Vec3, v audio.Voice, opts Spatial3DOptions) audio.VoiceVoiceWithOptions 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 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.
func NewMixer(cx *core.Scope, key string) *MixerNewMixer 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.
func (m *Mixer) Cue(group string, limit int, seed uint64, opts CueOptions, sounds ...*audio.Sound) *CueCue 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 (m *Mixer) Effect(s *audio.Sound, group string, limit int) *EffectEffect 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.
func (m *Mixer) GroupEffects(group string) EffectChainGroupEffects returns a copy of the DSP bus effect chain configured for group, or nil when none is set.
func (m *Mixer) Listener3D() Listener3DListener3D returns the mixer's active 3D listener.
func (m *Mixer) Master() float32Master 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 (m *Mixer) Music(group string) *MusicMusic returns music played through the mixer in group, which plays nothing until Play.
func (m *Mixer) PauseExempt(group string) boolPauseExempt reports whether group keeps playing while the mixer is paused with SetPaused.
func (m *Mixer) Paused() boolPaused reports whether gameplay audio is paused by SetPaused.
func (m *Mixer) PlayCue(cue *Cue) (CuePick, bool)PlayCue plays the next variant of cue through its Mixer Effect.
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 (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 (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 (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 (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 (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 (m *Mixer) SetMaster(v float32) errorSetMaster 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 (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 (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 (m *Mixer) SetVolume(group string, v float32) errorSetVolume 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 (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 (m *Mixer) Suspended() boolSuspended reports whether a Suspend has not been resumed yet.
func (m *Mixer) Volume(group string) float32Volume 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 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.
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, such as one the platform cannot decode, plays nothing.
func (mu *Music) PlaySections(intro, loop audio.Source, fade time.Duration)PlaySections plays intro once without looping, pre-arms loop with looping enabled, and hands off to loop as soon as intro ends, fading in over fade as any previous music fades out. 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.
func (mu *Music) PlayWithIntro(track SectionedTrack, fade time.Duration)PlayWithIntro plays track's intro once and hands off immediately to its looping section, fading in over fade as any previous music fades out.
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 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(pcm PCM, volume float64) PCMApplyGain 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(wav []byte) (PCM, error)DecodePCM decodes a 16-bit signed linear PCM RIFF/WAVE buffer into a PCM buffer.
func ResamplePitch(pcm PCM, pitch float64) PCMResamplePitch 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 (p PCM) EncodeWAV() ([]byte, error)EncodeWAV encodes p as a canonical 16-bit signed linear PCM RIFF/WAVE buffer.
func (p PCM) Frames() intFrames returns the number of complete multi-channel frames in p.
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 (p *Playback3D) Ended() boolEnded reports whether the playback has finished, was stopped, or never started.
func (p *Playback3D) Gain() float32Gain returns the playback's latest computed spatial gain in [0, 1].
func (p *Playback3D) Options() Spatial3DOptionsOptions returns the playback's current per-source 3D spatialization options.
func (p *Playback3D) Pan() float32Pan returns the playback's latest computed stereo pan in [-1, 1].
func (p *Playback3D) Playing() boolPlaying reports whether the playback is currently active.
func (p *Playback3D) Position() Vec3Position returns the playback's current 3D world position.
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 (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 (p *Playback3D) SetRate(rate float32)SetRate updates the playback's playback rate on the underlying audio.Playback when still playing.
func (p *Playback3D) Spatial() Spatial3DSpatial returns the playback's latest computed 3D spatialization (Gain, Pan, and Distance).
func (p *Playback3D) Stop()Stop stops the playback immediately. Calling Stop on a nil or already-ended Playback3D is a no-op.
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 uint8Rolloff 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 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.
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(l Listener3D, pos Vec3, opts Spatial3DOptions) Spatial3DSpatialize3D computes 3D spatialization for a source at pos relative to l with opts.
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 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).