sound

package
v0.0.0-...-94fff03 Latest Latest
Warning

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

Go to latest
Published: Dec 5, 2026 License: MIT Imports: 18 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package sound plays sound effects and music.

It has a data half and a runtime half, like package anim. The data half is the asset types Sound (a short effect, decoded to PCM on a worker) and Music (a track kept compressed and streamed while it plays), which RegisterLoaders makes loadable from .wav, .ogg and .mp3 files.

The runtime half mirrors rendering. Gameplay systems push requests into the Queue resource (Queue.Play, Queue.PlayMusic); the AudioSystem drains it once per tick, applies the Mixer's bus volumes and voice limits, crossfades music, plays gfx.SoundEmitter components and hands the result to a Backend. A sound that is not loaded yet is skipped: the placeholder of an audio asset is silence.

The Backend is the only part that touches the audio device: NewEbitenBackend plays through Ebiten's audio package, NullBackend plays nothing (tests, servers, headless tools). The guide is doc/guide/engine/audio.md.

Index

Constants

View Source
const (
	// AssetKindSound is a [Sound], a short effect decoded to memory.
	AssetKindSound = "sound"
	// AssetKindMusic is a [Music], a track streamed while it plays.
	AssetKindMusic = "music"
)

Asset kinds of this package: the names a component field carries in its +game:asset:kind=... marker.

View Source
const (
	DefaultMaxVoices        = 32
	DefaultSameSoundPerTick = 2
)

Default limits of a Mixer.

View Source
const DefaultSampleRate = 48000

DefaultSampleRate is the sample rate RegisterLoaders uses for 0, and the one game.Engine opens the audio device with.

View Source
const DefaultStreamBuffer = 50 * time.Millisecond

DefaultStreamBuffer is the player buffer of a stream whose StreamSource.Buffer is 0: small enough for dialogue blips to follow the text, large enough to survive a slow frame.

View Source
const NumBuses = 8

NumBuses is the number of buses a Mixer has. A Bus at or above it is treated as BusSFX.

View Source
const StreamReadTimeout = 200 * time.Millisecond

StreamReadTimeout is how long a stream may go without the audio side reading from it before Stream.Reading turns false. A browser keeps its audio context suspended until the first click, and a window that lost focus may pause its player.

Variables

This section is empty.

Functions

func HoldMusic

func HoldMusic(sc *asset.Scope, h gfx.MusicHandle)

HoldMusic adds sc as an owner of h, like asset.Hold.

func HoldSound

func HoldSound(sc *asset.Scope, h gfx.SoundHandle)

HoldSound adds sc as an owner of h, like asset.Hold.

func LoadMusic

func LoadMusic(sc *asset.Scope, key string) gfx.MusicHandle

LoadMusic returns the handle for a track key ("music/level1.ogg") and adds a hold for sc. It never blocks and panics like asset.Load.

func LoadMusicSync

func LoadMusicSync(sc *asset.Scope, key string) (gfx.MusicHandle, error)

LoadMusicSync is LoadMusic followed by loading until the track is ready or failed, like asset.LoadSync. It blocks: use it for boot screens, tests and tools.

func LoadSound

func LoadSound(sc *asset.Scope, key string) gfx.SoundHandle

LoadSound returns the handle for a sound key ("sfx/hit.wav") and adds a hold for sc. It never blocks and panics like asset.Load.

func LoadSoundSync

func LoadSoundSync(sc *asset.Scope, key string) (gfx.SoundHandle, error)

LoadSoundSync is LoadSound followed by loading until the sound is ready or failed, like asset.LoadSync. It blocks: use it for boot screens, tests and tools.

func RegisterLoaders

func RegisterLoaders(srv *asset.Server, sampleRate int)

RegisterLoaders registers Sound and Music and their loaders on srv. sampleRate is the rate sounds are decoded to; it must match the rate of the audio device (the Ebiten audio.Context) they play on. 0 means DefaultSampleRate.

It makes no audio calls, so it needs no audio device and may run on any goroutine that owns srv. It panics like asset.Register if a type is already registered.

Types

type AudioSystem

type AudioSystem struct {
	// OnError receives errors from the Backend (for example a sample rate
	// mismatch). The request or emitter that caused it is dropped. nil
	// ignores them.
	OnError func(error)
	// contains filtered or unexported fields
}

AudioSystem turns the tick's requests into playing voices. Each Run it:

  1. releases voices that finished;
  2. plays gfx.SoundEmitter components (see below);
  3. drains the Queue: ready sounds start, within the Mixer's limits;
  4. switches and crossfades music;
  5. applies volumes (request or emitter, bus, master, fade) and pan (request, or the Listener for positional sounds) to every voice.

Emitters: a one-shot emitter starts once its sound is Ready, then sets Done (and Voice); the sound plays to its end even if the entity is deleted right away. A looping emitter keeps one voice for as long as the entity has the component and Done is unset; its pan and volume follow the entity and the component every tick, and the voice stops when the entity is deleted or the component removed. An emitter whose sound failed to load sets Done.

Run it at the end of the tick, after gameplay has pushed its requests. It needs the *asset.Server resource with RegisterLoaders run on it; it uses the *Queue and *Mixer resources, creating them in Init if they are not set, and the optional *Listener resource. Run does not allocate in steady state; starting a voice allocates in the Backend.

func NewAudioSystem

func NewAudioSystem(w *ecs.World, b Backend) *AudioSystem

NewAudioSystem returns the system for w, playing on b. A nil b means NullBackend.

func (*AudioSystem) AddStream

func (s *AudioSystem) AddStream(src StreamSource) (*Stream, error)

AddStream starts reading src.Reader on the backend and returns the running stream, or the backend's error. The stream plays until Stream.Close, until its reader ends, or until AudioSystem.Close. Its volume is the bus's × master × the stream's own, applied every tick like a voice's.

func (*AudioSystem) Close

func (s *AudioSystem) Close()

Close stops every voice and track. Call it when the game ends; the system can run again afterwards.

func (*AudioSystem) Init

func (s *AudioSystem) Init(ctx *system.Context)

Init implements system.Initializer. It caches the stores and the Queue and Mixer resources, creating the latter two if they are not set.

func (*AudioSystem) Run

func (s *AudioSystem) Run(ctx *system.Context)

Run implements system.Runner.

func (*AudioSystem) Stats

func (s *AudioSystem) Stats() Stats

Stats returns what the last Run did.

type Backend

type Backend interface {
	// PlaySound starts s, repeated forever if loop is set, with the given
	// gains (see [Voice.SetGains]). s has at least one frame.
	PlaySound(s *Sound, loop bool, left, right float32) (Voice, error)
	// PlayMusic starts streaming m, looping, with the given gains. m has at
	// least one frame.
	PlayMusic(m *Music, left, right float32) (Voice, error)
	// PlayStream starts reading src, which delivers stereo PCM in format at
	// the device's sample rate, with the given gains. buffer is the
	// player's buffer size (0 means the backend's default); a larger buffer
	// is safer against stalls, a smaller one lowers the latency of what the
	// source produces. The stream ends when src returns an error (io.EOF
	// included) or on Stop.
	PlayStream(src io.Reader, format StreamFormat, buffer time.Duration, left, right float32) (StreamVoice, error)
}

Backend starts voices on an audio device. The AudioSystem is its only caller, on the game goroutine. Implement it to play through something other than Ebiten, or to observe playback in tests.

type Bus

type Bus uint8

Bus groups voices under one volume, for the options screen's sliders. A request names its bus; the zero Bus is BusSFX.

const (
	BusSFX   Bus = iota // effects from gameplay (Queue.Play, SoundEmitter)
	BusMusic            // music (Queue.PlayMusic always uses it)
	BusUI               // interface clicks and confirmations
	BusVoice            // dialogue
)

Predefined buses. Buses up to NumBuses-1 are free for the game's own use.

type EbitenBackend

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

EbitenBackend plays through an Ebiten audio.Context. Each voice is an audio.Player that reads its source through a gain stage (Ebiten players have no pan), so starting a voice allocates; a playing voice does not.

func NewEbitenBackend

func NewEbitenBackend(ctx *audio.Context) *EbitenBackend

NewEbitenBackend returns a backend that plays on ctx. Sounds and tracks must have been loaded with ctx's sample rate (RegisterLoaders).

func (*EbitenBackend) Context

func (b *EbitenBackend) Context() *audio.Context

Context returns the audio context the backend plays on.

func (*EbitenBackend) PlayMusic

func (b *EbitenBackend) PlayMusic(m *Music, left, right float32) (Voice, error)

PlayMusic implements Backend. The track is decoded while it plays.

func (*EbitenBackend) PlaySound

func (b *EbitenBackend) PlaySound(s *Sound, loop bool, left, right float32) (Voice, error)

PlaySound implements Backend. It returns an error if s was decoded at another sample rate than the context's.

func (*EbitenBackend) PlayStream

func (b *EbitenBackend) PlayStream(src io.Reader, format StreamFormat, buffer time.Duration, left, right float32) (StreamVoice, error)

PlayStream implements Backend. The source must produce frames at the context's sample rate. StreamFloat32 plays through NewPlayerF32.

type Format

type Format uint8

Format is the encoding of an audio file.

const (
	FormatUnknown Format = iota
	FormatWAV            // .wav
	FormatOgg            // .ogg (Ogg Vorbis)
	FormatMP3            // .mp3
)

Audio formats, chosen by file extension (case-insensitive).

func FormatOf

func FormatOf(name string) Format

FormatOf returns the format for a file name by its extension.

func (Format) String

func (f Format) String() string

String returns "wav", "ogg", "mp3" or "unknown".

type Listener

type Listener struct {
	// Pos is the listener's world position, usually the camera center.
	Pos gfx.Vec2
	// HalfWidth is the horizontal distance at which a sound is panned hard
	// left or right, usually half the visible world width. 0 disables
	// panning.
	HalfWidth float32
	// Range is the distance at which a sound fades to silence, linearly.
	// 0 disables distance attenuation.
	Range float32
}

Listener is where the player hears from: positional sounds (a SoundEmitter on an entity with a Transform, a PlaySound with At set) are panned and attenuated by their position relative to it. It is an optional world resource; without it positional sounds play centered and unattenuated. game.Engine keeps it at the camera.

type Mixer

type Mixer struct {
	// MaxVoices bounds the effect voices (queue requests and emitters,
	// not music) playing at once. A request that would exceed it is dropped;
	// an emitter retries on the next tick. 0 means DefaultMaxVoices.
	MaxVoices int
	// SameSoundPerTick bounds how often one sound starts from the queue in
	// a single tick, so ten enemies hit at once do not play ten identical
	// sounds at ten times the loudness. 0 means DefaultSameSoundPerTick.
	SameSoundPerTick int
	// contains filtered or unexported fields
}

Mixer is the volume and limit configuration the AudioSystem applies. It is a world resource; the AudioSystem creates one with NewMixer if none is set. Changes take effect on the next tick, for playing voices too.

Volumes are factors: 0 is silent, 1 is the recorded level. Values above 1 amplify (and may clip).

func NewMixer

func NewMixer() *Mixer

NewMixer returns a Mixer with every volume at 1 and the default limits. The zero Mixer has every volume at 0, which is silence.

func (*Mixer) Master

func (m *Mixer) Master() float32

Master returns the master volume.

func (*Mixer) SetMaster

func (m *Mixer) SetMaster(v float32)

SetMaster sets the volume that applies to every bus. Negative is 0.

func (*Mixer) SetVolume

func (m *Mixer) SetVolume(b Bus, v float32)

SetVolume sets the volume of bus b. Negative is 0.

func (*Mixer) Volume

func (m *Mixer) Volume(b Bus) float32

Volume returns the volume of bus b, not including the master volume.

type Music

type Music struct {
	// Data is the file as loaded. It is shared by every voice that plays the
	// track: never modify it.
	Data []byte
	// Format is the file's encoding, from its extension.
	Format Format
	// SampleRate is the rate the track is decoded to when it plays.
	SampleRate int
	// Duration is the track's length, from its header.
	Duration time.Duration
}

Music is a track that is kept compressed and decoded while it plays, so a three-minute song costs its file size, not 30 MB of PCM.

Load it with LoadMusic. The placeholder is an empty Music: it plays silence.

type MusicStore

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

MusicStore resolves gfx.MusicHandle values. Get one with MusicStoreOf. It is a small value; copy it freely.

func MusicStoreOf

func MusicStoreOf(srv *asset.Server) MusicStore

MusicStoreOf returns the track store of srv. It panics like asset.StoreOf if RegisterLoaders has not run on srv.

func (MusicStore) Err

func (s MusicStore) Err(h gfx.MusicHandle) error

Err returns why the track failed to load, or nil.

func (MusicStore) Generic

func (s MusicStore) Generic() *asset.Store[Music]

Generic returns the underlying generic store, for loaders and tools that work with asset.Handle[Music].

func (MusicStore) Get

func (s MusicStore) Get(h gfx.MusicHandle) *Music

Get returns the track, or the placeholder (silence); see asset.Store.Get for the pointer validity rule. It does not allocate.

func (MusicStore) Key

func (s MusicStore) Key(h gfx.MusicHandle) asset.Key

Key returns the key h was loaded from, or the zero Key for a zero or stale handle.

func (MusicStore) Lookup

func (s MusicStore) Lookup(h gfx.MusicHandle) (*Music, asset.State)

Lookup is Get plus the load state; see asset.Store.Lookup.

func (MusicStore) Ready

func (s MusicStore) Ready(h gfx.MusicHandle) bool

Ready reports whether h refers to a loaded track.

type NullBackend

type NullBackend struct{}

NullBackend plays nothing. Its one-shot voices end at once and its looping voices and tracks last until stopped, so the AudioSystem's bookkeeping behaves as with a device. Use it for servers, tools and tests.

func (NullBackend) PlayMusic

func (NullBackend) PlayMusic(*Music, float32, float32) (Voice, error)

PlayMusic implements Backend.

func (NullBackend) PlaySound

func (NullBackend) PlaySound(_ *Sound, loop bool, _, _ float32) (Voice, error)

PlaySound implements Backend.

func (NullBackend) PlayStream

PlayStream implements Backend. The source is never read, so a stream on the null backend reports no frames and a source that buffers while nobody reads must bound itself.

type PlaySound

type PlaySound struct {
	// Sound is the effect. A zero handle, or a sound that is not loaded
	// (yet), plays nothing: requests are never deferred, because a hit
	// sound a second late is worse than none.
	Sound gfx.SoundHandle
	// Volume scales the sound. Zero means 1, like SoundEmitter.Volume; a
	// negative value is silent.
	Volume float32
	// Pan places the sound from -1 (left) to 1 (right). It is ignored when
	// Positional is set.
	Pan float32
	// Bus is the mixer bus whose volume applies.
	Bus Bus
	// Positional takes the pan and a distance attenuation from At and the
	// Listener instead of Pan.
	Positional bool
	// At is the world position of a positional sound.
	At gfx.Vec2
}

PlaySound is a request to play a sound once, pushed with Queue.Play.

type Queue

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

Queue collects the sound and music requests of a tick. It is a world resource: gameplay systems push into it and the AudioSystem drains it at the end of the tick. Its buffer is reused, so pushing does not allocate in steady state. The zero Queue is ready to use.

func (*Queue) Len

func (q *Queue) Len() int

Len returns the number of sound requests waiting.

func (*Queue) Play

func (q *Queue) Play(p PlaySound)

Play requests a sound for this tick; see PlaySound.

func (*Queue) PlayMusic

func (q *Queue) PlayMusic(track gfx.MusicHandle, fade time.Duration)

PlayMusic switches the music to track, crossfading over fade (0 cuts). If track is still loading, the current music keeps playing until it is ready; if track is the music already playing, nothing changes. A zero or failed track stops the music. Music loops and plays on BusMusic. The last request of a tick wins.

func (*Queue) StopMusic

func (q *Queue) StopMusic(fade time.Duration)

StopMusic fades the music out over fade (0 cuts). The last request of a tick wins.

type Sound

type Sound struct {
	// PCM is the decoded audio, 4 bytes per frame (left, right). It is
	// shared by every voice that plays the sound: never modify it.
	PCM []byte
	// SampleRate is the rate PCM was decoded at.
	SampleRate int
}

Sound is a short effect, fully decoded on a worker to 16-bit signed little-endian stereo PCM at the server's sample rate (see RegisterLoaders). Playing it decodes nothing.

Load it with LoadSound. The placeholder is an empty Sound: it plays silence.

func (*Sound) Duration

func (s *Sound) Duration() time.Duration

Duration returns how long the sound plays.

type SoundStore

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

SoundStore resolves gfx.SoundHandle values. Get one with SoundStoreOf. It is a small value; copy it freely.

func SoundStoreOf

func SoundStoreOf(srv *asset.Server) SoundStore

SoundStoreOf returns the sound store of srv. It panics like asset.StoreOf if RegisterLoaders has not run on srv.

func (SoundStore) Err

func (s SoundStore) Err(h gfx.SoundHandle) error

Err returns why the sound failed to load, or nil.

func (SoundStore) Generic

func (s SoundStore) Generic() *asset.Store[Sound]

Generic returns the underlying generic store, for loaders and tools that work with asset.Handle[Sound].

func (SoundStore) Get

func (s SoundStore) Get(h gfx.SoundHandle) *Sound

Get returns the sound, or the placeholder (silence); see asset.Store.Get for the pointer validity rule. It does not allocate.

func (SoundStore) Key

func (s SoundStore) Key(h gfx.SoundHandle) asset.Key

Key returns the key h was loaded from, or the zero Key for a zero or stale handle.

func (SoundStore) Lookup

func (s SoundStore) Lookup(h gfx.SoundHandle) (*Sound, asset.State)

Lookup is Get plus the load state; see asset.Store.Lookup.

func (SoundStore) Ready

func (s SoundStore) Ready(h gfx.SoundHandle) bool

Ready reports whether h refers to a loaded sound.

type Stats

type Stats struct {
	// Voices is the number of effect voices playing (music not included).
	Voices int
	// Started is the number of effect voices started in the last Run.
	Started int
	// Dropped is the number of requests and emitter starts refused by the
	// Mixer's limits in the last Run.
	Dropped int
	// Streams is the number of stream sources playing.
	Streams int
	// Music reports whether a track is playing or fading in.
	Music bool
}

Stats describes the AudioSystem after its last Run.

type Stream

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

Stream is a playing stream source, started by AudioSystem.AddStream. Use it from the game goroutine only. Streams do not count against Mixer.MaxVoices.

func (*Stream) Close

func (s *Stream) Close()

Close stops the stream and releases its player. The stream must not be used afterwards; closing twice is harmless.

func (*Stream) Reading

func (s *Stream) Reading() bool

Reading reports whether the audio side is pulling samples from the source: true once frames were read and until StreamReadTimeout passes without a read. It is false right after AddStream, under NullBackend, while a browser has not started its audio context and after Close. It is updated by AudioSystem.Run, once per tick.

A source that queues commands for the next read (a synthesizer) uses it to drop what nobody listened to instead of playing it as a burst later.

func (*Stream) SetPan

func (s *Stream) SetPan(pan float32)

SetPan changes the stereo position, -1 (left) to 1 (right). It applies from the next tick.

func (*Stream) SetVolume

func (s *Stream) SetVolume(v float32)

SetVolume changes the stream's own volume factor (0 is silent; unlike in StreamSource, 0 does not mean 1). It applies from the next tick.

type StreamFormat

type StreamFormat uint8

StreamFormat is the PCM layout of a stream source: stereo, interleaved, little-endian, at the audio context's sample rate.

const (
	// StreamInt16 is 16-bit signed integer samples (4 bytes a frame), the
	// layout of every sound the package decodes.
	StreamInt16 StreamFormat = iota
	// StreamFloat32 is 32-bit float samples in [-1, 1] (8 bytes a frame).
	StreamFloat32
)

Stream formats.

type StreamSource

type StreamSource struct {
	// Reader produces the PCM. It is read on the audio goroutine, so it
	// must be safe against the game goroutine, must not block for long and
	// should not allocate. It ends the stream by returning an error.
	Reader io.Reader
	// Format is the layout Reader produces.
	Format StreamFormat
	// Bus is the bus whose volume applies (the zero Bus is BusSFX).
	Bus Bus
	// Volume is the stream's own volume factor; 0 means 1.
	Volume float32
	// Buffer is the player buffer size; 0 means [DefaultStreamBuffer].
	Buffer time.Duration
}

StreamSource describes a stream for AudioSystem.AddStream.

type StreamVoice

type StreamVoice interface {
	Voice
	// Frames returns how many stereo frames the audio side has read from
	// the source so far. It may be called from the game goroutine while the
	// audio goroutine reads.
	Frames() uint64
}

StreamVoice is a Voice that plays a stream source.

type Voice

type Voice interface {
	// SetGains changes the left and right gain (0 is silent, 1 is the
	// recorded level) of the playing voice.
	SetGains(left, right float32)
	// Playing reports whether the voice is still playing. A one-shot voice
	// stops by itself at its end; a looping one only through Stop.
	Playing() bool
	// Stop ends the voice and releases its resources. The Voice must not
	// be used afterwards.
	Stop()
}

Voice is one playing sound or track.

Jump to

Keyboard shortcuts

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