elevenlabs-sound-music · diff
git:20261114.b353ad0 to git:20261114.1296d8c
104 added, 183 removed. Audit A to A.
What this update changes in the checks
No check changed: every fixed check gives the same answer before and after this update.
A tripped check is a label, not a verdict: read the matched text and the lines below. This week's updates that newly trip a check.
---
name: elevenlabs-sound-music
description: >-
- Use when adding audio to a game — SFX generation, adaptive music, voice
- acting, and audio state machine integration. Covers BOTH ElevenLabs API AND
- Vertex AI Lyria as user-choosable alternatives for game audio production.
+ Covers generating game audio with ElevenLabs (voice lines, sound effects,
+ music) and Google Lyria 2 (instrumental music clips), and playing it in the
+ browser through an audio state machine with crossfades, per-layer volume and
+ an unlock on the first user input. Use when a game needs sound effects, NPC
+ voice lines or a soundtrack, when music must follow game state (menu,
+ exploration, combat, boss) without hard cuts, when audio stays silent on a
+ phone until the player taps, or when choosing between ElevenLabs and Lyria
+ for music.
---
- # ElevenLabs Sound & Music
-
- ## Purpose
-
- SFX generation, adaptive music, voice acting, and audio state machine integration for games. Covers **both** the ElevenLabs API (voice lines, SFX) **and** Vertex AI Lyria (music generation) as user-choosable alternatives. One skill, two providers, one unified audio pipeline.
-
- ## When to Use
-
- **Trigger keywords**: sound effects, SFX, music generation, voice acting, adaptive music, audio, ElevenLabs, Lyria, game audio, soundtrack, ambient sound, voice lines, text-to-speech, voice cloning, game music, audio state machine.
-
- Use this skill when:
- - Generating sound effects or voice lines via ElevenLabs
- - Generating music tracks via Vertex AI Lyria
- - Building an adaptive music system that responds to game state
- - Setting up an audio state machine with crossfade transitions
- - Implementing mobile audio unlock patterns
- - Designing a layered audio mix (music + SFX + ambient + voice)
-
- ## Prerequisites
-
- None. Provider-specific setup is covered in each client boilerplate.
-
- **ElevenLabs** requires an API key (`ELEVENLABS_API_KEY`).
- **Vertex AI Lyria** requires a Google Cloud project with Vertex AI API enabled and authentication (ADC or service account).
-
- ## Core Principles
-
- > *"Silence is as powerful as sound. Restraint in audio design creates moments of profound impact."* -- Fumito Ueda (ICO, Shadow of the Colossus)
-
- > *"Music should mirror the emotional arc. The soundtrack IS the emotional journey."* -- Jenova Chen (Journey)
-
- 1. **Audio is 50% of the experience** -- never an afterthought. Budget audio design time equal to visual design time.
- 2. **Adaptive music**: the soundtrack responds to game state (combat, exploration, menu). Never play a static playlist.
- 3. **Layered audio**: ambient + music + SFX + voice = immersive soundscape. Mix layers independently.
- 4. **Two providers, one interface**: ElevenLabs for voice/SFX, Lyria for music -- or mix them. The game code should not care which provider generated the audio file.
- 5. **Preload critical audio, lazy-load ambient**: menu music and combat stingers load first. Forest ambience can wait.
- 6. **Respect mobile audio restrictions**: iOS and Android require user interaction before playback. Gate audio behind a "Tap to Start" interaction.
- 7. **Audio state machine**: define states and transitions, not individual play commands. The system decides what to play based on current state.
-
- ## Step-by-Step
-
- ### 1. Choose your providers
-
- | Need | Provider | Why |
- |------|----------|-----|
- | Character voice lines | ElevenLabs TTS | Natural speech, voice cloning for consistency |
- | Sound effects | ElevenLabs SFX | Text-described SFX generation |
- | Background music | ElevenLabs Music API | Prompt-driven, up to 5 min, vocals or instrumental |
- | Background music (alt) | Vertex AI Lyria | 32.8s instrumental WAV, fixed duration |
- | Ambient loops | ElevenLabs Music API or Lyria | ElevenLabs for flexible duration, Lyria for WAV output |
-
- ### 2. Set up API clients
-
- - Copy `boilerplate/elevenlabs-client.ts` for voice and SFX generation
- - Copy `boilerplate/elevenlabs-music-client.ts` for ElevenLabs music generation (preferred for most games)
- - Copy `boilerplate/lyria-client.ts` for music generation
- - Configure environment variables for your chosen provider(s)
-
- ### 3. Define your audio states
-
- Use `templates/sound-config.ts` as a starting point. Define every game state that needs distinct audio (menu, exploration, combat, boss, social, idle). Map each state to track paths, volume levels, and crossfade durations.
-
- ### 4. Implement the audio manager
+ # Game Audio with ElevenLabs and Lyria
- Copy `boilerplate/audio-manager.ts` into your project. This provides:
- - State-based music switching with crossfade
- - Independent volume layers (music, SFX, voice, ambient)
- - Mobile audio unlock
- - Preload manifest support
+ Generate audio assets offline with the vendor SDKs, then play them through one state machine that the game drives.
- ### 5. Generate your audio assets
+ Related skills: `game-design-fundamentals` (audio as player feedback).
- Use the prompt templates from `templates/prompt-catalog.md`:
- - **ElevenLabs**: voice lines, UI sounds, combat SFX
- - **Lyria**: menu theme, exploration music, combat tracks, boss themes
+ ## Choose the provider
- ### 6. Convert and organize
+ | Asset | Use | Model id (set explicitly) |
+ |---|---|---|
+ | Pre-recorded dialogue | ElevenLabs Text to Speech | `eleven_multilingual_v2` |
+ | Lines generated while the player waits | ElevenLabs Text to Speech | `eleven_flash_v2_5` (about 100 ms median latency) |
+ | Sound effects, ambient loops | ElevenLabs Sound Effects, 0.5 to 30 s, `loop: true` for seamless ambience | `eleven_text_to_sound_v3` |
+ | Music of any length (3 s to 10 min), optional vocals, section control through a composition plan | ElevenLabs Music (paid plans only) | `music_v2_5` |
+ | Instrumental clips of about 30 s, up to 4 variations per prompt, billed to Google Cloud | Vertex AI Lyria 2 | `lyria-002` |
- Lyria outputs WAV (32.8s, 48 kHz stereo). Convert for web:
+ Lyria 3 is in preview on Vertex AI: `lyria-3-pro-preview` (up to 184 s, vocals, MP3) and `lyria-3-clip-preview` (30 s). It uses the `interactions` endpoint, not the predict call in `boilerplate/lyria-client.ts`. See https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/lyria/lyria-3.
- ```bash
- # WAV to OGG (primary web format)
- ffmpeg -i input.wav -c:a libvorbis -q:a 5 output.ogg
+ ElevenLabs lists `eleven_v4` under the Text to Dialogue API, which this skill does not cover.
- # WAV to MP3 (fallback)
- ffmpeg -i input.wav -c:a libmp3lame -q:a 2 output.mp3
- ```
+ ### Deprecated models
- ElevenLabs outputs MP3 or OGG directly -- no conversion needed.
+ From https://elevenlabs.io/docs/overview/models#deprecated-models:
- ### 7. Integrate with game state
+ - `eleven_text_to_sound_v2` is removed on 2027-03-01. It is still the Sound Effects default when `model_id` is unset.
+ - `music_v1` is removed on 2027-01-31. It is still the Music default when `model_id` is unset.
+ - `eleven_turbo_v2_5` and `eleven_turbo_v2` are deprecated in favour of the Flash models (no removal date given).
- Subscribe your audio manager to game state changes. When the game enters combat, the audio manager crossfades to the combat track. When combat ends, it plays the victory stinger then fades back to exploration.
+ ## Procedure
- ## Code Examples
+ 1. List the game's audio states and copy `templates/sound-config.ts`. Map each state to a music track, an optional ambient loop, and a crossfade time per transition.
+ 2. Write prompts from `templates/prompt-catalog.md`. Answer genre, mood, instruments, tempo and era in each music prompt.
+ 3. Generate the assets in a build script or on a server, never in the game client. The API keys stay out of the bundle.
+ 4. Save one manifest entry per accepted file: provider, model id, prompt, length, plan or seed. Without it you cannot regenerate a track.
+ 5. Lyria returns WAV. Convert it to a compressed format before shipping.
+ 6. In the client, create the `AudioManager`, call `unlockMobile()` at startup, call `transition()` on every game-state change, and `preload()` the tracks the next state is likely to need.
- ### ElevenLabs: Generate a voice line
+ ## Files
- ```typescript
- import { ElevenLabsClient } from './elevenlabs-client';
+ - Copy when generating voice, sound effects or music with ElevenLabs: `boilerplate/elevenlabs-audio.ts`.
+ - Copy when generating instrumental clips with Lyria 2: `boilerplate/lyria-client.ts`. It needs `@google-cloud/aiplatform` and Application Default Credentials.
+ - Copy when wiring playback in the browser: `boilerplate/audio-manager.ts`.
+ - Copy when defining the game's audio states: `templates/sound-config.ts`.
+ - Read when writing prompts or a regeneration manifest: `templates/prompt-catalog.md`.
+ - Read when checking a model id, limit or date: `references/sources.md`.
- const client = new ElevenLabsClient(process.env.ELEVENLABS_API_KEY!);
+ Vendor docs for anything beyond these files:
- // Generate NPC dialogue
- const audioBuffer = await client.textToSpeech(
- 'Welcome, traveler. The road ahead is dangerous.',
- { voiceId: 'your-voice-id', model: 'eleven_multilingual_v2' },
- );
- await Bun.write('public/audio/voice/npc_greeting.mp3', audioBuffer);
- ```
+ - Use the `text-to-speech` skill if it is installed, otherwise https://elevenlabs.io/docs/api-reference/text-to-speech/convert.
+ - Use the `sound-effects` skill if it is installed, otherwise https://elevenlabs.io/docs/api-reference/text-to-sound-effects/convert.
+ - Use the `music` skill if it is installed, otherwise https://elevenlabs.io/docs/eleven-api/guides/cookbooks/music.
+ - Lyria 2 API reference: https://docs.cloud.google.com/gemini-enterprise-agent-platform/reference/models/lyria-music-generation.
- ### ElevenLabs: Generate a sound effect
+ The three ElevenLabs skills come from https://github.com/elevenlabs/skills.
- ```typescript
- const sfxBuffer = await client.generateSfx(
- 'sword clash, metallic impact, brief reverb',
- { duration: 2 },
- );
- await Bun.write('public/audio/sfx/sword_clash.mp3', sfxBuffer);
- ```
+ ## Code examples
- ### ElevenLabs Music API: Generate a combat track
+ ### ElevenLabs: voice line, ambient loop, combat track
```typescript
- // Uses @elevenlabs/elevenlabs-js directly (not the wrapper in elevenlabs-client.ts)
import { ElevenLabsClient } from '@elevenlabs/elevenlabs-js';
- import { writeFileSync } from 'node:fs';
+ import {
+ composeFromPlan,
+ composeMusic,
+ createMusicPlan,
+ generateSfx,
+ generateVoiceLine,
+ saveAudio,
+ } from './elevenlabs-audio';
- const client = new ElevenLabsClient({ apiKey: process.env.ELEVENLABS_API_KEY });
+ const client = new ElevenLabsClient(); // reads ELEVENLABS_API_KEY
- // Basic generation
- const audio = await client.music.compose({
- prompt: 'Intense battle music, driving and urgent, 150 BPM, electric guitar riffs, pounding drums, brass stabs, instrumental only',
- musicLengthMs: 60000,
+ const greeting = await generateVoiceLine(client, {
+ text: 'Welcome, traveler. The road ahead is dangerous.',
+ voiceId: 'your-merchant-voice-id',
});
-
- const chunks: Buffer[] = [];
- for await (const chunk of audio) {
- chunks.push(Buffer.from(chunk));
- }
- writeFileSync('public/audio/music/combat_standard.mp3', Buffer.concat(chunks));
- ```
-
- For granular control, generate a composition plan first:
+ await saveAudio('public/audio/voice/merchant/greeting.mp3', greeting);
- ```typescript
- // compositionPlan API may require a recent ElevenLabs SDK version; check docs if unavailable
- const plan = await client.music.compositionPlan.create({
- prompt: 'Intense battle music, 150 BPM, no vocals',
- musicLengthMs: 60000,
+ const rain = await generateSfx(client, {
+ text: 'Soft rain on a tin roof, distant thunder',
+ durationSeconds: 30,
+ loop: true,
});
- // Inspect plan.positiveGlobalStyles, modify if needed
- const audio = await client.music.compose({
- compositionPlan: plan,
- musicLengthMs: 60000,
+ await saveAudio('public/audio/ambient/rain.mp3', rain);
+
+ const combat = await composeMusic(client, {
+ prompt: 'Intense battle music, driving and urgent, 150 BPM in D minor, electric guitar riffs, pounding drums, brass stabs',
+ musicLengthMs: 60_000,
});
+ await saveAudio('public/audio/music/combat.mp3', combat);
+
+ // Section-level control: inspect or edit the plan, then render it with a seed.
+ const plan = await createMusicPlan(client, 'Epic boss battle, 160 BPM, full orchestra', 90_000);
+ const boss = await composeFromPlan(client, plan, 42);
+ await saveAudio('public/audio/music/boss.mp3', boss);
```
- ### Lyria: Generate a combat track (alternative)
+ ### Lyria 2: combat variations
```typescript
- import { LyriaClient } from './lyria-client';
+ import { createLyriaClient, generateMusic, saveClips } from './lyria-client';
- const lyria = new LyriaClient({
- projectId: process.env.GCP_PROJECT_ID!,
- location: 'us-central1',
- });
+ const target = { projectId: process.env.GCP_PROJECT_ID ?? '', location: 'us-central1' };
+ const lyria = createLyriaClient(target);
- const tracks = await lyria.generate({
+ const clips = await generateMusic(lyria, target, {
prompt: 'Intense battle music, driving and urgent, 150 BPM, electric guitar riffs, pounding drums, brass stabs',
- negativePrompt: 'no vocals, no calm sections, no silence, no sound effects',
- seed: 2001,
- sampleCount: 2,
+ negativePrompt: 'vocals, calm sections, silence',
+ sampleCount: 2, // or `seed`, never both
});
-
- await lyria.saveAll(tracks, 'combat_standard', './output/music/combat');
+ await saveClips(clips, 'combat_standard', './output/music/combat');
```
- ### Audio state machine usage
+ ### Audio state machine
```typescript
import { AudioManager } from './audio-manager';
- import { AUDIO_CONFIG } from './sound-config';
+ import { AUDIO_CONFIG, type GameAudioState } from './sound-config';
- const audio = new AudioManager(AUDIO_CONFIG);
+ const audio = new AudioManager<GameAudioState>(AUDIO_CONFIG);
audio.unlockMobile();
+ audio.preload();
- // Game state changes drive audio automatically
- audio.transition('menu'); // Plays menu theme
- audio.transition('exploration'); // Crossfades to exploration + ambient
- audio.transition('combat'); // Fast crossfade to combat music
- audio.transition('boss'); // Switches to boss theme
- audio.playSfx('sword_clash'); // One-shot SFX on top
- audio.playVoice('npc_greeting'); // Voice line on top
+ audio.transition('menu'); // starts once the player taps, clicks or presses a key
+ audio.transition('exploration'); // crossfade, ambient starts
+ audio.preload(['/audio/music/battle.ogg', '/audio/music/boss.ogg']);
+ audio.transition('combat'); // 500 ms crossfade from the config
+ audio.playSfx('/audio/sfx/sword_clash.mp3');
+ audio.playVoice('/audio/voice/merchant/greeting.mp3'); // ducks the music
```
- ## Cross-References
-
- - **game-backend-architecture**: Server-side audio asset management, CDN delivery
- - **game-design-fundamentals**: Feedback loops -- audio reinforces player actions and emotional beats
-
## Pitfalls
- 1. **Playing audio without user interaction on mobile** -- iOS/Android will silently fail. Always gate behind a tap/click.
- 2. **No crossfade between states** -- Hard cuts between combat and exploration music break immersion. Always crossfade.
- 3. **Single volume slider** -- Players need separate music, SFX, voice, and ambient controls. Provide per-layer sliders.
- 4. **Music API: forgetting 'instrumental only'** -- ElevenLabs Music API may add vocals unless you include `instrumental only` in your prompt. For Lyria, include `no vocals, no sound effects` as a negative prompt.
- 5. **Not preloading combat audio** -- If combat starts and the track is still loading, the player hears silence. Preload combat tracks during exploration.
- 6. **Ignoring audio file size** -- OGG is smaller than MP3 at similar quality. Use OGG primary, MP3 fallback. Compress aggressively for ambient loops.
- 7. **Hardcoding track paths** -- Use a config mapping (state to path). Swapping tracks during iteration becomes trivial.
- 8. **Not saving Lyria seeds** -- Without the seed, you cannot reproduce or refine a track. Always log seeds in a manifest.
-
- ## Designer Philosophy
-
- **Fumito Ueda** (ICO, Shadow of the Colossus): Silence is as powerful as sound. Restraint in audio design creates moments of profound impact. When the music drops out during a key moment, the silence itself becomes the emotional beat. Do not fill every second with audio.
-
- **Jenova Chen** (Journey): Music should mirror the emotional arc. The soundtrack IS the emotional journey. In Journey, the music builds with the player's progress, peaks at moments of connection, and recedes during solitude. Your adaptive music system should do the same -- the audio state machine is the tool that makes this possible.
-
- ## Sources
-
- - [ElevenLabs API Documentation](https://elevenlabs.io/docs)
- - [ElevenLabs Sound Effects API](https://elevenlabs.io/docs/api-reference/sound-generation)
- - [ElevenLabs Music API Documentation](https://elevenlabs.io/docs/eleven-api/guides/cookbooks/music)
- - [ElevenLabs Music Best Practices](https://elevenlabs.io/docs/overview/capabilities/music/best-practices)
- - [Vertex AI Lyria Documentation](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/lyria)
- - [GDC Vault -- Game Audio Talks](https://www.gdcvault.com/)
- - [Web Audio API -- MDN](https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API)
+ 1. Playing before the first user input. Browsers reject `play()` with `NotAllowedError` until the user interacts. `touchend`, `click` and `keydown` count as user activation; `touchstart` does not. `unlockMobile()` listens for the first three and restarts the music that was blocked.
+ 2. Expecting volume control on iOS. iOS Safari ignores `HTMLMediaElement.volume`, so the manager's crossfade, ducking, sliders and mute make no audible change there: during a crossfade both tracks play at full volume until the old one stops. If you move playback to the Web Audio API, note that an `AudioContext` created outside a user gesture starts `suspended`; call `resume()` inside the first click handler.
+ 3. Leaving `model_id` unset. Sound effects and music then use the deprecated `eleven_text_to_sound_v2` and `music_v1`. The boilerplate sets every model id.
+ 4. Getting vocals in ElevenLabs music. Pass `forceInstrumental: true` (the boilerplate default). Lyria 2 is instrumental only; its negative prompt names what to leave out ("vocals"), not "no vocals".
+ 5. Mixing seed modes. ElevenLabs accepts a seed only with a composition plan. Lyria accepts `seed` or `sampleCount`, not both.
+ 6. Naming a band, an artist or copyrighted lyrics in an ElevenLabs music prompt. The API returns `bad_prompt` with a suggested rewrite.
+ 7. Hard cuts between states. Give each transition a crossfade time; fast into danger, slow out of it.
+ 8. One volume slider. Players need separate music, SFX, voice and ambient controls; the manager stores them in `localStorage`.
+ 9. Not preloading combat audio. If combat starts while its track is still loading, the player hears silence. Preload combat and boss tracks during exploration.
+ 10. Hardcoded track paths in game code. Keep the state-to-path map in `sound-config.ts` so swapping a track is one edit.