Sound in TCJSgame

Audio is an important part of any game, adding atmosphere, feedback, and immersion. TCJSgame v3 includes a simple Sound class that wraps the HTML5 <audio> element, allowing you to play and stop sounds with ease. Each sound is loaded once and can be reused multiple times during gameplay.

To use sounds, create a new Sound object by passing the file path (e.g., "jump.mp3") to the constructor. The play() method starts the sound, while stop() pauses it. Since the sound element is hidden, it will not appear on the page, but it is still fully functional.

Example: Playing a Sound


// Load a jump sound
let jumpSound = new Sound("jump.mp3");

// Play the sound when space is pressed
function update() {
  if (display.keys[32]) { // Space bar
    jumpSound.play();
  }
}
    

Example: Stopping a Sound


// Background music
let music = new Sound("background.mp3");

// Start music
music.play();

// Stop music after 10 seconds
setTimeout(() => {
  music.stop();
}, 10000);
    

Because the Sound class uses HTML5 audio, you can play MP3, WAV, OGG, and other supported formats. You can also load multiple instances of sounds for different effects, such as footsteps, explosions, or background music.

Note: Some browsers block audio from autoplaying until the player interacts with the page (such as pressing a key or clicking). If your sounds do not play immediately, try starting them after a user action. Also, keep in mind that long audio files may take a moment to load before playing.