Эта страница ещё не переведена на русский язык, поэтому ниже показан английский оригинал.
Ядро 2Dsound
game/sound layers a persistent volume Mixer, voice-limited sound Effects, crossfading Music, and automatic background muting on top of NSGo's audio package.
import (
"github.com/nsgo-dev/game/pkg/sound"
"github.com/nsgo-dev/nsgo/audio"
)
All Mixer, Effect and Music methods run on the engine's goroutine, just like audio's methods. From any other goroutine, dispatch through cx.Post. Ship audio files under resources/ as WAV, AAC (.m4a) or MP3.
Mixer and persistent volumes
A Mixer holds one master volume and a volume for every group name your game uses (for example "effects", "music" and "ui"). Every volume is in [0, 1] and defaults to 1.
mixer := sound.NewMixer(cx, "sound")
NewMixer(cx, key) stores values in cx.Storage() (core.Storage) under:
<key>.master<key>.group.<group>
Volumes persist automatically across app launches. Passing values outside [0, 1] clamps them (and NaN resets to 1). If storage is full, SetMaster and SetVolume return *core.StorageFullError and keep the previous volume.
SetDefaultMaster and SetDefaultVolume(group, v) set the volume a mixer has until the player sets one, such as a bus volume from the project file. They keep nothing in storage, so a volume the player set wins; set them before the game reads volumes.
Reactive settings UI
Master() and Volume(group) read from core.Storage, so calling them inside a reactive view function subscribes that view to volume changes automatically:
core.Text{
ContentFunc: func() string {
return fmt.Sprintf("Music: %.0f%%", mixer.Volume("music")*100)
},
}
How volume changes take effect
- Effects: each playback uses
voice.Volume * mixer.Volume(group) * mixer.Master(). Volume changes apply at once to effects already playing, through each playback'saudio.Playback, and to those started afterwards. A playback whose group or master volume reaches0plays on in silence and is heard again when the volume comes back. - Music: active tracks update live at
mixer.Volume(group) * mixer.Master(), pausing when the effective gain reaches0and resuming from the same position when raised above0.
Effect and voice limits
Short sounds (under 8 MiB encoded and 5 seconds decoded) are decoded into memory once with audio.LoadSound, then wrapped in a mixer Effect:
var hit *sound.Effect
audio.LoadSound(cx, audio.Source{URI: "asset:sounds/hit.wav"}, func(s *audio.Sound, err error) {
if err != nil {
return
}
hit = mixer.Effect(s, "effects", 4)
})
The third argument (limit) caps how many overlapping playbacks of that sound may run at once (0 means no per-effect cap, still bounded by the platform's 32 concurrent sound voices). This prevents rapid bursts — such as coins or footsteps — from starving every other sound.
Play(v audio.Voice) boolstarts a playback and reports whether it asked for one. It returnsfalsewhen effective gain is0(including a voice withMutedset) or the app is in the background, andtrueotherwise, even where the playback ends at once because the backend could not start it. WhenLimitplaybacks are still playing, it stops the oldest of them to make room, so the newest are heard; playbacks that end on their own free their place without stopping another, and one that never started leaves them playing. A backend that cannot address playbacks plays the voice as it started, outside the limit and later volume changes; every NSGo backend with audio can.Stop()stops every playback of that sound (and any other*audio.Soundsharing the same source).- Close the underlying
*audio.Soundwhen you no longer need it, or letcx's scope disposal free it.
if hit != nil {
hit.Play(audio.Voice{Volume: 0.9, Rate: 1.05})
}
Concurrency groups, priority, retrigger time, and ducking
Beyond a single Effect.Limit, Mixer supports named concurrency groups shared across multiple Effects and Cues, a global voice budget with cross-group priority stealing, minimum retrigger intervals, steal fade-outs, older-voice group ducking, and bus ducking:
mixer.SetMaxVoices(28) // default: sound.DefaultMaxVoices (30, below the platform's 32)
mixer.SetConcurrencyGroup("impacts", sound.ConcurrencyGroup{
Max: 4,
Resolve: sound.ResolveQuietest, // ResolveRefuse (default), ResolveOldest, ResolveFarthest, ResolveQuietest, ResolveLowestPriority
Scope: sound.ScopeGlobal, // ScopeGlobal (default) or ScopeOwner
Retrigger: 40 * time.Millisecond,
StealFade: 30 * time.Millisecond,
Duck: sound.DuckEnvelope{Amount: 0.25, Attack: 20 * time.Millisecond, Release: 150 * time.Millisecond},
})
mixer.SetBusDucking(sound.BusDuckRule{
Bus: "music",
By: "dialogue",
Amount: 0.4, // lowers music by 40% (to 0.6x) while dialogue plays
Attack: 100 * time.Millisecond,
Release: 500 * time.Millisecond,
})
hit.Concurrency = "impacts"
hit.Priority = 10
hit.PlayWith(audio.Voice{Volume: 0.9}, sound.PlayOptions{Owner: enemyID})
- Shared concurrency groups: set
Effect.Concurrency(orCueOptions.Concurrency/PlayOptions.Concurrency) to assign many different sounds to one registered group. WhenMaxactive voices are already playing in the group,Resolvedecides what happens:ResolveRefusedrops the new sound,ResolveOldeststops the oldest active voice,ResolveFartheststops the farthest positional voice (or refuses if the new sound is farther),ResolveQuieteststops the quietest audible voice (or refuses if the new sound is quieter), andResolveLowestPrioritystops the lowest-priority voice (breaking ties by oldest, or refusing if the new sound has strictly lower priority). - Owner scope: with
Scope: sound.ScopeOwner,Max,Retrigger, andDuckapply independently perPlayOptions.Owner(any comparable value such as an entity ID, string, or pointer) throughEffect.PlayWith,PlayAtWith,PlayAt3DWith,Play3DWith, and the matchingCuemethods. - Retrigger time:
Retriggerrejects new starts in the group (or owner) arriving sooner than the cooldown after the last accepted start, without stopping voices already playing. - Steal fade-out: when
StealFade > 0, voices stolen by a concurrency group are removed from active voice counts immediately and smoothly ramped to silence overStealFadebefore stopping. - Group ducking:
ConcurrencyGroup.Ducklowers older active voices in the same concurrency scope as newer voices start (scaling each older voice by(1 - Amount)^newer), ramping in overAttackand recovering overReleaseautomatically as newer voices finish. - Bus ducking:
SetBusDucking/AddBusDuckinglowersBusbyAmount(in[0, 1], where0.4yields0.6xgain and1silences while keepingMusicplayheads advancing) whenever anyEffectorMusicplays on busBy(or in concurrency groupBy), with smoothAttackandReleaseenvelopes. Multiple rules targeting the same bus stack multiplicatively. - Global voice budget and priority:
Mixercaps total active voices atMaxVoices()(DefaultMaxVoices,30, by default) and steals the lowest-priority active voice across all groups (ties broken by oldest), refusing strictly lower-priority sounds so bursts of minor effects never cut important dialogue or player cues. - Project configuration and validation: declare
audio.maxVoices,audio.concurrency, andaudio.duckingame.yamland install them withFile.ConfigureMixer(mixer).go tool game checkvalidatesconcurrency:names referenced by*.sound.yamlfiles againstgame.yaml. - Debug readout: call
mixer.DebugSnapshot()— or passSound: mixertogamedebug.Optionsandmcp.Config(game_sound_readout) — to inspect active and fading voice counts, global budget, per-group counts and counters (refused,stolen,retriggered), and live bus duck gains.
Bus effect chains
mixer.SetGroupEffects(group, ...) gives a group a DSP chain of bus effects, run in order, and mixer.GroupEffects(group) reads it back. The list is sound.LowPass, sound.HighPass, sound.BandPass, sound.Notch, sound.PeakingEQ, sound.EQ, sound.LowShelf, sound.HighShelf, sound.Delay, sound.Reverb, sound.Chorus, sound.Phaser, sound.Distortion, sound.PitchShift, sound.Panner, sound.StereoWidth, sound.Compressor, sound.Limiter, sound.Gain and sound.Bitcrush.
A project's game.yaml audio.buses effects install the same chains through project.File.ConfigureMixer.
The families split by what they do to a bus:
- Filters are 2nd-order RBJ biquads:
LowPassandHighPasskeep one side,BandPassandNotchwork around one frequency,PeakingEQ,LowShelfandHighShelfchange a band by dB, andEQapplies a list of peaking bands in order, so one entry shapes several frequencies.Qdefaults to Butterworth when it is not positive. - Dynamics are
Compressor(threshold, ratio, attack and release) andLimiter(a ceiling no sample passes). - Modulation and drive:
Chorusreads a wet copy from a delay sweeping around 20ms bydepthMsatrateHz,Phasersweeps four all-pass stages between 400 Hz and 1600 Hz with feedback and a dry/wet mix,Distortiondrives a sample by dB and shapes it withDistortionClip,DistortionTanhorDistortionFold, andPitchShiftretunes by semitones with overlapping 40ms Hann grains, so the duration and the timing of the buffer stay the same. - Placement:
Pannermoves a stereo signal between the channels with an equal-power law (pan-1 to 1, and a mono stream is unchanged), andStereoWidthnarrows a stereo signal to mono at 0 and widens it at 2.
Every effect follows the same contract as the originals: ProcessSamples works in place on interleaved samples, keeps its state inside the call, and returns samples unchanged for a parameter it cannot use, such as a NaN rate.
The chain applies where a source is still in memory before it reaches the player:
Music.Play(src, fade)(andPlayLooped,PlaySections,PlayWithIntro) runs src through the music's group chain when src holds in-memory 16-bit PCM WAV data, and plays the result.mixer.LoadEffect(src, group, limit, done)loads src through its group chain the same way, then wraps it asmixer.Effectdoes.mixer.ProcessSource(group, src)exposes the same processing on its own; the editor's bus audition uses it.
Any other source — a URI, or in-memory MP3, AAC, Ogg or non-PCM WAV data — cannot be processed this way and plays without the chain, with one log line per group saying its effects were skipped for it. mixer.Effect(s, group, limit) on an already decoded *audio.Sound plays without the chain too: it applies at load time, so load through LoadEffect to hear it. Processing whole buffers as they load is the interim pipeline; live effects on every playing voice, covering every format, are a planned follow-up.
Positional effects in 2D
A Listener2D hears effects placed in the world from where the 2D camera looks: an effect to the left of the camera plays panned left, one to the right panned right, and both play quieter the further they are.
listener := sound.Listener2D{
Position: math2d.V2(cam.X, cam.Y),
Rotation: cam.Rotation,
Near: 64, // full volume up to 64 world units away
Far: 640, // silent from 640 away
Rolloff: sound.RolloffInverse,
}
hit.PlayAt(listener, math2d.V2(enemy.X, enemy.Y), audio.Voice{Volume: 0.9})
PositionandRotationfollow the camera, such astilemap.Camera'sX,YandRotation, so left and right are the view's even when the camera turns. Distances are in world units; the camera's zoom does not change them.Gain(pos)is1withinNear,0atFarand beyond, and falls between them byRolloff:RolloffLinear(the default) in a straight line,RolloffInverseasNear / distancerescaled to reach0atFar, andRolloffExponentialas(Near / distance)^2rescaled to reach0atFar. AFarthat is not greater thanNear, infinite orNaNturns attenuation off.Pan(pos)is the effect's offset across the view divided byPanWidth, clamped to[-1, 1]; aPanWidthof0takesFar. An effect straight above or below the camera plays centered.PlayAt(l, pos, v)plays withv.Volume * l.Gain(pos), then the group and master volumes asPlaydoes, andv.Panreplaced byl.Pan(pos). It returnsfalseand plays nothing beyondFar, so silent effects never take a voice or count againstLimit.Cue.PlayAt(l, pos)picks the cue's next variant asPlaydoes and plays it through its effect'sPlayAt, at the variant's volume and pitch, so randomized footsteps and hits can be placed too.Voice(pos, v)returns the voicePlayAtwould play with, for playing anaudio.Sounddirectly. Where the effect is silent it setsMuted, sinceaudioplays a volume of0at full volume.- The camera's rotation only turns the pan; distance ignores it, and an infinite or
NaNRotationcounts as0.
The pan and volume are fixed when the playback starts, because NSGo's audio.Playback cannot change its pan once playing. Suit it to short effects; a long sound that follows a moving source would need to be replayed.
Positional effects in 3D
Listener3D hears effects placed in a right-handed Y-up 3D world (+X right, +Y up, -Z forward — matching math3d and scene3d.Camera). Because sound.Vec3 shares the exact field layout of math3d.Vec3, convert camera vectors directly with sound.Vec3(...):
listener := sound.Listener3D{
Position: sound.Vec3(cam.Pos),
Forward: sound.Vec3(cam.Forward()),
Up: sound.Vec3(cam.Up()),
Near: 2,
Far: 40,
Rolloff: sound.RolloffInverse,
}
mixer.SetListener3D(listener)
// Fire-and-forget 3D effect (mirrors Effect.PlayAt):
hit.PlayAt3D(listener, sound.Vec3(enemyPos), audio.Voice{Volume: 0.9})
// Live 3D playback that tracks camera and source motion:
engine := loopSFX.Play3D(sound.Vec3(shipPos), audio.Voice{Loop: true}, sound.Spatial3DOptions{})
engine.SetPosition(sound.Vec3(nextShipPos))
- Distance attenuation:
Gain(pos)is1withinNear,0atFarand beyond, and falls between them byRolloff(RolloffLinear,RolloffInverse, orRolloffExponential, shaped by optionalRolloffFactor). AFarnot greater thanNear, infinite, orNaNturns distance attenuation off. - Rear head-shadow attenuation: sounds behind the listener (
dot(dir, forward) < 0) interpolate linearly from1at the lateral plane down toRearGaindirectly behind (DefaultRearGain,0.7, whenRearGainis zero, negative, orNaN; setRearGain: 1to disable). An effect behind the camera is therefore quieter than an equidistant effect in front while remaining panned to its left or right side. - Stereo pan:
Pan(pos)projects the unit direction from the listener to the source onto the listener's right axis (dot(dir, right)), clamped to[-1, 1]. Sounds at the listener, directly ahead, directly behind, directly overhead/underfoot, or withNaNcoordinates play centered (0). Set a positive finitePanWidthto use linear lateral-offset panning likeListener2D. - Directional source cones & overrides: pass
Spatial3DOptionstoListener3D.Spatialize,Spatialize3D,Listener3D.VoiceWithOptions,Effect.Play3D, orCue.Play3Dto add a directional emission cone (SourceForward,InnerConeAngle,OuterConeAngle,OuterGain) or per-sourceNear/Far/Rolloff/RolloffFactoroverrides. - Live
Playback3Dtracking:Mixer.SetListener3D(l)refreshes every activePlayback3Dstarted byEffect.Play3DorCue.Play3D, andPlayback3D.SetPosition/SetOptionsrefresh a single source. Live distance, rear, and source-cone attenuation update immediately throughaudio.Playback.SetVolumewhile honoring master/group volumes,SetPaused,SetPauseExempt,Suspend, and background muting. Because NSGo'saudio.Playbackcannot change stereo pan after starting,Playback3D.Pan()tracks the latest computed pan while the backend playback keeps its initial pan. - Pose helpers & cues:
Listener3D.SetPose(pos, forward, up)andListener3D.LookAt(target, up)update orientation without altering attenuation settings.Cue.PlayAt3DandCue.Play3Dposition randomized sound cues in 3D.
Mono audio and left/right balance
Players with hearing in one ear can miss sounds panned to the other side. Mixer supports mono voice panning and a stereo left/right balance offset across every effect it plays (Effect.Play, Effect.PlayAt, Effect.PlayAt3D, Effect.Play3D, and Cue variants):
mixer.SetMono(true) // center every voice to pan 0, keeping distance/rear/cone attenuation
mixer.FollowSystemMono() // return to following the platform's mono audio switch
mixer.SetBalance(-0.3) // shift stereo panning left by 0.3 when mono is off (clamped to [-1, 1])
- Mono mode: when
mixer.Mono()istrue, every voice the mixer starts (or updates once NSGo exposes livePlayback.SetPan) uses pan0while keeping distance, rear head-shadow, and source-cone attenuation unchanged, so distance cues still work.Listener2D.Pan,Listener3D.Pan, andPlayback3D.Pan()still report the listener's geometric direction, so directional captions (a11y.CaptionTrack.ShowSFXAt) keep the direction the sound would have had. - Left/right balance:
SetBalance(float32)sets an offset in[-1, 1](-1full left,0centered,+1full right; out-of-range values clamp andNaNresets to0). When mono is off, each voice addsBalance()to its pan and clamps to[-1, 1]. While mono is on, every voice plays at pan0and the configured balance is retained for when mono is turned off. - Platform switch and settings:
NewMixerfollows the platform's mono audio switch untilSetMonois called, andFollowSystemMono()restores follow-system mode. Persist both preferences insave.AudioSettings(Mono *bool,nilto follow system;Balance float64in[-1, 1]), whichsave.Applyapplies toSettingsTargets.Soundandgameui.SettingsMenu's Audio tab exposes as Mono Audio and Balance rows. - Stereo assets and NSGo follow-ups: stereo audio files (such as stereo music or ambience tracks) keep their channels until NSGo supports mixing the output down to mono (
nsgo-dev/nsgo#2676), and following the OS mono audio switch automatically activates once NSGo exposesEnv.MonoAudio(nsgo-dev/nsgo#2677; defaults tofalseon NSGo v0.3.4).
Music and crossfades
mixer.Music(group) plays streaming tracks through audio.Player, one active track at a time, with smooth crossfades:
music := mixer.Music("music")
music.Loop = true
music.Play(audio.Source{URI: "asset:music/overworld.m4a"}, 2*time.Second)
Loop: whentrue, tracks started by subsequentPlaycalls loop at their end.Play(src, fade): starts the new track at once, muted, and fades it in overfadewhile fading all currently playing tracks out on display frames (core.Scope.Animate), closing faded-out players once they reach silence. Whenfade <= 0, it switches immediately. Starting anotherPlaymid-crossfade smoothly fades out the incoming track from its current level.Stop(fade): fades active music out overfadeand closes its players (fade <= 0stops immediately).- A
srcholding in-memory 16-bit PCM WAV data is processed through the group's bus effect chain before playing; any other source plays as it is.
Intro and loop music
Most game music plays an intro once and then loops the main body indefinitely.
Recommended: single file with PlayLooped
Keep intro and loop in one audio file and pass the loop point's timestamp to PlayLooped(src, loopStart, fade):
music.PlayLooped(
audio.Source{URI: "asset:music/boss.m4a"},
12*time.Second, // intro plays 0s..12s once, then 12s..end repeats
time.Second,
)
PlayLooped creates a single audio.Player with audio.PlayerOptions.LoopStart, so the loop return runs inside the native player with no handoff gap or click across platforms. It always loops regardless of music.Loop (without changing music.Loop for later Play calls), crossfades and pauses like Play, processes in-memory 16-bit PCM WAV sources through the group's bus effect chain, loops the full track when loopStart <= 0 (or >= duration), and stops the music over fade if src is empty.
Split files with PlaySections / PlayWithIntro
When intro and loop arrive as two separate files that cannot be combined into one asset, use PlaySections(intro, loop, fade) or PlayWithIntro(sound.SectionedTrack{Intro, Loop}, fade):
music.PlayWithIntro(sound.SectionedTrack{
Intro: audio.Source{URI: "asset:music/boss_intro.m4a"},
Loop: audio.Source{URI: "asset:music/boss_loop.m4a"},
}, time.Second)
PlaySectionsplaysintroonce without looping, preloadsloopwith looping enabled, and schedulesloopslightly ahead ofintro's reported duration usingOnProgress(falling back toOnEndwhen duration is unknown) while lettingintrofinish its remaining samples.- Stopping or starting another track during the intro cancels
loopso it never plays. - If
introis empty,loopplays directly with looping enabled; ifloopis empty,introplays once without looping; if both are empty,PlaySectionsstops the music overfade. - Because two-file playback coordinates two separate
audio.Playerinstances across engine turns, it may still leave a slight seam or overlap under load or on the web. Prefer a single file withPlayLoopedwhenever you control the asset.
Web autoplay and gesture unlock
On the web, browsers refuse audio playback (audio.NotAllowed) until the page has received a user gesture. You can still call music.Play (or PlayLooped / PlaySections) during setup as on native targets:
- When a music player fails with
audio.NotAllowed, the track stays current at position0with its group volume, crossfade level, loop settings and any armed intro handoff intact, andmusic.Blocked()reportstrue. Other failures (such as a decode error) still end the track. - Call
mixer.Unblock()once audio is allowed — assignactions.Mixer = mixeroninput.Actionsso the first press, touch or key press retries automatically, and callmixer.Unblock()from any standalone press handler (such as a HUD button) that does not route throughinput.Actions. music.Blocked()is reactive, so reading it inside a view lets you show a "Tap for sound" hint that disappears as soon as playback unblocks:
core.Show{
When: music.Blocked,
Then: func(*core.Scope) core.Node {
return core.Text{Content: "Tap for sound"}
},
}
Pausing with the game
mixer.SetPaused(true) pauses gameplay audio when a pause menu opens, and mixer.SetPaused(false) resumes it when the menu closes:
- Gameplay groups (any group not marked exempt): playing
Effects are silenced through theiraudio.Playbackwithout stopping, newEffect.Playcalls returnfalse, andMusicpauses at its current position. On resume, effects still playing return to their volume and music continues from where it paused. Because NSGo v0.3.0'saudio.Playbackprovides volume, rate and stop controls without a playhead pause command, short one-shot effects finish silently if the pause lasts longer than their remaining duration, while looping effects andMusic(audio.Player) resume right where they left off. - Exempt groups: call
mixer.SetPauseExempt("ui", true)so pause-menu clicks or menu music keep playing whilemixer.Paused()istrue.mixer.PauseExempt(group)reports whether a group is exempt, and toggling exemption while paused applies immediately. - Loop sync: pair
mixer.SetPausedwithgame.Loop.OnPauseso gameplay sounds pause and resume automatically wheneverloop.SetPausedorloop.Pausedchanges:
mixer.SetPauseExempt("ui", true)
loop := &game.Loop{
Rate: 60,
OnPause: mixer.SetPaused,
Update: stepWorld,
Draw: renderWorld,
}
loop.Run(cx)
Background muting
NewMixer watches cx.Env().Lifecycle() on the same condition as game.Loop.Run, so backgrounding pauses and resumes audio in sync with the loop:
- When the app enters
core.LifecycleBackground(minimized, hidden or covered on desktop; backgrounded on iOS or Android), the mixer silences every playing effect (including pause-exempt groups such as"ui"), drops newEffect.Playcalls, and pauses all music. - When the window returns to
core.LifecycleActiveorcore.LifecycleInactive(visible, even unfocused on desktop), pause-exempt groups resume at once, while gameplay groups resume only ifmixer.Paused()isfalse— returning from the background while the pause menu is still open keeps gameplay sounds silenced and gameplay music paused at its position until the menu closes.
Suspending for a cutscene
mixer.Suspend() silences the mixer the same way the background does, until the resume function it returns is called: effects playing are silenced, new Effect.Play calls play nothing, and music pauses and later plays on from where it stopped. Holds nest, so the mixer plays again only once every Suspend has been resumed; calling one resume twice does nothing. mixer.Suspended() reports whether a hold is left.
resume := mixer.Suspend()
// ... something else has the speakers ...
resume()
cutscene's Player suspends the mixer while a video plays.
Testing with nsgotest
Enable virtual audio in nsgotest with nsgotest.Environment(core.Environment{Audio: true}) and configure decoded durations on app.AudioDurations to test voice limits, crossfades, persistence and background muting deterministically:
package mygame_test
import (
"testing"
"time"
"github.com/nsgo-dev/game/pkg/sound"
"github.com/nsgo-dev/nsgo/audio"
"github.com/nsgo-dev/nsgo/core"
"github.com/nsgo-dev/nsgo/nsgotest"
)
func TestMain(m *testing.M) { nsgotest.Main(m) }
func TestMixerCrossfadeAndMute(t *testing.T) {
var mixer *sound.Mixer
var music *sound.Music
app := nsgotest.Start(t, func(cx *core.Scope) core.Node {
mixer = sound.NewMixer(cx, "sound")
music = mixer.Music("music")
music.Loop = true
return core.View{}
},
nsgotest.Environment(core.Environment{Audio: true}),
func(a *nsgotest.App) {
a.AudioDurations = map[string]time.Duration{
"asset:a.m4a": time.Minute,
"asset:b.m4a": time.Minute,
}
},
)
mixer.SetVolume("music", 0.5)
music.Play(audio.Source{URI: "asset:a.m4a"}, 0)
music.Play(audio.Source{URI: "asset:b.m4a"}, time.Second)
app.Advance(1100 * time.Millisecond)
if !app.Players[0].Closed || !app.Players[1].Playing {
t.Fatalf("expected track A closed and track B playing")
}
app.SetEnvironment(core.Environment{Audio: true, Lifecycle: core.LifecycleBackground})
app.Settle()
if app.Players[1].Playing {
t.Fatal("expected music paused in background")
}
}
Captions for positional sounds
Effect.SetCaption(label, callback) calls callback with label and the listener pan each time PlayAt, PlayAt3D, their With forms, or a Cue playing the effect at a position starts a playback, so a caption points where the player hears the sound. Plain Play has no position and does not call it; a nil callback removes it. Connect it to a11y.CaptionEmitter.Emit, which shows the caption on a CaptionTrack and drops a label repeated within MinInterval (default a11y.DefaultCaptionMinInterval, 250 ms, on the track's clock):
emitter := a11y.NewCaptionEmitter(captions)
door.SetCaption("Door creaks", func(label string, pan float32) {
emitter.Emit(label, a11y.CaptionSFX, pan, 0)
})
Animation resources can now carry timed sounds and nested clips keys, while events may include scalar args for gameplay callbacks.
Scene emitters and zones
Scene objects can reference a sound resource with autoplay, looping, distance culling, far-cutoff filtering and Doppler intent. A soundZone record names the bus and fade/reverb-send values for listener transitions.
Sound resources
resource.Sound files define bus, voice limit, deterministic variant mode, pitch and volume ranges, weighted source clips and optional 3D attenuation.
Adaptive music resources
resource.Music files define BPM, clips, synchronized stems, bar-synced transitions and deterministic playlists. Sources are project-relative paths validated during resource parsing.
Dynamics effects
sound.Compressor(thresholdDB, ratio, attackMs, releaseMs) is a feed-forward peak compressor: above the threshold, each channel's level rises only 1/ratio dB per input dB, following peaks over attackMs and recovering over releaseMs. sound.Limiter(ceilingDB) clips every sample to the ceiling. Both are BusEffects for Mixer.SetGroupEffects and the offline PCM and WAV helpers; bus layouts and game.yaml cannot declare them yet (#1399).
Opt-in software mixer
NewSoftwareMixer provides a deterministic interleaved-float mixer for stateful effects implementing StatefulBusEffect. Each bus owns effect instances so filters and delays retain state across blocks. The existing native mixer remains the default path.