This content originally appeared on DEV Community and was authored by Kehinde Owolabi
TCJSGame Sound Class: Complete Reference Guide
Introduction to the Sound Class
TCJSGame provides a simple yet powerful Sound
class for handling audio in your games. This class wraps the HTML5 Audio API to provide easy sound effects and music playback without complex audio setup.
Basic Sound Usage
Creating Sound Instances
// Create sound effects
const jumpSound = new Sound("sounds/jump.mp3");
const coinSound = new Sound("sounds/coin.wav");
const explosionSound = new Sound("sounds/explosion.ogg");
// Create background music
const backgroundMusic = new Sound("music/level1.mp3");
// Example: Preloading important sounds
const sounds = {
jump: new Sound("sounds/jump.mp3"),
hurt: new Sound("sounds/hurt.mp3"),
victory: new Sound("sounds/victory.mp3"),
gameOver: new Sound("sounds/gameover.mp3")
};
Playing Sounds
// Basic sound playback
jumpSound.play();
coinSound.play();
explosionSound.play();
// Example: Player jump sound
function handleJump() {
if (display.keys[32] && player.gravitySpeed === 0) { // Spacebar
player.speedY = -12;
sounds.jump.play(); // Play jump sound
}
}
// Example: Coin collection
function collectCoin(coin) {
score += 10;
sounds.coin.play();
coin.hide();
}
Stopping Sounds
// Stop a playing sound
backgroundMusic.stop();
explosionSound.stop();
// Example: Pause background music when game is paused
let gamePaused = false;
function togglePause() {
gamePaused = !gamePaused;
if (gamePaused) {
backgroundMusic.stop();
} else {
backgroundMusic.play();
}
}
Practical Game Audio Examples
Platformer Game Audio System
class GameAudio {
constructor() {
this.sounds = {
jump: new Sound("audio/jump.wav"),
land: new Sound("audio/land.wav"),
coin: new Sound("audio/coin.mp3"),
enemyHit: new Sound("audio/enemy_hit.wav"),
playerHit: new Sound("audio/player_hit.wav"),
powerup: new Sound("audio/powerup.wav")
};
this.music = {
mainTheme: new Sound("music/main_theme.mp3"),
levelComplete: new Sound("music/level_complete.mp3"),
gameOver: new Sound("music/game_over.mp3")
};
this.isMuted = false;
}
playSound(soundName) {
if (!this.isMuted && this.sounds[soundName]) {
this.sounds[soundName].play();
}
}
playMusic(musicName, loop = true) {
if (!this.isMuted && this.music[musicName]) {
this.music[musicName].play();
// Note: Looping would need additional implementation
}
}
toggleMute() {
this.isMuted = !this.isMuted;
if (this.isMuted) {
this.stopAll();
}
}
stopAll() {
for (let sound in this.sounds) {
this.sounds[sound].stop();
}
for (let music in this.music) {
this.music[music].stop();
}
}
}
// Usage
const audio = new GameAudio();
function update() {
// Play sounds based on game events
if (player.crashWith(coin)) {
audio.playSound("coin");
}
if (player.crashWith(enemy)) {
audio.playSound("playerHit");
}
}
Shooter Game Audio Manager
class ShooterAudio {
constructor() {
this.sounds = {
laser: new Sound("sfx/laser.wav"),
explosion: new Sound("sfx/explosion.wav"),
shield: new Sound("sfx/shield.wav"),
reload: new Sound("sfx/reload.wav"),
lowHealth: new Sound("sfx/low_health.wav")
};
this.backgroundMusic = new Sound("music/space_battle.mp3");
this.lowHealthPlayed = false;
}
playLaserShot() {
this.sounds.laser.play();
}
playExplosion() {
this.sounds.explosion.play();
}
playShieldHit() {
this.sounds.shield.play();
}
checkHealthWarning(health) {
if (health < 30 && !this.lowHealthPlayed) {
this.sounds.lowHealth.play();
this.lowHealthPlayed = true;
} else if (health >= 30) {
this.lowHealthPlayed = false;
}
}
startBackgroundMusic() {
this.backgroundMusic.play();
}
stopBackgroundMusic() {
this.backgroundMusic.stop();
}
}
// Usage in shooter game
const shooterAudio = new ShooterAudio();
function fireLaser() {
if (display.keys[32]) { // Spacebar
createLaser();
shooterAudio.playLaserShot();
}
}
function update() {
shooterAudio.checkHealthWarning(playerHealth);
}
Advanced Audio Features
Volume Control System
// Extended Sound class with volume control
class AdvancedSound {
constructor(src, volume = 1.0) {
this.sound = document.createElement("audio");
this.sound.src = src;
this.sound.setAttribute("preload", "auto");
this.sound.setAttribute("controls", "none");
this.sound.style.display = "none";
this.sound.volume = volume;
document.body.appendChild(this.sound);
}
play() {
this.sound.currentTime = 0; // Rewind to start
this.sound.play();
}
stop() {
this.sound.pause();
this.sound.currentTime = 0;
}
setVolume(volume) {
this.sound.volume = Math.max(0, Math.min(1, volume));
}
getVolume() {
return this.sound.volume;
}
}
// Usage
const music = new AdvancedSound("music/game.mp3", 0.5); // 50% volume
const sfx = new AdvancedSound("sfx/click.wav", 0.8); // 80% volume
// Adjust volumes dynamically
music.setVolume(0.3); // Lower music volume
sfx.setVolume(1.0); // Max SFX volume
Audio Pooling for Multiple Instances
javascript
class SoundPool {
constructor(src, poolSize = 5) {
this.sounds = [];
this.currentIndex = 0;
// Create pool of audio elements
for (let i = 0; i
This content originally appeared on DEV Community and was authored by Kehinde Owolabi