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
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.
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:
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:
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
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.
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.
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
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.
CSS :not() Selector for Excluding a Class or Attribute
Learn how to use the CSS :not() selector to target elements that do not have a specific class or attribute, with examples and common mistakes.
Can HTML Checkboxes Be Readonly? Understanding readonly vs disabled in HTML Forms
Learn why HTML checkboxes do not support readonly, how disabled differs, and practical ways to prevent changes while still submitting values.