Question
I am building a game with HTML5 and JavaScript.
How can I play game audio using JavaScript?
Short Answer
By the end of this page, you will understand how to play audio in a browser-based game using JavaScript, how to load sound files, start playback, control volume, loop music, and handle common issues such as browser autoplay restrictions.
Concept
In an HTML5 game, audio is usually played through the browser's built-in audio features. The most beginner-friendly way is to use the Audio constructor or an HTML <audio> element and control it with JavaScript.
JavaScript can:
- load a sound file
- play it when something happens in the game
- pause or stop it
- loop background music
- adjust volume
A simple example is this:
const sound = new Audio('jump.mp3');
sound.play();
This creates an audio object and starts playback.
This concept matters because sound is an important part of game feedback. Players expect audio for actions like:
- jumping
- collecting items
- taking damage
- winning or losing
- background music during gameplay
Without audio, a game often feels less responsive and less immersive.
In real programming, audio playback is event-driven. That means you usually do not play sound immediately when the page loads. Instead, you play it in response to something, such as:
- a button click
- a key press
- a collision in the game
- the start of a new level
One important browser rule is that many browsers block audio playback until the user interacts with the page. This is called an autoplay restriction. So in games, audio usually starts after the player clicks or presses a key.
Mental Model
Think of an audio object like a music player you keep in your code.
- Creating
new Audio('sound.mp3')is like loading a song into the player. - Calling
.play()is like pressing the play button. - Calling
.pause()is like pressing pause. - Setting
.loop = trueis like turning on repeat mode. - Setting
.currentTime = 0is like rewinding to the beginning.
In a game, you often keep several small audio players ready:
- one for background music
- one for jump sounds
- one for explosion sounds
- one for menu clicks
Then, when a game event happens, you tell the right player to start.
Syntax and Examples
The simplest way to play audio in JavaScript is:
const sound = new Audio('sound.mp3');
sound.play();
Example: play a sound when a button is clicked
<button id="playButton">Play Sound</button>
<script>
const sound = new Audio('coin.mp3');
document.getElementById('playButton').addEventListener('click', () => {
sound.play();
});
</script>
What this does
new Audio('coin.mp3')creates an audio object for the file.addEventListener('click', ...)waits for the user to click.sound.play()starts playback.
Example: loop background music
const music = new Audio('background.mp3');
music.loop = true;
music.volume = 0.5;
startButton.addEventListener('click', () => {
music.play();
});
What this adds
loop = truerepeats the music forever.volume = 0.5sets the volume to 50%.
Example: replay a short sound effect
const laser = new Audio('laser.mp3');
function fireLaser() {
laser.currentTime = 0;
laser.play();
}
This is useful for sound effects that may be triggered many times. Resetting currentTime sends playback back to the beginning before playing again.
Step by Step Execution
Consider this example:
const jumpSound = new Audio('jump.mp3');
jumpSound.volume = 0.7;
function playerJump() {
jumpSound.currentTime = 0;
jumpSound.play();
}
playerJump();
Here is what happens step by step:
-
const jumpSound = new Audio('jump.mp3');- JavaScript creates an audio object.
- The browser knows which file should be used for the sound.
-
jumpSound.volume = 0.7;- The volume is set to 70%.
- Volume values usually go from
0to1.
-
function playerJump() { ... }- A function is defined.
- The function will play the jump sound whenever it is called.
-
jumpSound.currentTime = 0;- The sound is rewound to the beginning.
- This is useful if the jump happens repeatedly.
-
jumpSound.play();- The browser starts playing the file.
- In modern browsers, this works best after user interaction.
-
playerJump();- The function is called.
- The sound starts playing.
Trace example in a game
Imagine the player presses the space bar:
document.addEventListener('keydown', (event) => {
if (event.code === 'Space') {
playerJump();
}
});
Now the game flow is:
- user presses Space
keydownevent fires- condition checks
event.code === 'Space' playerJump()runs- sound resets to start
- sound plays
Real World Use Cases
Audio playback is used in many kinds of web applications, especially games.
In games
- jump sounds when the player moves
- collision sounds when objects hit each other
- pickup sounds for coins, keys, or power-ups
- looping background music for levels
- menu sounds for buttons and navigation
In interactive apps
- notification sounds in chat apps
- voice prompts in language-learning tools
- feedback sounds in quiz apps
- alarms or timers in productivity apps
In browser-based media tools
- previewing audio clips
- playing music tracks
- sound effects in animation editors
For games specifically, the most common pattern is:
- preload important sounds
- play short effects during events
- loop background music separately
- provide mute or volume controls
Real Codebase Usage
In real projects, developers usually organize audio into reusable patterns instead of creating random audio objects everywhere.
Common pattern: one place for game sounds
const sounds = {
jump: new Audio('jump.mp3'),
hit: new Audio('hit.mp3'),
coin: new Audio('coin.mp3'),
music: new Audio('music.mp3')
};
sounds.music.loop = true;
This makes it easier to access sounds throughout the codebase.
Common pattern: helper function for sound effects
function playSound(sound) {
sound.currentTime = 0;
sound.play();
}
playSound(sounds.coin);
This avoids repeating the same logic.
Guarding playback errors
In modern browsers, play() returns a promise. Developers sometimes handle failures:
sounds.music.play().catch((error) => {
console.log('Audio could not start yet:', error);
});
This is useful when autoplay is blocked.
Muting audio from settings
let isMuted = false;
function setMuted(value) {
isMuted = value;
Object.values(sounds).forEach(sound => {
sound.muted = isMuted;
});
}
This is common in game settings menus.
Early checks before playing
function playCoinSound() {
if (isMuted) return;
playSound(sounds.coin);
}
This is a simple guard clause. It prevents unnecessary playback logic when audio is muted.
Common Mistakes
Beginners often run into a few common issues when working with browser audio.
1. Trying to play audio before user interaction
Broken example:
const music = new Audio('music.mp3');
music.play();
Why this fails:
- many browsers block autoplay
- audio often will not start until the user clicks, taps, or presses a key
Better approach:
startButton.addEventListener('click', () => {
music.play();
});
2. Using the wrong file path
Broken example:
const sound = new Audio('sounds/jump.mp3');
sound.play();
If the file path is wrong, nothing will play.
How to avoid it:
- verify the file exists
- check the browser console for loading errors
- use correct relative paths
3. Expecting a sound effect to replay instantly without resetting time
Broken example:
const hit = new Audio('hit.mp3');
function takeDamage() {
hit.play();
}
Problem:
- repeated calls may not restart the sound as expected
Better version:
function takeDamage() {
hit.currentTime = 0;
hit.play();
}
4. Forgetting volume range rules
Broken example:
sound.volume = 10;
Why it is wrong:
- volume should usually be between
0and1
Correct example:
sound.volume = 0.8;
5. Creating a new audio object every time without a reason
Less efficient example:
function jump() {
const sound = new Audio('jump.mp3');
sound.play();
}
Why to avoid it:
- this repeatedly creates new objects
- it can be wasteful in a fast game loop
Better approach:
const jumpSound = new Audio('jump.mp3');
function jump() {
jumpSound.currentTime = 0;
jumpSound.play();
}
6. Not handling the promise from play() when needed
Sometimes playback can fail:
sound.play().catch(error => {
console.log('Playback failed:', error);
});
This helps with debugging browser restrictions.
Comparisons
Here are the main ways beginners commonly play audio in browser JavaScript.
| Approach | Example | Best for | Notes |
|---|---|---|---|
new Audio() | const s = new Audio('a.mp3') | Simple sound effects and small games | Easy to start with |
HTML <audio> element + JavaScript | document.querySelector('audio').play() | Pages where audio is part of the HTML | Useful when controls or markup already exist |
| Web Audio API | Advanced audio graphs and processing | Complex games and audio apps | More powerful, but harder for beginners |
new Audio() vs <audio> element
const sound = new Audio('coin.mp3');
sound.play();
vs
<audio id="coinSound" src="coin.mp3"></audio>
<script>
document.getElementById('coinSound').play();
</script>
Differences
new Audio()is quick and convenient in JavaScript-heavy games.<audio>is useful when you want the audio resource defined in HTML.- Both use similar playback methods such as
.play()and.pause().
Sound effects vs background music
| Type | Typical settings |
|---|---|
| Sound effect | short, may use currentTime = 0 before replay |
| Background music | often uses loop = true and lower volume |
| UI sound | short, triggered by click or navigation events |
Cheat Sheet
// Create audio
const sound = new Audio('sound.mp3');
// Play
sound.play();
// Pause
sound.pause();
// Stop-like behavior
sound.pause();
sound.currentTime = 0;
// Loop
sound.loop = true;
// Volume (0 to 1)
sound.volume = 0.5;
// Mute
sound.muted = true;
// Replay from start
sound.currentTime = 0;
sound.play();
Quick rules
- Use
new Audio('file.mp3')for simple game sounds. - Start audio after user interaction when possible.
- Use
loop = truefor background music. - Use
currentTime = 0for replaying short sound effects. - Use values from
0to1forvolume. - Check file paths if a sound does not play.
play()may fail if the browser blocks autoplay.
Common properties and methods
| Item | Purpose |
|---|---|
play() | Start playback |
pause() | Pause playback |
currentTime | Get or set playback position |
loop | Repeat automatically |
volume | Set loudness from 0 to 1 |
muted | Mute or unmute |
src | Audio file path |
FAQ
How do I play audio in JavaScript?
Create an audio object with new Audio('file.mp3') and call .play() on it.
Why is my audio not playing in the browser?
The most common reasons are autoplay restrictions, a wrong file path, or the audio format not loading correctly.
How do I loop background music in an HTML5 game?
Set music.loop = true before calling music.play().
How do I stop a sound in JavaScript?
Use sound.pause() and, if you want to reset it, set sound.currentTime = 0.
How do I replay a sound effect quickly?
Set sound.currentTime = 0 before calling sound.play().
Can I control volume in JavaScript audio?
Yes. Set sound.volume to a value between 0 and 1.
Should I use new Audio() or the Web Audio API?
For simple HTML5 games, new Audio() is often enough. For advanced audio control and effects, the Web Audio API is more powerful.
Can I preload sounds for my game?
Yes. A common approach is to create audio objects early in the game so they are ready when events happen.
Mini Project
Description
Build a small sound controller for a browser game. The page will let a player start background music, play a jump sound effect, and mute all audio. This demonstrates the core audio actions most games need: event-based playback, looping music, replaying sound effects, and basic audio settings.
Goal
Create a simple JavaScript game-audio panel that can play looping music, trigger a sound effect on demand, and mute or unmute all sound.
Requirements
- Create one audio object for background music and one for a jump sound effect.
- Start the background music only after the user clicks a button.
- Make the background music loop continuously.
- Add a button that replays the jump sound from the beginning each time it is clicked.
- Add a mute toggle that affects both sounds.
Keep learning
Related questions
Add a Favicon to a Static HTML Page
Learn how to add a favicon to static HTML pages, use correct paths and icon formats, and troubleshoot browser caching and local-file issues.
Allow Only Numeric Input (0-9) in HTML Input Using jQuery
Learn how to allow only digits 0-9 in an HTML input using jQuery, with examples, validation tips, common mistakes, and best practices.
Apply CSS !important with jQuery .css()
Learn why jQuery .css() cannot set !important and how to use CSSStyleDeclaration.setProperty() to apply inline important styles safely.