This resume is also available in English.

Bonus5 / 5 · All columns

Columns › Bonus › Part 69

Bonus: Game Music and Sound Effects with Claude Code and the Suno MCP Server

番外:用 Claude Code 接 Suno MCP,替網頁小遊戲做配樂與音效

Using Claude Code with Suno's official MCP server to score a small browser game: writing the sound list first, connecting the Suno MCP server and generating calm and battle music, comparing Suno Sounds, code synthesis and CC0 libraries for short effects, then trimming, seamless looping, loudness normalisation and compression with ffmpeg, wiring it all in with Web Audio, and keeping track of rights.

  • Claude Code
  • MCP
  • Suno
  • Web Audio
  • ffmpeg
In this article
  1. What this article solves
  2. Step 1: Division of labour: what Claude Code does and what Suno does
  3. Step 2: Write a sound list first
  4. Step 3: Connect the Suno MCP server to Claude Code
  5. Step 4: Generate music through MCP
  6. Step 5: Short effects: choosing among three sources
  7. Step 6: Post-processing with ffmpeg
  8. Step 7: Wire it into the page
  9. Step 8: Rights and commercial use
  10. Step 9: Turn the workflow into a Claude Code skill
  11. Common pitfalls
  12. Key takeaways
  13. References
  14. Series wrap-up

The previous article, “Bonus: SEO, AEO, GEO and AIO: Getting Found by Search Engines and AI”, was about getting finished work found by people and AI. This is the last bonus article in the series, and it takes on a lighter topic that still comes up in real projects: a small browser game works but has no sound. How do you have Claude Code plan the audio, generate the music through Suno's official MCP server, turn the files into something a web page can use, and wire them into the code? The point is not that AI can compose; it is treating sound as one more kind of project asset, with a spec, a processing pipeline, a record of where it came from, and a way into the code.

What this article solves

Say you have a small game written with HTML5 canvas: the player wanders a calm map collecting coins, sometimes meets an enemy, fights a short battle and clears the level by winning. The game is playable but completely silent. You need:

  • Background music (calm): plays while exploring the map; quiet, unobtrusive, able to loop forever.
  • Battle music (battle): switches in when a fight starts, faster, and switches back when the fight ends.
  • Short sound effects: a button press (click), picking up a coin (coin), taking damage (hit) and clearing the level (win).

As soon as you start, the questions arrive one after another:

  • An AI-generated song has an intro, an outro and a fade-out; set it to loop as it is and every pass “stops” for a moment when it jumps back to the start.
  • Every clip is at a different volume, so players keep reaching for the volume control.
  • The files come out as WAVs of several megabytes and take ages to load on a phone.
  • Browsers do not let a page start making sound by itself the moment it opens.
  • Can AI-generated music go into a game that charges money or shows ads?

This article works through it step by step:

  1. Division of labour: what goes to Claude Code and what goes to Suno.
  2. Writing the sounds the game needs as a list kept in the repository.
  3. Connecting Suno's official MCP server to Claude Code.
  4. Generating music from Claude Code through MCP, and the fallback when MCP is not available.
  5. Three sources for short effects: Suno Sounds, synthesis in code, and CC0 sound libraries.
  6. Post-processing with ffmpeg: trimming, seamless loops, loudness, compression.
  7. Wiring it into the page: autoplay rules, volume, mute, pausing in the background.
  8. Rights and commercial use, and a source record for every file.
  9. Turning the workflow into a Claude Code skill so it can be repeated.

To be clear about scope: this article uses only the MCP server Suno itself provides and the Suno website. Suno currently has no public, self-service developer REST API (it has been reported to be trialling one by invitation; check Suno's own announcements for details). The many third-party services sold as a “Suno API” reach Suno by unofficial means; Suno's terms of service forbid accessing the service by means it does not provide, as well as robots and scraping, so they are not covered here. Suno MCP was also still in beta at the time of writing, so features and names may change; the official documentation is authoritative.

Step 1: Division of labour: what Claude Code does and what Suno does

Broken down, the part that actually “makes sound” is small; the rest is ordinary engineering work, which is exactly what Claude Code is good at.

Claude Code Plan the list: audio/brief.md Write style prompts, instrumental Call Suno tools through MCP ffmpeg: trim, loop, loudness, encode Write playback code (Web Audio) Record sources: audio/sources.json Suno Generate music, effects from the prompt Suno library every song is saved MCP: prompt results, links You: review the list, approve every generation, listen and pick a version

Figure: Claude Code plans the sound list, writes style prompts, calls the Suno MCP server, post-processes with ffmpeg, writes the playback code and records sources; Suno only generates music and effects from the prompts, and the results are stored in the Suno library.

TaskWho does itWhy
Work out from the game design which sounds are needed, how long, whether they loopClaude Code (you review)It can read the code and design notes and knows which events need sound
Write the musical style prompt, ask for instrumentalClaude CodeA prompt is text: it can live in the repository and be revised
Generate music and effectsSuno (through MCP or the website)Only Suno's models can do this part
Pick a versionYouOnly a person can judge whether it sounds good and fits the game
Trim, loop, loudness, encodingClaude Code running ffmpegEvery step is a repeatable command with a measurable result
Playback code, mute, volume settingsClaude CodeOrdinary front-end code
Source and licence recordClaude Code writes, you checkSo that “where did this track come from?” has an answer later

Where it fits: small games, prototypes and campaign pages that need a few loopable background tracks and a handful of effects. Why split it like this: generation is a small part; the rest becomes commands and code, so swapping in a new track later means running them again. When not to use it: a score that must follow the story closely, interactive music that changes with game state (stems, dynamic mixing), or a brand that needs a fixed sonic identity. Those still belong with a composer or sound designer; AI material is at best a draft for discussion.

The whole pipeline looks like this; each of the following steps handles one part of it.

List brief.md Generate Suno / CC0 Originals audio/raw/ Trim silence Loop bars + fade Loudness loudnorm Encode Opus + AAC Play Web Audio 1 Plan 2 Generate 3 Post-process (ffmpeg) 4 Page audio/sources.json: source, prompt, date, plan and edits for every file Originals are never edited; processing writes elsewhere so it can always be rerun

Figure: write the list, generate material and keep it as originals, then trim, cut loops, even out loudness, encode in two formats, and finally load the files from the playback code; every file goes into the source record.

Step 2: Write a sound list first

Before generating anything, have Claude Code read the game's code and design and produce a sound list, saved as audio/brief.md in the repository. For example, tell Claude Code:

Read the game code in src/ and find every event that needs a sound (start, coin pickup, damage, entering and leaving a fight, level cleared).
Write audio/brief.md: one row per sound, with columns id, purpose, length, loop, style, source and output format.
All music is instrumental; the total audio budget is under 1 MB. Do not generate any sound yet.

The list comes out roughly like this:

# Game audio brief

Game: a small HTML5 canvas game. Collect coins on a calm map; enemies sometimes start a short fight.
Target: desktop and phone browsers. Total audio budget: under 1 MB.

| id     | purpose              | length    | loop | mood / style                                | source             | output                |
| ------ | -------------------- | --------- | ---- | ------------------------------------------- | ------------------ | --------------------- |
| calm   | map background music | 24 s loop | yes  | calm, light, 120 BPM, instrumental          | Suno (MCP)         | webm + m4a, 96k       |
| battle | fight music          | 16 s loop | yes  | tense, driving drums, 150 BPM, instrumental | Suno (MCP)         | webm + m4a, 96k       |
| click  | button press         | < 0.1 s   | no   | soft, short, not tiring after 100 presses   | code (Web Audio)   | none (synthesised)    |
| coin   | picking up a coin    | < 0.6 s   | no   | bright, rising, two notes                   | Suno Sounds or CC0 | webm + m4a, 64k, mono |
| hit    | player takes damage  | < 0.4 s   | no   | dull thump, clearly different from coin     | CC0 library        | webm + m4a, 64k, mono |
| win    | level cleared        | 1.5–2 s   | no   | short fanfare, same key as calm             | Suno Sounds        | webm + m4a, 64k, mono |

Rules: no vocals in music; music at -16 LUFS integrated; effects mixed by ear against the music in the game.

Why write a list first instead of asking the AI to “make some game music”:

  • It can be reviewed. The list is a file under version control alongside the code. Anyone can see in a pull request that “battle music is 150 BPM, a 16-second loop”, and disagreements change the file rather than going back and forth in a chat.
  • Agree before spending credits. Every generation in Suno costs credits (see step 3). Fixing length, tempo and “no vocals” up front saves a few wasted attempts.
  • The numbers post-processing needs live here. BPM sets the bar length, the bar length sets where to cut the loop (step 6), and loop length plus bitrate set the file size.
  • Decide the source column early. Not every sound suits Suno. A click synthesised in code is smaller and more consistent; a hit sound from a CC0 library is quicker. Step 5 compares them.

When to skip it: for a prototype you will throw away today, one ready-made CC0 track is enough and no list is needed. If the sound will stay in the project longer than a week, the list is worth writing.

Step 3: Connect the Suno MCP server to Claude Code

MCP (Model Context Protocol) gives AI tools such as Claude Code a standard way to call tools provided by outside services. Suno announced the official Suno MCP (beta) in its release notes on 28 October 2026. The server URL is https://api.suno.com/mcp, and the official guide lists Claude, ChatGPT, Claude Code, Cursor and Gemini among the clients that can connect. Three things matter:

  • No API key. You connect by signing in with your Suno account and approving access. It is OAuth, so Claude Code never sees your password.
  • The same credits. Songs generated through MCP use your current plan's credits, just like songs made on suno.com; Suno also says you can ask the AI how many credits you have left.
  • Results land in the Suno library. Every song you make is saved to your Suno library.

On who can use it: Suno's release notes call it a beta and link to an early-access sign-up, while the help article “What is Suno MCP?” says it is available on all plans, with some features requiring a paid subscription. The two do not fully agree, so whether it works for you depends on your account once you sign in and on Suno's latest documentation.

Add the server

In a terminal in the project directory, run:

claude mcp add --transport http suno https://api.suno.com/mcp

--transport http says this is a remote HTTP server, and suno is the name you give it inside Claude Code; its tools then have full names of the form mcp__suno__<tool>.

Illustration Terminal 1 $ claude mcp add --transport http suno https://api.suno.com/mcp server added (local scope by default) 2 $ claude mcp list suno: https://api.suno.com/mcp (HTTP), not yet authenticated 3 > /mcp suno · needs authentication → select it to sign in

Figure: Illustration. ① Run claude mcp add in the terminal; ② confirm with claude mcp list that the server has been added; ③ type /mcp inside Claude Code and see that suno still needs a sign-in.

Claude Code has three scopes for MCP configuration, chosen with --scope:

ScopeCommandWhere it is storedFits
local (default)no --scope~/.claude.json, this project onlyOnly you use it, in this project
project--scope project.mcp.json at the project root, can be committedEveryone on the team needs the same server
user--scope user~/.claude.json, all your projectsYou use Suno across many projects

Prefer local or user; do not rush to project. .mcp.json puts the server in front of everyone's Claude Code on the team (each person is asked to approve it before first use), but Suno credits and results belong to a personal account: everyone has to sign in with their own account and spend their own credits. If the team really does want to share it, put it in .mcp.json and say clearly in the README that “this spends your own Suno credits”.

Sign in

Once the server is added, type /mcp in a Claude Code session, choose suno, and follow the prompts to sign in to Suno in the browser and approve access. Claude Code stores the token and refreshes it automatically; to revoke access, choose the option to clear authentication in the same /mcp menu.

Illustration /mcp suno needs authentication Enter: sign in 1 Browser Suno Claude Code requests access to your Suno account Approve 2 /mcp suno · connected View tools mcp__suno__… Clear authentication 3

Figure: Illustration. ① Choose suno in the /mcp menu; ② the browser opens Suno's sign-in and authorisation page, and you approve; ③ back in Claude Code, suno shows as connected and you can view the tools it provides.

Check the connection and control spending

claude mcp list          # list all servers and their connection status
claude mcp get suno      # show suno's configuration
claude mcp remove suno   # remove it when no longer needed

Choosing suno in /mcp shows the tools it provides and their full names. Suno's documentation lists what it can do: create songs from a text description (the AI can help write lyrics and styles), turn uploaded audio into songs, covers, extensions and mashups, split stems, generate sound effects and loops with Sounds, browse the library, and check your plan and credits. Suno has not published the name and parameters of each tool, so this article does not hard-code tool names; go by what /mcp actually lists once you are connected.

Because every generation spends credits, add an ask rule to the project's .claude/settings.json so that Claude Code asks you before every call to a Suno tool:

{
	"permissions": {
		"ask": ["mcp__suno"]
	}
}

mcp__suno matches every tool of the suno server. Do not move it to allow for convenience: once allowed, Claude Code may generate several times in a long task just to “try another version”.

Step 4: Generate music through MCP

Once connected, generating music is a plain-language request in Claude Code. The key is to give it the list and to be explicit about how many versions and how many credits:

Following the calm row of audio/brief.md, generate the background music with Suno.
Requirements: instrumental, no vocals, 120 BPM, calm and light, suitable for looping, soft synth pads and plucked bass.
Show me the style prompt you will send first; once I agree, generate exactly once.
Afterwards list each version's title, length and Suno link. Do not pick one yourself.
Read list calm Write prompt instrumental, 120 You approve ask rule Suno MCP spends credits Suno library the versions You listen not the AI Download original audio/raw/ Post-process step 6 None fits: revise the prompt and generate again (more credits)

Figure: Claude Code writes the style prompt from the list and calls the Suno MCP server only after you approve; the versions Suno generates are saved to the library; you listen, pick one and download the original to audio/raw/ before post-processing starts.

Points for writing the prompt:

  • Say instrumental explicitly. Game background music almost never wants vocals, which compete with the on-screen text. Write both instrumental and no vocals in the prompt; if the tools listed in /mcp have an instrumental-style parameter, have Claude Code set it as well.
  • State BPM and time signature. Loops are cut at bar lines in post-processing, and you need the BPM to work out a bar's length. The actual tempo may not exactly match what you wrote, so check it again before post-processing.
  • Describe mood and instruments, not “like the music from game X”. Naming specific works or artists gives unstable results and invites rights problems.
  • Generate once, listen several times. One generation usually returns more than one version (the Sounds guide says two samples; how many songs come back through MCP is whatever the response shows). Listen to all of them before deciding to try again; that costs fewer credits than regenerating over and over.
  • Make the two tracks match. calm and battle switch back and forth, so ask for the same key or similar instruments; the switch will be less jarring.
Illustration Claude Code 1 > Generate calm from audio/brief.md; show me the prompt first 2 Style prompt: calm, light, 120 BPM, soft synth pads, plucked bass, instrumental, no vocals, loopable. Send it? 3 Allow mcp__suno__…? (spends Suno credits) 1. Allow once 2. Deny 4 Done, saved to your Suno library: Version 1 2:41 suno.com/song/… Version 2 2:58 suno.com/song/… Listen and tell me which one to use.

Figure: Illustration. ① You ask Claude Code to generate calm from the list; ② it shows the style prompt and waits for your agreement; ③ before calling Suno's tool, Claude Code asks for confirmation because of the ask rule; ④ it reports each version's length and link so you can listen and choose.

How the file reaches your disk

This part needs the most care. Suno's documentation confirms that “every song is saved to your Suno library”, but it does not say whether the MCP tools return a downloadable audio link. In practice there are two cases:

  • A tool returns an audio link. Have Claude Code save it with curl -L -o audio/raw/calm-v2.mp3 '<link>', and note the song's Suno link in the source record.
  • No link is returned. Find the song in your library on suno.com, download it from the website, and put it in audio/raw/.

Either way, downloads are limited by your plan: Suno's documentation says paid plans have a monthly download limit, the rules for downloads on the free plan changed in September 2026 and its pages do not fully agree with one another, and the formats (MP3 or WAV) also depend on the plan, so check the official documentation. If you have the choice, download WAV and compress it yourself; that sounds better than re-encoding an MP3.

Files in audio/raw/ are never edited in place; all processing writes to other folders. That way you can rerun from the originals whenever you adjust a loop point or the loudness.

Without MCP: use the Suno website

MCP is still in beta, and your account may not have it yet. The pipeline barely changes; only steps 3 and 4 become manual: have Claude Code write the style prompt from the list, paste it into the create page on suno.com, generate, listen, download into audio/raw/, and hand back to Claude Code for post-processing. Fits: when you need only one or two tracks, or want to fine-tune on the website yourself. Drawback: you have to keep track of which prompt produced which result, and fill in the source record by hand.

Step 5: Short effects: choosing among three sources

Generating a whole song is overkill for sounds under a second, such as a button press or a coin. There are three common sources:

Suno Sounds Text → two samples One Shot or Loop Optional BPM, key Fits: level clear, level up, coin Here: win, coin Synthesis in code Web Audio oscillator No file to download Pitch can change live Fits: clicks, beeps, simple sweeps Here: click CC0 library Ready-made recordings Clear licence Record the source URL Fits: damage, footsteps, doors Here: hit

Figure: Suno Sounds generates a single effect or a loop from text; synthesis in code generates the sound in the browser with Web Audio, with no file at all; a CC0 library provides ready-made effects that can be used freely. They can be mixed.

SourceFitsWhyWhen not to use it
Suno SoundsShort musical phrases: level cleared, level up, a two-note coinYou can describe the style and set the key, so it matches the musicLarge numbers of very short, clean interface sounds; each must be picked by hand, and downloads are limited by plan
Synthesis in code (Web Audio)Clicks, notification beeps, simple sweepsNo file to download, pitch and length can change at run time, no licensingSounds that need realistic texture (impacts, explosions, footsteps)
CC0 sound libraryDamage, footsteps, doors and other realistic effectsFast, consistent quality, clear licenceSounds that must share the key or style of the music

Suno marks Sounds as an experimental (beta) feature. On the website's create page you choose the Sounds mode, describe the sound in text, optionally choose One Shot (a single short sound) or Loop (a repeating clip), and optionally set a BPM and key; each request returns two samples. The guide warns that Loop may produce a full musical arrangement, so One Shot is usually better for pure effects. It gives no length limit; if you want something shorter or longer, put the duration in the description. Separately, “What is Suno MCP?” lists generating sound effects and loops with Sounds among the things you can do through MCP, so you can also ask for them from Claude Code; the parameters are whatever /mcp actually lists.

A synthesised click takes a dozen lines:

// synth.js: a button click made in code, so there is no file to download
export function click(ctx, out, when = ctx.currentTime) {
	const osc = ctx.createOscillator();
	const gain = ctx.createGain();
	osc.type = 'triangle';
	osc.frequency.setValueAtTime(1200, when);
	osc.frequency.exponentialRampToValueAtTime(600, when + 0.05);
	gain.gain.setValueAtTime(0.0001, when); // exponential ramps cannot start from 0
	gain.gain.exponentialRampToValueAtTime(0.3, when + 0.005);
	gain.gain.exponentialRampToValueAtTime(0.0001, when + 0.06);
	osc.connect(gain).connect(out);
	osc.start(when);
	osc.stop(when + 0.07);
}

It uses a triangle wave that falls from 1200 Hz to 600 Hz within 50 milliseconds, while the volume rises within 5 milliseconds and dies away within 60. The volume follows an exponential curve, and an exponential curve cannot start at 0, so the starting value is a tiny 0.0001. A hundred presses will not grate, and it adds nothing to the download.

When you use CC0 effects, record each file's source URL and licence (the source record in step 8) rather than relying on memory.

Step 6: Post-processing with ffmpeg

Once you have the originals, have Claude Code process them with ffmpeg according to the list. Each step is one command that can be rerun and measured. All the commands below were run locally on test audio generated by ffmpeg itself: a “fake AI song” with 1.5 seconds of silence, 32 seconds of music at 120 BPM, a 4-second fade-out and another second of silence.

Original raw/calm.wav 38.5 s 1 Trim silenceremove 35.9 s 2 Loop atrim + amix 24.0 s 3 Loudness loudnorm ×2 -16.1 LUFS 4 Encode Opus / AAC 238 / 389 KB Test audio: 1.5 s silence + 32 s at 120 BPM + 4 s fade-out + 1 s silence (made with ffmpeg) The processed WAV is about 4.6 MB

Figure: strip the silence from both ends of the original, cut a loop on bar lines with a crossfade, even out loudness with two loudnorm passes, then encode to Opus (WebM) and AAC (M4A).

Trim the silence at both ends

# Cut silence below -50 dB from both ends (areverse lets the same filter handle the end).
ffmpeg -i raw/calm.wav -af "silenceremove=start_periods=1:start_threshold=-50dB,\
areverse,silenceremove=start_periods=1:start_threshold=-50dB,areverse" work/calm.trim.wav

silenceremove with start_periods=1 removes one stretch of silence at the start. Reversing the audio (areverse) and doing it again removes the silence at the end, and a final reverse puts it back the right way round. The test file went from 38.5 seconds to about 35.9: the leading 1.5 seconds of silence are gone, as are the trailing silence and the part of the fade-out below -50 dB.

Why an AI-generated song cannot loop as it is

One AI-generated song Intro Body (bars 1…16) Outro Fade ✕ Loop the whole song Fade-out jumps back to the intro: it sounds like stopping and restarting ✕ Body only, but cut mid-bar 2.13 s → 26.37 s beat slips + a click at the seam ✓ Right: whole bars from the body, crossfaded at the seam (next figure)

Figure: a complete song has an intro, a body, an outro and a fade-out. Looped as it is, the fade-out jumps back to the intro and sounds like the music stopping and starting again; taking only the body but cutting off the bar line breaks the beat at the seam, and a discontinuous waveform at the cut adds an audible click.

Suno generates “a song”: it has an intro, develops, ends, and often fades out. That is good for listening and a problem for game background music:

  • Fade-out and intro. At the end of each pass the volume drops and the intro starts again; the player clearly hears “one round is over”.
  • Cut points off the bar line. The beat gains or loses half a beat at the seam, which the ear notices easily.
  • A discontinuous waveform at the seam. If the last sample and the first differ a lot, you hear a short click.

So two things are needed: take a whole number of bars from the body, and crossfade briefly at the seam.

Cut the loop on bar lines and crossfade

# 120 BPM in 4/4: one bar = 4 * 60 / 120 = 2 s.
# Keep bars 2..13 (A = 2 s to B = 26 s, length L = 24 s) plus X = 0.5 s past B,
# and crossfade that extra tail into the head so the end flows into the start.
A=2 X=0.5 L=24 END=26.5   # END = B + X
ffmpeg -i work/calm.trim.wav -filter_complex "
[0:a]atrim=start=$A:end=$END,asetpts=PTS-STARTPTS,asplit=3[a][b][c];
[a]atrim=end=$X,asetpts=PTS-STARTPTS,afade=t=in:d=$X:curve=qsin[head];
[b]atrim=start=$X:end=$L,asetpts=PTS-STARTPTS[mid];
[c]atrim=start=$L,asetpts=PTS-STARTPTS,afade=t=out:d=$X:curve=qsin[tail];
[tail][head]amix=inputs=2:normalize=0[join];
[join][mid]concat=n=2:v=0:a=1[out]" -map "[out]" work/calm.loop.wav
Original (trimmed) head mid tail A = 2 s B = 26 s B + X L = B − A = 12 bars = 24 s The output loop file tail ↘ head ↗ mid length = L X = 0.5 s, qsin curve End wraps to start: what followed B (tail) belongs here, fading into what follows A (head) Measured locally: seam jump 0.006; a careless cut with no fade gives 0.453

Figure: A to B is exactly 12 bars, and X extra seconds after B are taken too. That extra tail fades out while the first X seconds fade in, and the two are mixed together at the very start of the file. When the loop wraps from the end (B) to the start, you hear exactly what originally followed B, which then gradually gives way to what follows A.

The arithmetic: at 120 BPM in 4/4, a beat is 0.5 seconds and a bar is 2 seconds. Both A and B must sit on bar lines (ideally at the start of a phrase), and the length L = B - A is a whole number of bars. asplit=3 splits the same audio into three: the first X seconds (head, faded in), the middle (mid), and the X seconds after B (tail, faded out). Tail and head are mixed with amix (normalize=0 stops it from lowering the volume), followed by mid. The output is exactly L long, and when the end wraps to the start you hear the continuation that originally followed B.

curve=qsin is a quarter sine; fading in and out with the same curve keeps the level more even through the crossover than a straight line. X does not need to be long: 0.2 to 0.5 seconds is enough; longer leaves two different harmonies overlapping for too long.

How do you find the real A and B? An AI-generated song does not necessarily start on the first beat at 0 seconds, and its tempo may not be exactly the number you asked for. Ask Claude Code to cut candidate sections with ffmpeg for you to audition, or to write a small tool in the project that estimates the BPM; in the end, you confirm by listening.

The local check: a small script compared the jump from the loop file's last sample to its first. With the crossfade the jump is 0.006, smaller than the largest step between neighbouring samples inside the file (0.027), so the seam is inaudible. The same music cut carelessly from 2.13 to 26.37 seconds with no crossfade jumps by 0.453: a clear click.

Even out the loudness

Different versions and sources can differ a lot in volume. loudnorm (loudness measured according to EBU R128) does it in two passes: the first only measures, the second feeds the measured numbers back for a linear adjustment.

# Pass 1: measure only (-f null writes nothing) and print the numbers as JSON.
ffmpeg -i work/calm.loop.wav -af loudnorm=I=-16:TP=-1.5:LRA=11:print_format=json -f null -

The last part of the output is JSON (excerpt):

{
	"input_i": "-15.14",
	"input_tp": "-6.99",
	"input_lra": "0.00",
	"input_thresh": "-25.14"
}
# Pass 2: feed the measured values back; -ar 48000 because loudnorm may upsample.
ffmpeg -i work/calm.loop.wav -af "loudnorm=I=-16:TP=-1.5:LRA=11:\
measured_I=-15.14:measured_TP=-6.99:measured_LRA=0.00:measured_thresh=-25.14:linear=true" \
  -ar 48000 work/calm.norm.wav
  • I=-16 is the integrated loudness target (LUFS). loudnorm defaults to -24, a broadcast-oriented value; games on the web and on phones often use something louder, around -16. That is not a standard, just a starting point you can adjust for your game, but all music in one game should use the same target.
  • TP=-1.5 caps the true peak, leaving headroom for the lossy encoding that follows so it does not clip.
  • linear=true applies only an overall gain change when it can, leaving the dynamics alone; when it cannot (for example when the target is much louder than the input and the peak would exceed the cap), loudnorm switches to dynamic processing, and the second pass reports which one it used.
  • -ar 48000 is there because loudnorm raises the sample rate internally to measure true peak; without it the output may come out at 192 kHz.

Measured again after processing, the test file's integrated loudness is -16.1 LUFS. Effects are usually too short for integrated loudness to be measured reliably, so they do not suit the same target; set the levels of effects relative to each other and to the music in the game, by ear, with the volume parameter in code.

Encode to two formats

ffmpeg -i work/calm.norm.wav -c:a libopus -b:a 96k public/audio/calm.webm
ffmpeg -i work/calm.norm.wav -c:a aac -b:a 128k -movflags +faststart public/audio/calm.m4a

Why two: Opus gives smaller files at the same quality, but browsers differ in their support for it and for its containers (MDN's data notes Safari's limitations in particular), whereas AAC in an MP4 container is supported by all major browsers. So make both; the playback code tries Opus first and falls back to AAC (step 7). -movflags +faststart moves the MP4 index to the front of the file, so decoding can start after downloading only part of it.

Actual sizes (a 24-second stereo loop):

FileSize
Processed WAV (48 kHz)about 4.6 MB
Opus 96 kbps (.webm)about 238 KB
AAC 128 kbps (.m4a)about 389 KB

Processing the effects

# Short effects: trim, 5 ms fade-in and 20 ms fade-out against clicks, mono, small bitrate.
ffmpeg -i raw/coin.wav -af "silenceremove=start_periods=1:start_threshold=-50dB,\
areverse,silenceremove=start_periods=1:start_threshold=-50dB,\
afade=t=in:d=0.02,areverse,afade=t=in:d=0.005" -ac 1 work/coin.wav
ffmpeg -i work/coin.wav -c:a libopus -b:a 64k public/audio/coin.webm
ffmpeg -i work/coin.wav -c:a aac -b:a 96k public/audio/coin.m4a

Effects also lose the silence at both ends, then get a very short fade-in (5 milliseconds) and fade-out (20 milliseconds) to avoid clicks at the start and end; they are converted to mono and use a lower bitrate. Mind the order: the fade-in applied while reversed becomes the fade-out at the end once reversed back. The test coin sound was trimmed from 1.4 seconds to about 0.59, about 6 KB as Opus and 8 KB as AAC.

Have Claude Code run these commands for each row of the list, then use ffprobe to list every output file's duration and size and compare them with the budget in the list.

Step 7: Wire it into the page

With the files ready, what remains is the playback code. Sound in a browser game runs into a few limits every time:

  • The browser's autoplay policy. MDN explains that media with sound is generally allowed to play only after the user has interacted with the site (a click, tap or key press); otherwise it is likely to be blocked. Chrome's documentation is more specific: an AudioContext created before a user gesture starts in the suspended state, and you must call resume() after the user gesture.
  • Background music must loop seamlessly. The file is already cut for it; playback must not insert a gap at the seam.
  • Music and effects need separate volume controls and a one-tap mute, and the settings must be remembered.
  • Stop when the user switches to another tab. Playing to nobody just wastes battery and annoys people.
calm AudioBufferSourceNode GainNode battle fade in / out GainNode coin / hit / win AudioBufferSourceNode GainNode click OscillatorNode GainNode Music bus user volume 0.6 Effects bus user volume 0.8 Output destination Mute: both buses go to 0; settings are kept in localStorage

Figure: every effect and every piece of music is a source node with its own gain node, feeding into two buses, music and effects; each bus has the volume the user set and connects to the output. Muting sets both buses to 0.

Page load silent Start pressed user gesture Create, resume AudioContext running can play Load effects play calm suspended tab hidden hidden: suspend visible: resume Created before a gesture, an AudioContext is suspended

Figure: nothing is created on page load; when the user presses Start, the AudioContext is created and resume()d inside that click, and only once it is running do the effects load and the music start. Switching tabs calls suspend(), and returning calls resume().

The playback module

// audio.js: background music and sound effects for a small browser game
const FORMATS = [
	['webm', 'audio/webm; codecs="opus"'],
	['m4a', 'audio/mp4; codecs="mp4a.40.2"']
];
const probe = document.createElement('audio');
const exts = FORMATS.filter(([, type]) => probe.canPlayType(type) !== '').map(([ext]) => ext);

const DEFAULTS = { muted: false, music: 0.6, sfx: 0.8 };
const prefs = loadPrefs();
let ctx = null;
let musicBus = null;
let sfxBus = null;
const loading = new Map(); // name -> Promise<AudioBuffer>
const ready = new Map(); // name -> AudioBuffer, for instant playback
let current = null; // { name, src, gain }
let wanted = null;

function loadPrefs() {
	try {
		return { ...DEFAULTS, ...JSON.parse(localStorage.getItem('audio-prefs')) };
	} catch {
		return { ...DEFAULTS };
	}
}

function savePrefs() {
	try {
		localStorage.setItem('audio-prefs', JSON.stringify(prefs));
	} catch {
		// private mode or storage disabled: settings last for this visit only
	}
}

function applyVolumes() {
	if (!ctx) return;
	const t = ctx.currentTime;
	musicBus.gain.setTargetAtTime(prefs.muted ? 0 : prefs.music, t, 0.05);
	sfxBus.gain.setTargetAtTime(prefs.muted ? 0 : prefs.sfx, t, 0.05);
}

// Call from a click or keydown handler: browsers keep audio suspended until a user gesture.
export async function unlock() {
	if (!ctx) {
		ctx = new AudioContext();
		musicBus = ctx.createGain();
		sfxBus = ctx.createGain();
		musicBus.connect(ctx.destination);
		sfxBus.connect(ctx.destination);
		applyVolumes();
	}
	if (ctx.state === 'suspended') await ctx.resume();
}

async function decodeFirst(name) {
	for (const ext of exts) {
		try {
			const res = await fetch(`/audio/${name}.${ext}`);
			if (!res.ok) continue;
			const buf = await ctx.decodeAudioData(await res.arrayBuffer());
			ready.set(name, buf);
			return buf;
		} catch {
			// this format failed to download or decode: try the next one
		}
	}
	throw new Error(`cannot load audio "${name}"`);
}

function load(name) {
	if (!loading.has(name)) {
		loading.set(
			name,
			decodeFirst(name).catch((err) => {
				loading.delete(name); // allow a retry later
				throw err;
			})
		);
	}
	return loading.get(name);
}

export function preload(names) {
	return Promise.all(names.map(load));
}

export function playSfx(name, volume = 1) {
	const buf = ready.get(name);
	if (!buf || !ctx || ctx.state !== 'running') return; // not ready: skip rather than play late
	const src = ctx.createBufferSource();
	const gain = ctx.createGain();
	src.buffer = buf;
	gain.gain.value = volume;
	src.connect(gain).connect(sfxBus);
	src.start();
}

// For sounds made in code: fn(ctx, out) schedules nodes into the effects bus.
export function playSynth(fn) {
	if (ctx?.state === 'running') fn(ctx, sfxBus);
}

export async function playMusic(name, fade = 1) {
	wanted = name;
	if (current?.name === name) return;
	const buf = await load(name);
	if (wanted !== name || current?.name === name) return; // another track was requested meanwhile
	const t = ctx.currentTime;
	const src = ctx.createBufferSource();
	const gain = ctx.createGain();
	src.buffer = buf;
	src.loop = true; // the file itself is cut to loop seamlessly
	gain.gain.setValueAtTime(0, t);
	gain.gain.linearRampToValueAtTime(1, t + fade);
	src.connect(gain).connect(musicBus);
	src.start();
	stopCurrent(fade);
	current = { name, src, gain };
}

function stopCurrent(fade) {
	if (!current) return;
	const t = ctx.currentTime;
	current.gain.gain.cancelScheduledValues(t);
	current.gain.gain.setTargetAtTime(0, t, fade / 4);
	current.src.stop(t + fade);
	current = null;
}

export function stopMusic(fade = 1) {
	wanted = null;
	if (ctx) stopCurrent(fade);
}

export function setMuted(muted) {
	prefs.muted = muted;
	savePrefs();
	applyVolumes();
}

export function setVolume(kind, value) {
	if (kind !== 'music' && kind !== 'sfx') throw new Error(`unknown volume "${kind}"`);
	prefs[kind] = Math.min(1, Math.max(0, value));
	savePrefs();
	applyVolumes();
}

export const settings = () => ({ ...prefs });

document.addEventListener('visibilitychange', () => {
	if (!ctx) return;
	if (document.hidden) ctx.suspend();
	else ctx.resume();
});

A few design choices:

  • Music plays through Web Audio's AudioBufferSourceNode, not <audio loop>. The whole decoded track sits in memory, and with loop = true the loop is sample-accurate, with no gap inserted at the seam. The price is memory: 24 seconds of 48 kHz stereo decodes to about 9 MB (24 × 48000 × 2 channels × 4 bytes). Two tracks are fine, but long music should stream through <audio> instead.
  • Effects are decoded up front and played synchronously. playSfx only plays effects already in ready; one that has not loaded yet is skipped rather than sounding half a second late.
  • Formats are tried in order. canPlayType filters out formats that are clearly unsupported, then each is downloaded and decoded in turn, moving on to the next on failure. canPlayType only answers "probably", "maybe" or an empty string, so the fallback on decode failure is still needed.
  • Switching music crossfades. The new track fades in over fade seconds while the old one fades out and stops. wanted remembers the last track requested: if a fight ends as soon as it starts, two quick playMusic calls leave only the last one playing.
  • Settings live in localStorage, wrapped in try. Reads and writes can fail in private mode or with storage disabled; the settings then last for this visit only and the game carries on.
  • The whole AudioContext is suspended on visibilitychange. It resumes when the tab returns, and the music carries on from where it stopped.

Wiring it into the game

// game.js: wiring the audio module into the game's buttons and events
import { unlock, preload, playMusic, playSfx, playSynth, setMuted, settings } from './audio.js';
import { click } from './synth.js';

const startButton = document.querySelector('#start');
const muteButton = document.querySelector('#mute');

function showMute() {
	const { muted } = settings();
	muteButton.textContent = muted ? 'Sound: off' : 'Sound: on';
	muteButton.setAttribute('aria-pressed', String(muted));
}
showMute();

startButton.addEventListener('click', async () => {
	await unlock(); // inside the click: the browser allows audio from here on
	await preload(['coin', 'hit', 'win']);
	playSynth(click);
	playMusic('calm');
	startGame();
});

muteButton.addEventListener('click', () => {
	playSynth(click);
	setMuted(!settings().muted);
	showMute();
});

// Called by the game loop.
export const onCoin = () => playSfx('coin', 0.7);
export const onHit = () => playSfx('hit');
export const onBattleStart = () => playMusic('battle', 0.5);
export const onBattleEnd = () => playMusic('calm', 1.5);
export const onWin = () => playSfx('win');

function startGame() {
	// the game itself is outside the scope of this example
	window.dispatchEvent(new Event('game-start'));
}
Illustration Coin Quest Start 2 Sound: on 3 (no sound has played yet) 1 What actually happens 1 Page load: no audio created 2 Inside the click: unlock() preload(coin, hit, win) playMusic(calm) 3 setMuted(true) saved to localStorage still off after reload

Figure: Illustration. ① The game opens completely silent, with Start and Sound: on buttons; ② pressing Start unlocks audio within that click, loads the effects and starts the background music; ③ the sound button toggles mute, and the setting is remembered the next time the game opens.

Do not play music on page load. Even where the browser allows it (for example on a site the user visits often), sudden sound is unkind to someone opening the page in an office or on a commute. Make the first sound follow the explicit Start action, and keep the sound button visible on screen. prefers-reduced-motion is a setting about animation, not a sound preference, so do not use it to decide whether to play music; the mute the user pressed themselves, remembered, is the most reliable preference.

This code was run locally in Chrome via Playwright: after clicking Start, the effects loaded and the music started; triggering “enter fight, leave fight, enter fight” in quick succession raised no errors; and after pressing mute and reloading the page, the button still read “Sound: off”.

Step 8: Rights and commercial use

With the technical work done, one question cannot be skipped: can this music go into your game, especially one that charges, has in-app purchases or shows ads? The following summarises what Suno's help centre and terms of service said at the time of writing. Terms change, and the latest official terms are authoritative; for a commercial project read the terms yourself and, if needed, ask a legal professional.

Plan when it was made? Paid plan (Pro, Premier) You own the songs Commercial use allowed Kept after cancelling Download officially for commercial use Free plan Suno owns the songs Personal, non-commercial only Upgrading later does not change it Terms change; the latest official terms apply. Record date and plan for every file

Figure: a song's rights depend on the plan at the time it was made. Songs made on a paid plan (Pro, Premier) are yours and can be used commercially, even after the subscription ends; songs made on the free plan are owned by Suno and are for non-commercial use only, and upgrading later does not make them commercially usable.

  • Paid plans (Pro, Premier). You own songs created while subscribed and can use them commercially, and those rights remain after you cancel. The terms also state that Suno does not warrant that copyright will vest in any output.
  • Free plan. Suno owns the songs; you may use them only for personal, non-commercial purposes in line with the terms of service. Upgrading to a paid plan later does not automatically make songs made on the free plan commercially usable.
  • Downloads. The terms effective September 2026 tie commercial use to a permitted download within your plan's allocation, and trial downloads carry no commercial rights. In other words, files for commercial use should be downloaded officially while you are on a paid plan.
  • Songs made through MCP are the same. Suno's documentation says they use the same credits and go into the same library “the same as songs made on suno.com”; there are no separate rules for rights.

So keep a record for every file: where it came from, which prompt, which date, which plan at the time, and what processing was done. Have Claude Code write it to audio/sources.json after each generation or download:

[
	{
		"file": "public/audio/calm.webm",
		"source": "Suno via MCP",
		"prompt": "calm, light, 120 BPM, soft synth pads and plucked bass, instrumental, loopable",
		"variant": "2 of 2",
		"created": "2026-11-26",
		"plan": "paid plan at time of creation",
		"edited": "trimmed, looped bars 2-13, loudnorm -16 LUFS, Opus 96k / AAC 128k"
	},
	{
		"file": "public/audio/hit.webm",
		"source": "CC0 sound library",
		"url": "https://example.com/sounds/thump-01",
		"licence": "CC0 1.0",
		"created": "2026-11-26",
		"edited": "trimmed, fades, mono, Opus 64k / AAC 96k"
	}
]

This record goes under version control with the code. When someone asks months later “can this track go into the paid version?”, the file answers it, with no need to recall an old chat. Record CC0 effects too: where it was downloaded and what the licence was are easiest to confirm at the moment you download.

Step 9: Turn the workflow into a Claude Code skill

You will certainly do this again: add boss-fight music, replace the coin sound. Write the steps above as a project skill in .claude/skills/game-audio/SKILL.md, and next time type /game-audio to follow the same workflow:

---
name: game-audio
description: Plan, generate and post-process music and sound effects for the game. Use only when the user asks for new game audio.
disable-model-invocation: true
allowed-tools: Bash(ffmpeg *) Bash(ffprobe *)
---

Make or update game audio for: $ARGUMENTS

1. Read audio/brief.md. Add or change rows for the request and show the table before generating anything.
2. Music: write an instrumental prompt (style, BPM, mood, "instrumental", "no vocals") and generate through the
   Suno MCP server. Each generation spends Suno credits: say how many generations you plan and wait for a yes.
3. Short effects: prefer code synthesis or a CC0 library; use Suno Sounds only for musical stingers.
4. Put downloaded originals in audio/raw/ (never edited in place). Process into audio/work/ and public/audio/:
   trim silence, cut music loops at bar lines with a short crossfade, loudnorm two-pass to -16 LUFS for music,
   encode Opus (WebM) and AAC (M4A). Report every file's duration and size with ffprobe.
5. Append an entry per file to audio/sources.json: source, prompt, date, plan, edits.
6. Do not change playback code unless asked; new ids must be added to the preload list in game.js.
  • disable-model-invocation: true: it runs only when you type /game-audio; Claude Code will not start a credit-spending workflow on its own just because “music” comes up in conversation.
  • allowed-tools lists only ffmpeg and ffprobe: post-processing need not ask before every command, but Suno's tools are not listed, so generation is still confirmed through the ask rule from step 3.
  • $ARGUMENTS is replaced with what you type, for example /game-audio add boss-fight music, tenser than battle.

The skill describes only the workflow and its rules; the numbers (loudness target, bitrates, folders) are written into it, so it stays consistent when someone else or another project uses it.

Common pitfalls

Looping a whole AI song as it is. The fade-out, the intro and a cut point off the bar line make every pass stutter. Take a whole number of bars from the body and crossfade briefly at the seam (step 6).

Creating and playing audio on page load. Most of the time the browser blocks it and the AudioContext sits in suspended, often with no error, just silence. Unlock audio inside the user's first click.

Looping an MP3 with <audio loop> and getting a gap at the seam. Lossy formats can carry encoder padding at the start and end of the file, and <audio> looping is not guaranteed to be sample-accurate. For short loops, use a decoded AudioBuffer with loop = true, and listen to the seam in your target browsers.

Shipping only Opus. Some browsers do not support it, so those devices get no sound at all, and developers testing in their own browser never notice. Provide at least one AAC or MP3 fallback.

Every file at a different volume. Players end up adjusting the volume constantly. Normalise all music to the same target with loudnorm; set effect levels against the music in the game.

Letting Claude Code call Suno without confirmation. Every generation spends credits, and a long task can easily produce several extra. Use an ask rule and state in the request how many generations to make.

Editing originals in audio/raw/. Once overwritten, adjusting a loop point or the loudness means generating again and paying again. Keep originals read-only and send all processing to other folders.

Generating on the free plan and shipping it in a commercial game. Rights follow the plan at creation time, and upgrading later does not add them. For commercial use, use a paid plan from the start and keep the source record.

Using third-party “Suno API” services. These are not provided by Suno, and Suno's terms forbid accessing the service by means it does not provide, as well as automated scraping. If you need automation, use the official MCP server.

Hard-coding MCP tool names in documents or scripts. Suno MCP is still in beta, its tools and parameters may change, and Suno has not published a full list. Describe what needs doing in your documents, and go by what /mcp lists for the actual tool.

Key takeaways

  • Claude Code plans, writes prompts, calls tools, post-processes, writes code and keeps records; Suno only generates sound; a person picks the version.
  • Write the sound list first as audio/brief.md in the repository, fixing length, BPM, looping, source and format.
  • The Suno MCP server is at https://api.suno.com/mcp; add it with claude mcp add --transport http suno …, sign in with /mcp; no API key is needed and it uses the same Suno credits. It is in beta, and availability is whatever Suno's documentation currently says.
  • Use an ask rule so every Suno call is confirmed first; go by the tool names /mcp actually lists.
  • Choose short effects from Suno Sounds, code synthesis or a CC0 library depending on the case; they can be mixed.
  • ffmpeg post-processing: strip silence at both ends, cut loops on bar lines with a crossfade, two loudnorm passes for consistent loudness, encode to Opus and AAC.
  • In the page, unlock audio inside the user's first click, loop music from a decoded AudioBuffer, keep music and effect volumes separate, remember mute, and pause in the background.
  • Commercial use depends on the plan at creation time and on how the file was downloaded; record every file in audio/sources.json.

References

Series wrap-up

This series started from an online shop's order service and went all the way to a microservice system that can go live and be operated:

Each part builds on the one before: without solid Go fundamentals, services will not be stable; without a clear single service, splitting only amplifies the chaos; without reliability design, a distributed system breaks when failures happen; without observability and deployment capability, you cannot see problems when they happen, let alone fix them. I hope this series can serve as a map that shows you where to go next in your own projects.