agentleFS
bmcszkbmcszk/agent-skills/skills/ebiten/audio/SKILL.md

audio

Skill1 starsChanged 2 months agoMITView on GitHub

Ebitengine audio: sound effects, music, audio players, streaming, resound effects.

6 other projects use a version of this.

Adopted by

Most recently taken up by

The file

We split this skill into the rules it gives an agent

6 rules. 0 are common, 4 are distinctive, and 2 are very specific to this project.

  • 0

    Common

    Most of the 5 edited versions we read keep these.

  • 4

    Distinctive

    This author's own choices. Worth a look.

  • 2

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Every Ebitengine audio session requires a single audio.Context:

    line 17
  2. Very specific:

    Create exactly one audio.Context for the entire game

    line 36
  3. Distinctive:

    Create it once at startup (not per frame)

    line 37
  4. Distinctive:

    Use this skill only when the task clearly matches the scope described above.

    line 367
  5. Distinctive:

    Do not treat the output as a substitute for environment-specific validation, testing, or expert review.

    line 368
  6. Distinctive:

    Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.

    line 369

“Common” is measured: kept by at least 6 in 10 of the 5 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Audio

Sound effects, music, and audio playback in Ebitengine.


Audio Context Initialization

Every Ebitengine audio session requires a single audio.Context:

import "github.com/hajimehoshi/ebiten/v2/audio"

const sampleRate = 44100

type Game struct {
    audioCtx *audio.Context
}

func NewGame() *Game {
    return &Game{
        audioCtx: audio.NewContext(sampleRate),
    }
}

Rules:

  • Create exactly one audio.Context for the entire game
  • Create it once at startup (not per frame)
  • Sample rate must match your audio files (typically 44100 Hz)

Playing Sounds from WAV/OGG/MP3

Loading Audio Files

import (
    "bytes"
    "io"

    "github.com/hajimehoshi/ebiten/v2/audio"
    "github.com/hajimehoshi/ebiten/v2/audio/wav"
    "github.com/hajimehoshi/ebiten/v2/audio/vorbis"
    "github.com/hajimehoshi/ebiten/v2/audio/mp3"
)

func loadWAV(audioCtx *audio.Context, data []byte) (*audio.Player, error) {
    return wav.Decode(audioCtx, bytes.NewReader(data))
}

func loadOGG(audioCtx *audio.Context, data []byte) (*audio.Player, error) {
    return vorbis.Decode(audioCtx, bytes.NewReader(data))
}

func loadMP3(audioCtx *audio.Context, data []byte) (*audio.Player, error) {
    return mp3.Decode(audioCtx, bytes.NewReader(data))
}

Decoder Import Table

FormatImportDecoder
WAVebiten/v2/audio/wavwav.Decode()
OGG/Vorbisebiten/v2/audio/vorbisvorbis.Decode()
MP3ebiten/v2/audio/mp3mp3.Decode()
XMgithub.com/quasilyte/xmxm.NewFromData()
Custom PCMManual io.Readeraudio.NewPlayer()

Playing a Sound Effect

type Game struct {
    audioCtx  *audio.Context
    jumpSound *audio.Player
}

func NewGame() *Game {
    g := &Game{
        audioCtx: audio.NewContext(44100),
    }

    jumpData, _ := os.ReadFile("assets/jump.wav")
    g.jumpSound, _ = wav.Decode(g.audioCtx, bytes.NewReader(jumpData))

    return g
}

func (g *Game) Update() error {
    if inpututil.IsKeyJustPressed(ebiten.KeySpace) {
        g.playSound(g.jumpSound)
    }
    return nil
}

func (g *Game) playSound(p *audio.Player) {
    p := g.audioCtx.NewPlayerFromBytes(g.audioCtx, p.(interface{ Bytes() []byte }).Bytes())
    p.Play()
}

Background Music (Looping)

Simple Loop

type Game struct {
    audioCtx *audio.Context
    bgm      *audio.Player
}

func NewGame() *Game {
    g := &Game{
        audioCtx: audio.NewContext(44100),
    }

    bgmData, _ := os.ReadFile("assets/music.ogg")
    bgmPlayer, _ := vorbis.Decode(g.audioCtx, bytes.NewReader(bgmData))
    g.bgm = audio.NewInfiniteLoop(bgmPlayer, bgmPlayer.Length())
    g.bgm.Play()

    return g
}

InfiniteLoop

audio.NewInfiniteLoop wraps a decoded audio player for seamless looping:

decoded, _ := vorbis.Decode(audioCtx, reader)
loop := audio.NewInfiniteLoop(decoded, decoded.Length())
loop.Play()

NewInfiniteLoop takes the source player and its total length. It creates a seamlessly looping player.


Audio Pool for Simultaneous Sounds

To play the same sound multiple times simultaneously (e.g., rapid gunfire):

type SoundPool struct {
    audioCtx *audio.Context
    sounds   map[string][]byte
}

func NewSoundPool(audioCtx *audio.Context) *SoundPool {
    return &SoundPool{
        audioCtx: audioCtx,
        sounds:   make(map[string][]byte),
    }
}

func (p *SoundPool) Load(name string, data []byte) {
    p.sounds[name] = data
}

func (p *SoundPool) Play(name string) {
    data, ok := p.sounds[name]
    if !ok {
        return
    }
    player := p.audioCtx.NewPlayerFromBytes(data)
    player.Play()
}

Usage

pool := NewSoundPool(audioCtx)

// Pre-load sounds
jumpData, _ := os.ReadFile("assets/jump.wav")
pool.Load("jump", jumpData)

shootData, _ := os.ReadFile("assets/shoot.wav")
pool.Load("shoot", shootData)

// Play anytime (each call creates a new player)
pool.Play("jump")
pool.Play("shoot")

Limiting Concurrent Sounds

type CappedSoundPool struct {
    audioCtx  *audio.Context
    sounds    map[string][]byte
    active    []*audio.Player
    maxActive int
}

func (p *CappedSoundPool) Play(name string) {
    // Clean up finished players
    alive := p.active[:0]
    for _, player := range p.active {
        if player.IsPlaying() {
            alive = append(alive, player)
        }
    }
    p.active = alive

    if len(p.active) >= p.maxActive {
        return
    }

    data := p.sounds[name]
    player := p.audioCtx.NewPlayerFromBytes(data)
    p.active = append(p.active, player)
    player.Play()
}

resound Effects Library

resound provides audio effects: delay, low-pass filter, panning, distortion, and more.

import "github.com/SolarLune/resound"

// Create effects chain
delay := resound.NewDelay(audioCtx)
delay.SetDelayTime(0.3)
delay.SetFeedback(0.5)

lowpass := resound.NewFilter(audioCtx)
lowpass.SetType(resound.FilterTypeLowPass)
lowpass.SetCutoff(800)

pan := resound.NewPan(audioCtx)
pan.SetPan(0.5) // -1.0 (left) to 1.0 (right)

// Apply to player
delay.SetSource(bgmPlayer)
lowpass.SetSource(delay)
pan.SetSource(lowpass)
pan.Play()

Available Effects

EffectTypePurpose
resound.NewDelay()Delay/EchoEcho effect
resound.NewFilter()FilterLow-pass, high-pass, band-pass
resound.NewPan()PanningStereo positioning
resound.NewDistortion()DistortionOverdrive effect
resound.NewCompressor()CompressorDynamic range compression
resound.NewReverb()ReverbRoom ambiance

Audio File Format Matrix

FormatExtensionProsConsBest For
WAV.wavFast decode, no quality lossLarge file sizeShort SFX
OGG/Vorbis.oggSmall size, good qualityCPU to decodeMusic, long SFX
MP3.mp3Universal, smallGap on loop (encoder padding)Non-looping music
XM.xmTiny file, proceduralTracker knowledge neededRetro music

Recommendations

  • Sound effects: WAV (short) or OGG (long)
  • Background music: OGG (for looping) or XM (for retro)
  • Avoid MP3 for looping BGM — encoder padding causes audible gaps

Volume Control

// Set volume (0.0 to 1.0)
player.SetVolume(0.5)

// Master volume pattern
type AudioManager struct {
    masterVolume float64
    sfxVolume    float64
    musicVolume  float64
    audioCtx     *audio.Context
}

func (m *AudioManager) PlaySFX(player *audio.Player) {
    player.SetVolume(m.masterVolume * m.sfxVolume)
    player.Play()
}

func (m *AudioManager) SetMusicVolume(vol float64) {
    m.musicVolume = vol
    if m.currentBGM != nil {
        m.currentBGM.SetVolume(m.masterVolume * m.musicVolume)
    }
}

Pausing and Resuming

// Pause
player.Pause()

// Resume
player.Play()

// Check state
player.IsPlaying()

// Seek
player.SetPosition(timeOffset)

Audio Guidelines

  1. Load all audio at startup — never load during gameplay
  2. Use NewPlayerFromBytes for SFX — allows simultaneous playback
  3. Use InfiniteLoop for BGM — seamless looping
  4. Prefer OGG over MP3 for music — no gap issues on loop
  5. Keep sample rate consistent — all files at 44100 Hz
  6. Cap concurrent sounds — too many active players degrades performance
  7. Clean up finished players — call Close() or let GC handle it
  8. Test on target platforms — audio behavior differs on mobile/WASM

Anti-Patterns

Don'tDo
Create audio.Context per frameCreate exactly one at startup
Use MP3 for looping BGMUse OGG/WAV for seamless loops
Decode audio in Update()/Draw()Decode at load time, store bytes
Play raw decoded player for SFXUse NewPlayerFromBytes for each play
Ignore IsPlaying() cleanupClose or pool finished players
Load large uncompressed WAV for musicUse compressed OGG for long audio
Skip audio initialization error checksAlways check errors from NewContext
Use different sample rates for filesStandardize on 44100 Hz
Create new os.File reads per playRead file once, store []byte

When to Use

This skill is applicable when implementing or modifying audio in an Ebitengine game: sound effects, background music, audio effects, or resource management.

Limitations

  • Use this skill only when the task clearly matches the scope described above.
  • Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
  • Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.