Diese Seite ist noch nicht auf Deutsch übersetzt und wird daher auf Englisch angezeigt.
2D-Kernsound
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})
}
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.
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).
On the web, browsers enforce autoplay policies and refuse playback (audio.NotAllowed) until the user interacts with the page; start music from a button press or first tap/click.
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")
}
}