Aller au contenu
Skillpedia
Programmation générale6.4k · #14197

melonjs-audio

Ce qu’il fait

Ce guide explique comment configurer l'audio dans un jeu melonJS, charger les sons et les jouer correctement. Il s'adresse aux développeurs de jeux qui ajoutent du son à un jeu navigateur.

Quand l’utiliser

  • ✓Quand un développeur veut ajouter des effets sonores ou une musique de fond à un jeu melonJS.
  • ✓Quand un développeur obtient une erreur sur les formats audio lors du chargement des sons.
  • ✓Quand un développeur veut qu'un son s'atténue ou se déplace selon la position d'un objet.

Lien du skill

https://github.com/melonjs/melonJS/blob/master/packages/melonjs/skills/melonjs-audio/SKILL.md

Copiez-le et collez-le dans votre IA (Claude, ChatGPT ou Cursor) en lui demandant de suivre les instructions.

Comment l’utiliser

Le plus simple : copiez le message et collez-le dans votre IA. Elle lit le skill et suit les instructions.

Message prêt à coller

Utilise ce skill pour m’aider : https://github.com/melonjs/melonJS/blob/master/packages/melonjs/skills/melonjs-audio/SKILL.md Lis le fichier SKILL.md de ce lien et suis ses instructions pour ma tâche.
Envie que votre IA trouve seule des skills comme celui-ci ?Installez le MCP gratuit de Skillpedia : une ligne, et elle cherche parmi 15 000+ skills avant chaque tâche.Installer en 1 minute →

Exemple de demande à votre IA

“Ajoutez un son de saut et une musique de fond en boucle à mon jeu melonJS.”

5 nouveaux skills par semaine. 1 minute de lecture.

Comment ça marche

Le skill demande à l'IA de définir d'abord les formats audio, puis de précharger un dossier de sons, et d'utiliser des appels séparés pour les effets sonores et les pistes de fond.

Contenu technique (SKILL.md original)

Texte original de l’auteur, en anglais, directement depuis GitHub.

Audio

Two setup rules

import { audio, loader } from "melonjs";

audio.init("mp3,ogg");                      // 1. BEFORE preloading any audio

await loader.preload([
    { name: "cling", type: "audio", src: "data/sfx/" },   // 2. a PREFIX, not a file
]);
  1. audio.init(format) must run before any audio asset is preloaded, and lists the formats you actually ship. Preloading first throws target audio extension(s) should be set through me.audio.init() before calling the preloader. It returns false when no audio backend is available, so it is worth checking. The format list defaults to "mp3".
  2. src is a prefix, not a file. The loader appends the asset name plus each configured extension and uses the first that loads — so data/sfx/ + cling + mp3 → data/sfx/cling.mp3. Passing a full filename gives you a 404. A data:audio/... URL is the one exception: it is used verbatim, prefix and extension skipped.

audio.hasAudio() says whether the browser can play audio at all, and audio.hasFormat("ogg") whether it can play one codec — useful for choosing the init list or hiding a sound toggle on a device with no audio.

Order matters — melonJS tries the listed formats left to right, so put the preferred one first. Two formats ("webm,mp3" or "mp3,ogg") is the usual belt-and-braces for codec coverage. Accepted tokens: mp3, mpeg, opus, ogg, oga, wav, aac, caf, m4a, m4b, mp4, weba, webm, dolby, flac.

Effects versus music

audio.play("cling");                    // fire and forget
audio.play("cling", false, null, 0.5);  // loop, onend, volume
const id = audio.play("engine", true);  // looping; keep the id to stop it

audio.playTrack("theme");               // background music
audio.stopTrack();

Use playTrack for music, not play. playTrack(name, volume?) always loops, and it records the name as the current track — which is what app.pauseOnBlur / resumeOnFocus / stopOnBlur act on, via state.pause(true) → pauseTrack(). stopTrack(), pauseTrack(), resumeTrack() and getCurrentTrack() all read that same single slot, so there is only ever one current track name.

playTrack stops the track it replaces (20.9.0 and later; before that it only assigned the slot, and the previous bed kept looping underneath where stopTrack() could no longer reach it). So a scene just states its own music and nothing cancels anything:

class PlayScreen extends Stage {
    onResetEvent() { audio.playTrack("battle", 0.6); }
}

Calling it with the track already playing restarts it, the same as play() on any other clip. A scene that wants the bed to carry on across a screen change should not call it again, rather than rely on it doing nothing.

stopTrack() is for where nothing follows: a scene whose successor has no music of its own, or a game going quiet. state.change destroys the outgoing stage before it resets the incoming one, so a stopTrack() in onDestroyEvent and a playTrack() in the next onResetEvent are in that order and never cancel each other.

To end a track on an event rather than on a screen change, say a run ending while the player stays on the same screen, audio.fade(name, from, 0, ms) takes it down gently. A fade to zero is silence, not a stop, so the voice is still live until something stops it or replaces it.

Every per-clip function throws audio clip <name> does not exist if the clip was never loaded, and play additionally throws when a named sprite region is missing.

Audio sprites

One file carrying many effects, with named regions in milliseconds:

await loader.preload([{
    name: "sfx", type: "audio", src: "data/sfx/",
    sprite: { jump: [0, 450], hit: [2000, 250], music: [4000, 12000, true] },
}]);

audio.play("sfx", { sprite: "jump" });

A loop with no gap

An MP3 encoder pads the end of its file. Chrome and Firefox trim the padding when they decode it, Safari keeps it, so a looping MP3 has a short silence at every loop there (27 ms on a 12 s clip at 22 kHz, measured). Declare a region of the loop's exact length and loop on that: the voice never reaches the padding.

await loader.preload([{
    name: "ambience", type: "audio", src: "data/sfx/",
    sprite: { loop: [0, 12000] },
}]);
audio.playTrack("ambience", { sprite: "loop", volume: 0.6 });
// or, as a plain clip: audio.play("ambience", { sprite: "loop", loop: true })
Questions fréquentes

Pourquoi le chargement audio renvoie-t-il une erreur ?

Le skill indique que les formats audio doivent être définis avant de précharger le moindre son.

La source du son est-elle un fichier ou un dossier ?

C'est le chemin d'un dossier de préfixes, et le chargeur ajoute le nom et l'extension.

Peut-il vérifier que l'audio fonctionne sur un appareil ?

Oui. Il mentionne des fonctions qui indiquent si l'audio est disponible et quels codecs sont pris en charge.

Détails

Description originale de l’auteur

Use this skill for sound and music in melonJS — loading audio, playing effects, background tracks, audio sprites, volume and muting, spatial audio, procedural tone/noise generation, and effects such as reverb or a compressor on the whole mix. Covers the mandatory audio.init format list, the directory-not-file src convention, playTrack versus play, the fixed listener and pixel-scale distances of positional sound, and browser autoplay unlocking. Triggers on: audio, sound, audio.init, audio.play, playTrack, stopTrack, audio.load, sfx, music, volume, mute, fade, rate, pitch, sprite audio, stereo,

repo: melonjs/melonJS

Popularité

Étoiles GitHub
6.4k
Position au classement
#14197
Licence
MIT
Mis à jour
02/11/2026

Ce skill vous est-il utile ?

0

Connectez-vous pour voter.

Commentaires

  • …

Autres skills de ce dépôt

Skills similaires