I am making a game with HTML5 and JavaScript.
How could I play game audio via JavaScript?
If you don't want to mess with HTML elements:
var audio = new Audio('audio_file.mp3');
audio.play();
function play() {
var audio = new Audio('https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3');
audio.play();
}
<button onclick="play()">Play Audio</button>
This uses the HTMLAudioElement interface, which plays audio the same way as the <audio> element.
If you need more functionality, I used the howler.js library and found it simple and useful.
<script src="https://cdnjs.cloudflare.com/ajax/libs/howler/2.1.1/howler.min.js"></script>
<script>
var sound = new Howl({
src: ['https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3'],
volume: 0.5,
onend: function () {
alert('Finished!');
}
});
sound.play()
</script>
It's easy, just get your audio element and call the play() method:
document.getElementById('yourAudioTag').play();
Check out this example: http://www.storiesinflight.com/html5/audio.html
This site uncovers some of the other cool things you can do such as load(), pause(), and a few other properties of the audio element.
This is a quite old question but I want to add some useful info. The topic starter has mentioned that he is "making a game". So for everybody who needs audio for game development there is a better choice than just an <audio> tag or an HTMLAudioElement. I think you should consider the use of the Web Audio API:
While audio on the web no longer requires a plugin, the audio tag brings significant limitations for implementing sophisticated games and interactive applications. The Web Audio API is a high-level JavaScript API for processing and synthesizing audio in web applications. The goal of this API is to include capabilities found in modern game audio engines and some of the mixing, processing, and filtering tasks that are found in modern desktop audio production applications.
http://www.schillmania.com/projects/soundmanager2/
SoundManager 2 provides a easy to use API that allows sound to be played in any modern browser, including IE 6+. If the browser doesn't support HTML5, then it gets help from flash. If you want stricly HTML5 and no flash, there's a setting for that, preferFlash=false
It supports 100% Flash-free audio on iPad, iPhone (iOS4) and other HTML5-enabled devices + browsers
Use is as simple as:
<script src="soundmanager2.js"></script>
<script>
// where to find flash SWFs, if needed...
soundManager.url = '/path/to/swf-files/';
soundManager.onready(function() {
soundManager.createSound({
id: 'mySound',
url: '/path/to/an.mp3'
});
// ...and play it
soundManager.play('mySound');
});
</script>
Here's a demo of it in action: http://www.schillmania.com/projects/soundmanager2/demo/christmas-lights/
Easy with Jquery
// set audio tags with no preload
<audio class="my_audio" controls preload="none">
<source src="audio/my_song.mp3" type="audio/mpeg">
<source src="audio/my_song.ogg" type="audio/ogg">
</audio>
// add jquery to load
$(".my_audio").trigger('load');
// write methods for playing and stopping
function play_audio(task) {
if(task == 'play'){
$(".my_audio").trigger('play');
}
if(task == 'stop'){
$(".my_audio").trigger('pause');
$(".my_audio").prop("currentTime",0);
}
}
// decide how to control audio
<button onclick="play_audio('play')">PLAY</button>
<button onclick="play_audio('stop')">STOP</button>
EDIT
To address #stomy's question, here is how you would use this approach to play a playlist:
Set your songs in an object:
playlist = {
'song_1' : 'audio/splat.mp3',
'song_2' : 'audio/saw.mp3',
'song_3' : 'audio/marbles.mp3',
'song_4' : 'audio/seagulls.mp3',
'song_5' : 'audio/plane.mp3'
}
Use the trigger and play functions as before:
$(".my_audio").trigger('load');
function play_audio(task) {
if(task == 'play'){
$(".my_audio").trigger('play');
}
if(task == 'stop'){
$(".my_audio").trigger('pause');
$(".my_audio").prop("currentTime",0);
}
}
Load the first song dynamically:
keys = Object.keys(playlist);
$('.my_audio').append("<source id='sound_src' src=" + playlist[keys[0]] + " type='audio/mpeg'>");
Reset the audio source to the next song in the playlist, when the current song ends:
count = 0;
$('.my_audio').on('ended', function() {
count++;
$("#sound_src").attr("src", playlist[keys[count]])[0];
$(".my_audio").trigger('load');
play_audio('play');
});
See here for an example of this code in action.
If you are getting the following error:
Uncaught (in promise) DOMException: play() failed because the user
didn't interact with the document first.
That means the user needs to interact with the website first (as the error message says). In this case you need to use click or just another event listener, so the user can interact with your website.
If you want to auto load the audio and don't want the user to interact with the document first, you could use setTimeout.
setTimeout(() => {
document.getElementById('mySound').play();
}, 500)
<audio id="mySound" src="sound.mp3"></audio>
The sound will start after 0.5 second.
Add a hidden <audio> element and play it as shown.
function playSound(url) {
var ourAudio = document.createElement('audio'); // Create a audio element using the DOM
ourAudio.style.display = "none"; // Hide the audio element
ourAudio.src = url; // Set resource to our URL
ourAudio.autoplay = true; // Automatically play sound
ourAudio.onended = function() {
this.remove(); // Remove when played.
};
document.body.appendChild(ourAudio);
}
new Audio('./file.mp3').play()
With the security requirements that a user must interact with a webpage for audio to be allowed this is how I do it, based on reading many articles, including on this site
Define the required audio files in your html
Have a start game button with an onclick
When the button is clicked then play and pause ALL the audio files bar the one you want to play at the beginning
Because all the audio files have been "played" on the same OnClick, you can now play them any time in the game without restrictions
Note that for best compatability do not use wav files, MS do not support them
Use mp3 and ogg, that covers all devices
Example:
<audio id="welcome">
<source src="URL/welcome.ogg" type="audio/ogg">
<source src="URL/welcome.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
repeat as needed for all audio in the game
Then:
document.getElementById("welcome").play();
document.getElementById("welcome").pause();
repeat as needed except do not pause the audio you want to hear when the game starts
Pretty simple solution if you have an HTML tag like below:
<audio id="myAudio" src="some_audio.mp3"></audio>
Just use JavaScript to play it, like so:
document.getElementById('myAudio').play();
var song = new Audio();
song.src = 'file.mp3';
song.play();
I had some issues related to audio promise object returns and some issues related to user interaction with sounds I end up using this small object,
I would recommend to implement the play sounds the closest to the interaction event user is using.
var soundPlayer = {
audio: null,
muted: false,
playing: false,
_ppromis: null,
puse: function () {
this.audio.pause();
},
play: function (file) {
if (this.muted) {
return false;
}
if (!this.audio && this.playing === false) {
this.audio = new Audio(file);
this._ppromis = this.audio.play();
this.playing = true;
if (this._ppromis !== undefined) {
this._ppromis.then(function () {
soundPlayer.playing = false;
});
}
} else if (!this.playing) {
this.playing = true;
this.audio.src = file;
this._ppromis = soundPlayer.audio.play();
this._ppromis.then(function () {
soundPlayer.playing = false;
});
}
}
};
And implement it as follow:
<button onclick="soundPlayer.play('https://interactive-examples.mdn.mozilla.net/media/examples/t-rex-roar.mp3');">Play</button>
I used this method to play a sound...
var audioElement;
if(!audioElement) {
audioElement = document.createElement('audio');
audioElement.innerHTML = '<source src="' + '/audio/sound.mp3'+ '" type="audio/mpeg" />'
}
audioElement.play();
If you want to be able to play the sound even when the browser-tab is currently not selected, you have to load the audio-resource on page load.
Like so:
var audio = new Audio('audio/path.mp3');
function playSound(){
audio.play();
}
See this question for more detail
if you want to play your audio whenever the page is opened then do like this.
<script>
function playMusic(){
music.play();
}
</script>
<html>
<audio id="music" loop src="sounds/music.wav" autoplay> </audio>
</html>
and call this playMusic() whenever you need in your game code.
You can use Web Audio API for playing sounds. There are quite some audio libraries out there like howler.js, soundjs etc. If you don't worry about old browsers then you can also check on http://musquitojs.com/. It provides a simple API to create and play sounds.
For example, to play a sound all you've to do is.
import $buzz from 'musquito';
const buzz = $buzz('gunfire.mp3');
buzz.play();
The library also supports Audio Sprites.
This is some JS i came up with on a baby AI project im working with. i hope this is able to help you out.
<!DOCTYPE html>
<html>
<head>
<title>
js prompt AI
</title>
<style>
#button {
border: 1px solid black;
border-radius: 10px;
font-size: 22px;
height:65px;
width:100px;
text-align: center;
line-height: 65px;
}
</style>
</head>
<body>
<audio id="myAudio" src="./how_are_you.m4a"></audio>
<p>To Interact with the AI please click the button</p>
<div id=button>click</div>
<script>
var button = document.getElementById("button");
function playBack() {
button.addEventListener("click", function (){
var talk = prompt("If you wish for the AI to respond type hi");
var myAudio = document.getElementById("myAudio");
if(talk === "hi") {
myAudio.play();
}
}) ;
}
playBack();
</script>
</body>
</html>
Just use this:
<video controls="" autoplay="" name="media"><source src="Sound URL Here" type="audio/mpeg" /></video>
Or, to make it simpler:
<video controls="" autoplay="" name="media">
<source src="Sound URL Here" type="audio/mpeg" />
</video>
Sample:
<video controls="" autoplay="" name="media">
<source src="https://interactive-examples.mdn.mozilla.net/media/examples/t-rex-roar.mp3" type="audio/mpeg">
</video>
Have NO IDEA if this works on other browsers other than Chrome 73!!
const playAudio = (path) => {
new Audio(path ?? 'defaultPath').play()
}
playAudio('path')`
I had some issues with playing audio, especially since Chrome has updated that the user has to interact with the document first.
However, across almost all solutions I found is that the JS code has to actively set listeners (e.g. button clicks) to receive user events in order to play the audio.
In my case I just wanted my game to play BGM as soon as the player interacts with it, so I made myself a simple listener that keeps checking whether the web page is being interacted or not.
const stopAttempt = setInterval(() => {
const audio = new Audio('your_audio_url_or_file_name.mp3');
const playPromise = audio.play();
if (playPromise) {
playPromise.then(() => {
clearInterval(stopAttempt)
}).catch(e=>{
console.log('' + e);
})
}
}, 100 )
Here is a solution for the year 2020 when you are seeing the error:
[Error] Unhandled Promise Rejection: NotSupportedError: The operation is not supported.
(anonymous function)
rejectPromise
play
(anonymous function) (testaudio.html:96)
dispatch (jquery-3.4.1.min.js:2:42577)
<div onclick="new Audio('/assets/test.mp3').play()">aaa</div>
Don't be slick and think ooh that's an old school oclick, I'll just move that down the page to my jQuery or my external JavaScript file. Nope. It needs to be an onclick.
In react, you can use ref:
// typescript
const audRef = useRef(null);
const playAudio = () => {
(audRef.current as any).play();
}
...
// html
<audio controls src={your_audio} ref={audRef} />
<button onClick={playAudio}>Play</button>
Related
I am making a game with HTML5 and JavaScript.
How could I play game audio via JavaScript?
If you don't want to mess with HTML elements:
var audio = new Audio('audio_file.mp3');
audio.play();
function play() {
var audio = new Audio('https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3');
audio.play();
}
<button onclick="play()">Play Audio</button>
This uses the HTMLAudioElement interface, which plays audio the same way as the <audio> element.
If you need more functionality, I used the howler.js library and found it simple and useful.
<script src="https://cdnjs.cloudflare.com/ajax/libs/howler/2.1.1/howler.min.js"></script>
<script>
var sound = new Howl({
src: ['https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3'],
volume: 0.5,
onend: function () {
alert('Finished!');
}
});
sound.play()
</script>
It's easy, just get your audio element and call the play() method:
document.getElementById('yourAudioTag').play();
Check out this example: http://www.storiesinflight.com/html5/audio.html
This site uncovers some of the other cool things you can do such as load(), pause(), and a few other properties of the audio element.
This is a quite old question but I want to add some useful info. The topic starter has mentioned that he is "making a game". So for everybody who needs audio for game development there is a better choice than just an <audio> tag or an HTMLAudioElement. I think you should consider the use of the Web Audio API:
While audio on the web no longer requires a plugin, the audio tag brings significant limitations for implementing sophisticated games and interactive applications. The Web Audio API is a high-level JavaScript API for processing and synthesizing audio in web applications. The goal of this API is to include capabilities found in modern game audio engines and some of the mixing, processing, and filtering tasks that are found in modern desktop audio production applications.
http://www.schillmania.com/projects/soundmanager2/
SoundManager 2 provides a easy to use API that allows sound to be played in any modern browser, including IE 6+. If the browser doesn't support HTML5, then it gets help from flash. If you want stricly HTML5 and no flash, there's a setting for that, preferFlash=false
It supports 100% Flash-free audio on iPad, iPhone (iOS4) and other HTML5-enabled devices + browsers
Use is as simple as:
<script src="soundmanager2.js"></script>
<script>
// where to find flash SWFs, if needed...
soundManager.url = '/path/to/swf-files/';
soundManager.onready(function() {
soundManager.createSound({
id: 'mySound',
url: '/path/to/an.mp3'
});
// ...and play it
soundManager.play('mySound');
});
</script>
Here's a demo of it in action: http://www.schillmania.com/projects/soundmanager2/demo/christmas-lights/
Easy with Jquery
// set audio tags with no preload
<audio class="my_audio" controls preload="none">
<source src="audio/my_song.mp3" type="audio/mpeg">
<source src="audio/my_song.ogg" type="audio/ogg">
</audio>
// add jquery to load
$(".my_audio").trigger('load');
// write methods for playing and stopping
function play_audio(task) {
if(task == 'play'){
$(".my_audio").trigger('play');
}
if(task == 'stop'){
$(".my_audio").trigger('pause');
$(".my_audio").prop("currentTime",0);
}
}
// decide how to control audio
<button onclick="play_audio('play')">PLAY</button>
<button onclick="play_audio('stop')">STOP</button>
EDIT
To address #stomy's question, here is how you would use this approach to play a playlist:
Set your songs in an object:
playlist = {
'song_1' : 'audio/splat.mp3',
'song_2' : 'audio/saw.mp3',
'song_3' : 'audio/marbles.mp3',
'song_4' : 'audio/seagulls.mp3',
'song_5' : 'audio/plane.mp3'
}
Use the trigger and play functions as before:
$(".my_audio").trigger('load');
function play_audio(task) {
if(task == 'play'){
$(".my_audio").trigger('play');
}
if(task == 'stop'){
$(".my_audio").trigger('pause');
$(".my_audio").prop("currentTime",0);
}
}
Load the first song dynamically:
keys = Object.keys(playlist);
$('.my_audio').append("<source id='sound_src' src=" + playlist[keys[0]] + " type='audio/mpeg'>");
Reset the audio source to the next song in the playlist, when the current song ends:
count = 0;
$('.my_audio').on('ended', function() {
count++;
$("#sound_src").attr("src", playlist[keys[count]])[0];
$(".my_audio").trigger('load');
play_audio('play');
});
See here for an example of this code in action.
If you are getting the following error:
Uncaught (in promise) DOMException: play() failed because the user
didn't interact with the document first.
That means the user needs to interact with the website first (as the error message says). In this case you need to use click or just another event listener, so the user can interact with your website.
If you want to auto load the audio and don't want the user to interact with the document first, you could use setTimeout.
setTimeout(() => {
document.getElementById('mySound').play();
}, 500)
<audio id="mySound" src="sound.mp3"></audio>
The sound will start after 0.5 second.
Add a hidden <audio> element and play it as shown.
function playSound(url) {
var ourAudio = document.createElement('audio'); // Create a audio element using the DOM
ourAudio.style.display = "none"; // Hide the audio element
ourAudio.src = url; // Set resource to our URL
ourAudio.autoplay = true; // Automatically play sound
ourAudio.onended = function() {
this.remove(); // Remove when played.
};
document.body.appendChild(ourAudio);
}
new Audio('./file.mp3').play()
With the security requirements that a user must interact with a webpage for audio to be allowed this is how I do it, based on reading many articles, including on this site
Define the required audio files in your html
Have a start game button with an onclick
When the button is clicked then play and pause ALL the audio files bar the one you want to play at the beginning
Because all the audio files have been "played" on the same OnClick, you can now play them any time in the game without restrictions
Note that for best compatability do not use wav files, MS do not support them
Use mp3 and ogg, that covers all devices
Example:
<audio id="welcome">
<source src="URL/welcome.ogg" type="audio/ogg">
<source src="URL/welcome.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
repeat as needed for all audio in the game
Then:
document.getElementById("welcome").play();
document.getElementById("welcome").pause();
repeat as needed except do not pause the audio you want to hear when the game starts
Pretty simple solution if you have an HTML tag like below:
<audio id="myAudio" src="some_audio.mp3"></audio>
Just use JavaScript to play it, like so:
document.getElementById('myAudio').play();
var song = new Audio();
song.src = 'file.mp3';
song.play();
I had some issues related to audio promise object returns and some issues related to user interaction with sounds I end up using this small object,
I would recommend to implement the play sounds the closest to the interaction event user is using.
var soundPlayer = {
audio: null,
muted: false,
playing: false,
_ppromis: null,
puse: function () {
this.audio.pause();
},
play: function (file) {
if (this.muted) {
return false;
}
if (!this.audio && this.playing === false) {
this.audio = new Audio(file);
this._ppromis = this.audio.play();
this.playing = true;
if (this._ppromis !== undefined) {
this._ppromis.then(function () {
soundPlayer.playing = false;
});
}
} else if (!this.playing) {
this.playing = true;
this.audio.src = file;
this._ppromis = soundPlayer.audio.play();
this._ppromis.then(function () {
soundPlayer.playing = false;
});
}
}
};
And implement it as follow:
<button onclick="soundPlayer.play('https://interactive-examples.mdn.mozilla.net/media/examples/t-rex-roar.mp3');">Play</button>
I used this method to play a sound...
var audioElement;
if(!audioElement) {
audioElement = document.createElement('audio');
audioElement.innerHTML = '<source src="' + '/audio/sound.mp3'+ '" type="audio/mpeg" />'
}
audioElement.play();
If you want to be able to play the sound even when the browser-tab is currently not selected, you have to load the audio-resource on page load.
Like so:
var audio = new Audio('audio/path.mp3');
function playSound(){
audio.play();
}
See this question for more detail
if you want to play your audio whenever the page is opened then do like this.
<script>
function playMusic(){
music.play();
}
</script>
<html>
<audio id="music" loop src="sounds/music.wav" autoplay> </audio>
</html>
and call this playMusic() whenever you need in your game code.
You can use Web Audio API for playing sounds. There are quite some audio libraries out there like howler.js, soundjs etc. If you don't worry about old browsers then you can also check on http://musquitojs.com/. It provides a simple API to create and play sounds.
For example, to play a sound all you've to do is.
import $buzz from 'musquito';
const buzz = $buzz('gunfire.mp3');
buzz.play();
The library also supports Audio Sprites.
This is some JS i came up with on a baby AI project im working with. i hope this is able to help you out.
<!DOCTYPE html>
<html>
<head>
<title>
js prompt AI
</title>
<style>
#button {
border: 1px solid black;
border-radius: 10px;
font-size: 22px;
height:65px;
width:100px;
text-align: center;
line-height: 65px;
}
</style>
</head>
<body>
<audio id="myAudio" src="./how_are_you.m4a"></audio>
<p>To Interact with the AI please click the button</p>
<div id=button>click</div>
<script>
var button = document.getElementById("button");
function playBack() {
button.addEventListener("click", function (){
var talk = prompt("If you wish for the AI to respond type hi");
var myAudio = document.getElementById("myAudio");
if(talk === "hi") {
myAudio.play();
}
}) ;
}
playBack();
</script>
</body>
</html>
Just use this:
<video controls="" autoplay="" name="media"><source src="Sound URL Here" type="audio/mpeg" /></video>
Or, to make it simpler:
<video controls="" autoplay="" name="media">
<source src="Sound URL Here" type="audio/mpeg" />
</video>
Sample:
<video controls="" autoplay="" name="media">
<source src="https://interactive-examples.mdn.mozilla.net/media/examples/t-rex-roar.mp3" type="audio/mpeg">
</video>
Have NO IDEA if this works on other browsers other than Chrome 73!!
const playAudio = (path) => {
new Audio(path ?? 'defaultPath').play()
}
playAudio('path')`
I had some issues with playing audio, especially since Chrome has updated that the user has to interact with the document first.
However, across almost all solutions I found is that the JS code has to actively set listeners (e.g. button clicks) to receive user events in order to play the audio.
In my case I just wanted my game to play BGM as soon as the player interacts with it, so I made myself a simple listener that keeps checking whether the web page is being interacted or not.
const stopAttempt = setInterval(() => {
const audio = new Audio('your_audio_url_or_file_name.mp3');
const playPromise = audio.play();
if (playPromise) {
playPromise.then(() => {
clearInterval(stopAttempt)
}).catch(e=>{
console.log('' + e);
})
}
}, 100 )
Here is a solution for the year 2020 when you are seeing the error:
[Error] Unhandled Promise Rejection: NotSupportedError: The operation is not supported.
(anonymous function)
rejectPromise
play
(anonymous function) (testaudio.html:96)
dispatch (jquery-3.4.1.min.js:2:42577)
<div onclick="new Audio('/assets/test.mp3').play()">aaa</div>
Don't be slick and think ooh that's an old school oclick, I'll just move that down the page to my jQuery or my external JavaScript file. Nope. It needs to be an onclick.
In react, you can use ref:
// typescript
const audRef = useRef(null);
const playAudio = () => {
(audRef.current as any).play();
}
...
// html
<audio controls src={your_audio} ref={audRef} />
<button onClick={playAudio}>Play</button>
I am making a game with HTML5 and JavaScript.
How could I play game audio via JavaScript?
If you don't want to mess with HTML elements:
var audio = new Audio('audio_file.mp3');
audio.play();
function play() {
var audio = new Audio('https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3');
audio.play();
}
<button onclick="play()">Play Audio</button>
This uses the HTMLAudioElement interface, which plays audio the same way as the <audio> element.
If you need more functionality, I used the howler.js library and found it simple and useful.
<script src="https://cdnjs.cloudflare.com/ajax/libs/howler/2.1.1/howler.min.js"></script>
<script>
var sound = new Howl({
src: ['https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3'],
volume: 0.5,
onend: function () {
alert('Finished!');
}
});
sound.play()
</script>
It's easy, just get your audio element and call the play() method:
document.getElementById('yourAudioTag').play();
Check out this example: http://www.storiesinflight.com/html5/audio.html
This site uncovers some of the other cool things you can do such as load(), pause(), and a few other properties of the audio element.
This is a quite old question but I want to add some useful info. The topic starter has mentioned that he is "making a game". So for everybody who needs audio for game development there is a better choice than just an <audio> tag or an HTMLAudioElement. I think you should consider the use of the Web Audio API:
While audio on the web no longer requires a plugin, the audio tag brings significant limitations for implementing sophisticated games and interactive applications. The Web Audio API is a high-level JavaScript API for processing and synthesizing audio in web applications. The goal of this API is to include capabilities found in modern game audio engines and some of the mixing, processing, and filtering tasks that are found in modern desktop audio production applications.
http://www.schillmania.com/projects/soundmanager2/
SoundManager 2 provides a easy to use API that allows sound to be played in any modern browser, including IE 6+. If the browser doesn't support HTML5, then it gets help from flash. If you want stricly HTML5 and no flash, there's a setting for that, preferFlash=false
It supports 100% Flash-free audio on iPad, iPhone (iOS4) and other HTML5-enabled devices + browsers
Use is as simple as:
<script src="soundmanager2.js"></script>
<script>
// where to find flash SWFs, if needed...
soundManager.url = '/path/to/swf-files/';
soundManager.onready(function() {
soundManager.createSound({
id: 'mySound',
url: '/path/to/an.mp3'
});
// ...and play it
soundManager.play('mySound');
});
</script>
Here's a demo of it in action: http://www.schillmania.com/projects/soundmanager2/demo/christmas-lights/
Easy with Jquery
// set audio tags with no preload
<audio class="my_audio" controls preload="none">
<source src="audio/my_song.mp3" type="audio/mpeg">
<source src="audio/my_song.ogg" type="audio/ogg">
</audio>
// add jquery to load
$(".my_audio").trigger('load');
// write methods for playing and stopping
function play_audio(task) {
if(task == 'play'){
$(".my_audio").trigger('play');
}
if(task == 'stop'){
$(".my_audio").trigger('pause');
$(".my_audio").prop("currentTime",0);
}
}
// decide how to control audio
<button onclick="play_audio('play')">PLAY</button>
<button onclick="play_audio('stop')">STOP</button>
EDIT
To address #stomy's question, here is how you would use this approach to play a playlist:
Set your songs in an object:
playlist = {
'song_1' : 'audio/splat.mp3',
'song_2' : 'audio/saw.mp3',
'song_3' : 'audio/marbles.mp3',
'song_4' : 'audio/seagulls.mp3',
'song_5' : 'audio/plane.mp3'
}
Use the trigger and play functions as before:
$(".my_audio").trigger('load');
function play_audio(task) {
if(task == 'play'){
$(".my_audio").trigger('play');
}
if(task == 'stop'){
$(".my_audio").trigger('pause');
$(".my_audio").prop("currentTime",0);
}
}
Load the first song dynamically:
keys = Object.keys(playlist);
$('.my_audio').append("<source id='sound_src' src=" + playlist[keys[0]] + " type='audio/mpeg'>");
Reset the audio source to the next song in the playlist, when the current song ends:
count = 0;
$('.my_audio').on('ended', function() {
count++;
$("#sound_src").attr("src", playlist[keys[count]])[0];
$(".my_audio").trigger('load');
play_audio('play');
});
See here for an example of this code in action.
If you are getting the following error:
Uncaught (in promise) DOMException: play() failed because the user
didn't interact with the document first.
That means the user needs to interact with the website first (as the error message says). In this case you need to use click or just another event listener, so the user can interact with your website.
If you want to auto load the audio and don't want the user to interact with the document first, you could use setTimeout.
setTimeout(() => {
document.getElementById('mySound').play();
}, 500)
<audio id="mySound" src="sound.mp3"></audio>
The sound will start after 0.5 second.
Add a hidden <audio> element and play it as shown.
function playSound(url) {
var ourAudio = document.createElement('audio'); // Create a audio element using the DOM
ourAudio.style.display = "none"; // Hide the audio element
ourAudio.src = url; // Set resource to our URL
ourAudio.autoplay = true; // Automatically play sound
ourAudio.onended = function() {
this.remove(); // Remove when played.
};
document.body.appendChild(ourAudio);
}
new Audio('./file.mp3').play()
With the security requirements that a user must interact with a webpage for audio to be allowed this is how I do it, based on reading many articles, including on this site
Define the required audio files in your html
Have a start game button with an onclick
When the button is clicked then play and pause ALL the audio files bar the one you want to play at the beginning
Because all the audio files have been "played" on the same OnClick, you can now play them any time in the game without restrictions
Note that for best compatability do not use wav files, MS do not support them
Use mp3 and ogg, that covers all devices
Example:
<audio id="welcome">
<source src="URL/welcome.ogg" type="audio/ogg">
<source src="URL/welcome.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
repeat as needed for all audio in the game
Then:
document.getElementById("welcome").play();
document.getElementById("welcome").pause();
repeat as needed except do not pause the audio you want to hear when the game starts
Pretty simple solution if you have an HTML tag like below:
<audio id="myAudio" src="some_audio.mp3"></audio>
Just use JavaScript to play it, like so:
document.getElementById('myAudio').play();
var song = new Audio();
song.src = 'file.mp3';
song.play();
I had some issues related to audio promise object returns and some issues related to user interaction with sounds I end up using this small object,
I would recommend to implement the play sounds the closest to the interaction event user is using.
var soundPlayer = {
audio: null,
muted: false,
playing: false,
_ppromis: null,
puse: function () {
this.audio.pause();
},
play: function (file) {
if (this.muted) {
return false;
}
if (!this.audio && this.playing === false) {
this.audio = new Audio(file);
this._ppromis = this.audio.play();
this.playing = true;
if (this._ppromis !== undefined) {
this._ppromis.then(function () {
soundPlayer.playing = false;
});
}
} else if (!this.playing) {
this.playing = true;
this.audio.src = file;
this._ppromis = soundPlayer.audio.play();
this._ppromis.then(function () {
soundPlayer.playing = false;
});
}
}
};
And implement it as follow:
<button onclick="soundPlayer.play('https://interactive-examples.mdn.mozilla.net/media/examples/t-rex-roar.mp3');">Play</button>
I used this method to play a sound...
var audioElement;
if(!audioElement) {
audioElement = document.createElement('audio');
audioElement.innerHTML = '<source src="' + '/audio/sound.mp3'+ '" type="audio/mpeg" />'
}
audioElement.play();
If you want to be able to play the sound even when the browser-tab is currently not selected, you have to load the audio-resource on page load.
Like so:
var audio = new Audio('audio/path.mp3');
function playSound(){
audio.play();
}
See this question for more detail
if you want to play your audio whenever the page is opened then do like this.
<script>
function playMusic(){
music.play();
}
</script>
<html>
<audio id="music" loop src="sounds/music.wav" autoplay> </audio>
</html>
and call this playMusic() whenever you need in your game code.
You can use Web Audio API for playing sounds. There are quite some audio libraries out there like howler.js, soundjs etc. If you don't worry about old browsers then you can also check on http://musquitojs.com/. It provides a simple API to create and play sounds.
For example, to play a sound all you've to do is.
import $buzz from 'musquito';
const buzz = $buzz('gunfire.mp3');
buzz.play();
The library also supports Audio Sprites.
This is some JS i came up with on a baby AI project im working with. i hope this is able to help you out.
<!DOCTYPE html>
<html>
<head>
<title>
js prompt AI
</title>
<style>
#button {
border: 1px solid black;
border-radius: 10px;
font-size: 22px;
height:65px;
width:100px;
text-align: center;
line-height: 65px;
}
</style>
</head>
<body>
<audio id="myAudio" src="./how_are_you.m4a"></audio>
<p>To Interact with the AI please click the button</p>
<div id=button>click</div>
<script>
var button = document.getElementById("button");
function playBack() {
button.addEventListener("click", function (){
var talk = prompt("If you wish for the AI to respond type hi");
var myAudio = document.getElementById("myAudio");
if(talk === "hi") {
myAudio.play();
}
}) ;
}
playBack();
</script>
</body>
</html>
Just use this:
<video controls="" autoplay="" name="media"><source src="Sound URL Here" type="audio/mpeg" /></video>
Or, to make it simpler:
<video controls="" autoplay="" name="media">
<source src="Sound URL Here" type="audio/mpeg" />
</video>
Sample:
<video controls="" autoplay="" name="media">
<source src="https://interactive-examples.mdn.mozilla.net/media/examples/t-rex-roar.mp3" type="audio/mpeg">
</video>
Have NO IDEA if this works on other browsers other than Chrome 73!!
const playAudio = (path) => {
new Audio(path ?? 'defaultPath').play()
}
playAudio('path')`
I had some issues with playing audio, especially since Chrome has updated that the user has to interact with the document first.
However, across almost all solutions I found is that the JS code has to actively set listeners (e.g. button clicks) to receive user events in order to play the audio.
In my case I just wanted my game to play BGM as soon as the player interacts with it, so I made myself a simple listener that keeps checking whether the web page is being interacted or not.
const stopAttempt = setInterval(() => {
const audio = new Audio('your_audio_url_or_file_name.mp3');
const playPromise = audio.play();
if (playPromise) {
playPromise.then(() => {
clearInterval(stopAttempt)
}).catch(e=>{
console.log('' + e);
})
}
}, 100 )
Here is a solution for the year 2020 when you are seeing the error:
[Error] Unhandled Promise Rejection: NotSupportedError: The operation is not supported.
(anonymous function)
rejectPromise
play
(anonymous function) (testaudio.html:96)
dispatch (jquery-3.4.1.min.js:2:42577)
<div onclick="new Audio('/assets/test.mp3').play()">aaa</div>
Don't be slick and think ooh that's an old school oclick, I'll just move that down the page to my jQuery or my external JavaScript file. Nope. It needs to be an onclick.
In react, you can use ref:
// typescript
const audRef = useRef(null);
const playAudio = () => {
(audRef.current as any).play();
}
...
// html
<audio controls src={your_audio} ref={audRef} />
<button onClick={playAudio}>Play</button>
I am making a game with HTML5 and JavaScript.
How could I play game audio via JavaScript?
If you don't want to mess with HTML elements:
var audio = new Audio('audio_file.mp3');
audio.play();
function play() {
var audio = new Audio('https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3');
audio.play();
}
<button onclick="play()">Play Audio</button>
This uses the HTMLAudioElement interface, which plays audio the same way as the <audio> element.
If you need more functionality, I used the howler.js library and found it simple and useful.
<script src="https://cdnjs.cloudflare.com/ajax/libs/howler/2.1.1/howler.min.js"></script>
<script>
var sound = new Howl({
src: ['https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3'],
volume: 0.5,
onend: function () {
alert('Finished!');
}
});
sound.play()
</script>
It's easy, just get your audio element and call the play() method:
document.getElementById('yourAudioTag').play();
Check out this example: http://www.storiesinflight.com/html5/audio.html
This site uncovers some of the other cool things you can do such as load(), pause(), and a few other properties of the audio element.
This is a quite old question but I want to add some useful info. The topic starter has mentioned that he is "making a game". So for everybody who needs audio for game development there is a better choice than just an <audio> tag or an HTMLAudioElement. I think you should consider the use of the Web Audio API:
While audio on the web no longer requires a plugin, the audio tag brings significant limitations for implementing sophisticated games and interactive applications. The Web Audio API is a high-level JavaScript API for processing and synthesizing audio in web applications. The goal of this API is to include capabilities found in modern game audio engines and some of the mixing, processing, and filtering tasks that are found in modern desktop audio production applications.
http://www.schillmania.com/projects/soundmanager2/
SoundManager 2 provides a easy to use API that allows sound to be played in any modern browser, including IE 6+. If the browser doesn't support HTML5, then it gets help from flash. If you want stricly HTML5 and no flash, there's a setting for that, preferFlash=false
It supports 100% Flash-free audio on iPad, iPhone (iOS4) and other HTML5-enabled devices + browsers
Use is as simple as:
<script src="soundmanager2.js"></script>
<script>
// where to find flash SWFs, if needed...
soundManager.url = '/path/to/swf-files/';
soundManager.onready(function() {
soundManager.createSound({
id: 'mySound',
url: '/path/to/an.mp3'
});
// ...and play it
soundManager.play('mySound');
});
</script>
Here's a demo of it in action: http://www.schillmania.com/projects/soundmanager2/demo/christmas-lights/
Easy with Jquery
// set audio tags with no preload
<audio class="my_audio" controls preload="none">
<source src="audio/my_song.mp3" type="audio/mpeg">
<source src="audio/my_song.ogg" type="audio/ogg">
</audio>
// add jquery to load
$(".my_audio").trigger('load');
// write methods for playing and stopping
function play_audio(task) {
if(task == 'play'){
$(".my_audio").trigger('play');
}
if(task == 'stop'){
$(".my_audio").trigger('pause');
$(".my_audio").prop("currentTime",0);
}
}
// decide how to control audio
<button onclick="play_audio('play')">PLAY</button>
<button onclick="play_audio('stop')">STOP</button>
EDIT
To address #stomy's question, here is how you would use this approach to play a playlist:
Set your songs in an object:
playlist = {
'song_1' : 'audio/splat.mp3',
'song_2' : 'audio/saw.mp3',
'song_3' : 'audio/marbles.mp3',
'song_4' : 'audio/seagulls.mp3',
'song_5' : 'audio/plane.mp3'
}
Use the trigger and play functions as before:
$(".my_audio").trigger('load');
function play_audio(task) {
if(task == 'play'){
$(".my_audio").trigger('play');
}
if(task == 'stop'){
$(".my_audio").trigger('pause');
$(".my_audio").prop("currentTime",0);
}
}
Load the first song dynamically:
keys = Object.keys(playlist);
$('.my_audio').append("<source id='sound_src' src=" + playlist[keys[0]] + " type='audio/mpeg'>");
Reset the audio source to the next song in the playlist, when the current song ends:
count = 0;
$('.my_audio').on('ended', function() {
count++;
$("#sound_src").attr("src", playlist[keys[count]])[0];
$(".my_audio").trigger('load');
play_audio('play');
});
See here for an example of this code in action.
If you are getting the following error:
Uncaught (in promise) DOMException: play() failed because the user
didn't interact with the document first.
That means the user needs to interact with the website first (as the error message says). In this case you need to use click or just another event listener, so the user can interact with your website.
If you want to auto load the audio and don't want the user to interact with the document first, you could use setTimeout.
setTimeout(() => {
document.getElementById('mySound').play();
}, 500)
<audio id="mySound" src="sound.mp3"></audio>
The sound will start after 0.5 second.
Add a hidden <audio> element and play it as shown.
function playSound(url) {
var ourAudio = document.createElement('audio'); // Create a audio element using the DOM
ourAudio.style.display = "none"; // Hide the audio element
ourAudio.src = url; // Set resource to our URL
ourAudio.autoplay = true; // Automatically play sound
ourAudio.onended = function() {
this.remove(); // Remove when played.
};
document.body.appendChild(ourAudio);
}
new Audio('./file.mp3').play()
With the security requirements that a user must interact with a webpage for audio to be allowed this is how I do it, based on reading many articles, including on this site
Define the required audio files in your html
Have a start game button with an onclick
When the button is clicked then play and pause ALL the audio files bar the one you want to play at the beginning
Because all the audio files have been "played" on the same OnClick, you can now play them any time in the game without restrictions
Note that for best compatability do not use wav files, MS do not support them
Use mp3 and ogg, that covers all devices
Example:
<audio id="welcome">
<source src="URL/welcome.ogg" type="audio/ogg">
<source src="URL/welcome.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
repeat as needed for all audio in the game
Then:
document.getElementById("welcome").play();
document.getElementById("welcome").pause();
repeat as needed except do not pause the audio you want to hear when the game starts
Pretty simple solution if you have an HTML tag like below:
<audio id="myAudio" src="some_audio.mp3"></audio>
Just use JavaScript to play it, like so:
document.getElementById('myAudio').play();
var song = new Audio();
song.src = 'file.mp3';
song.play();
I had some issues related to audio promise object returns and some issues related to user interaction with sounds I end up using this small object,
I would recommend to implement the play sounds the closest to the interaction event user is using.
var soundPlayer = {
audio: null,
muted: false,
playing: false,
_ppromis: null,
puse: function () {
this.audio.pause();
},
play: function (file) {
if (this.muted) {
return false;
}
if (!this.audio && this.playing === false) {
this.audio = new Audio(file);
this._ppromis = this.audio.play();
this.playing = true;
if (this._ppromis !== undefined) {
this._ppromis.then(function () {
soundPlayer.playing = false;
});
}
} else if (!this.playing) {
this.playing = true;
this.audio.src = file;
this._ppromis = soundPlayer.audio.play();
this._ppromis.then(function () {
soundPlayer.playing = false;
});
}
}
};
And implement it as follow:
<button onclick="soundPlayer.play('https://interactive-examples.mdn.mozilla.net/media/examples/t-rex-roar.mp3');">Play</button>
I used this method to play a sound...
var audioElement;
if(!audioElement) {
audioElement = document.createElement('audio');
audioElement.innerHTML = '<source src="' + '/audio/sound.mp3'+ '" type="audio/mpeg" />'
}
audioElement.play();
If you want to be able to play the sound even when the browser-tab is currently not selected, you have to load the audio-resource on page load.
Like so:
var audio = new Audio('audio/path.mp3');
function playSound(){
audio.play();
}
See this question for more detail
if you want to play your audio whenever the page is opened then do like this.
<script>
function playMusic(){
music.play();
}
</script>
<html>
<audio id="music" loop src="sounds/music.wav" autoplay> </audio>
</html>
and call this playMusic() whenever you need in your game code.
You can use Web Audio API for playing sounds. There are quite some audio libraries out there like howler.js, soundjs etc. If you don't worry about old browsers then you can also check on http://musquitojs.com/. It provides a simple API to create and play sounds.
For example, to play a sound all you've to do is.
import $buzz from 'musquito';
const buzz = $buzz('gunfire.mp3');
buzz.play();
The library also supports Audio Sprites.
This is some JS i came up with on a baby AI project im working with. i hope this is able to help you out.
<!DOCTYPE html>
<html>
<head>
<title>
js prompt AI
</title>
<style>
#button {
border: 1px solid black;
border-radius: 10px;
font-size: 22px;
height:65px;
width:100px;
text-align: center;
line-height: 65px;
}
</style>
</head>
<body>
<audio id="myAudio" src="./how_are_you.m4a"></audio>
<p>To Interact with the AI please click the button</p>
<div id=button>click</div>
<script>
var button = document.getElementById("button");
function playBack() {
button.addEventListener("click", function (){
var talk = prompt("If you wish for the AI to respond type hi");
var myAudio = document.getElementById("myAudio");
if(talk === "hi") {
myAudio.play();
}
}) ;
}
playBack();
</script>
</body>
</html>
Just use this:
<video controls="" autoplay="" name="media"><source src="Sound URL Here" type="audio/mpeg" /></video>
Or, to make it simpler:
<video controls="" autoplay="" name="media">
<source src="Sound URL Here" type="audio/mpeg" />
</video>
Sample:
<video controls="" autoplay="" name="media">
<source src="https://interactive-examples.mdn.mozilla.net/media/examples/t-rex-roar.mp3" type="audio/mpeg">
</video>
Have NO IDEA if this works on other browsers other than Chrome 73!!
const playAudio = (path) => {
new Audio(path ?? 'defaultPath').play()
}
playAudio('path')`
I had some issues with playing audio, especially since Chrome has updated that the user has to interact with the document first.
However, across almost all solutions I found is that the JS code has to actively set listeners (e.g. button clicks) to receive user events in order to play the audio.
In my case I just wanted my game to play BGM as soon as the player interacts with it, so I made myself a simple listener that keeps checking whether the web page is being interacted or not.
const stopAttempt = setInterval(() => {
const audio = new Audio('your_audio_url_or_file_name.mp3');
const playPromise = audio.play();
if (playPromise) {
playPromise.then(() => {
clearInterval(stopAttempt)
}).catch(e=>{
console.log('' + e);
})
}
}, 100 )
Here is a solution for the year 2020 when you are seeing the error:
[Error] Unhandled Promise Rejection: NotSupportedError: The operation is not supported.
(anonymous function)
rejectPromise
play
(anonymous function) (testaudio.html:96)
dispatch (jquery-3.4.1.min.js:2:42577)
<div onclick="new Audio('/assets/test.mp3').play()">aaa</div>
Don't be slick and think ooh that's an old school oclick, I'll just move that down the page to my jQuery or my external JavaScript file. Nope. It needs to be an onclick.
In react, you can use ref:
// typescript
const audRef = useRef(null);
const playAudio = () => {
(audRef.current as any).play();
}
...
// html
<audio controls src={your_audio} ref={audRef} />
<button onClick={playAudio}>Play</button>
I've tried a code that I found here on this website, but for some reason it won't work. Hope someone here could help. It plays the song when I click the gif, but when I click the gif again, it just replays it.
Here's the code I used:
<img src="lilgif.gif" alt="Play Button" onclick="StartOrStop('boss.mp3')">
<audio id="myAudio"></audio>
Script:
function StartOrStop(audioFile) {
var audio = document.getElementById("myAudio");
if (!audio.src || audio.src !== audioFile) audio.src = audioFile;
if (audio.paused == false)
audio.pause();
else
audio.play();
}
Have this working example I made:
workign audio play pause on image
HTML:
<img id="startOrStopImg" src="http://wallpaper-gallery.net/images/dope-pictures/dope-pictures-17.jpg" alt="Play Button">
<audio id="audio" src="http://www.soundjig.com/pages/soundfx/futuristic.php?mp3=scifi21.mp3" type="audio/mp3" controls>
Your browser does not support the audio element.
</audio>
You can use with controls or without if you prefer to only interact with picture. Don't forget, older browsers don't have HTML5 audio, you should always place a text, image or something to tell user where is the problem. Good thing you did so with image (that one is in case image is broken or accessibility options enabled in browser)
Nothing special here only I put some ids for easy orientation and real file you can test on hosted remotely.
JS:
document.getElementById("startOrStopImg").onclick = function() {
var audio = document.getElementById("audio");
if (audio.paused) audio.play();
else audio.pause();
};
Basically, I bound function defensively (this is prefered to in HTML onclick binding) and written an anon function to handle it all as a value, since I am not using it elsewhere.
It simply accesses audio elements API to check if playing then either plays or pauses.
EDIT: I have fixed and put a remotely hosted image also for a complete example. Looks way better now.
can you enclose your if else statement in curly brackets please
like this.
if (audio.paused == false){
audio.pause();
}else{
audio.play();
}
I am trying to figure out how to continuously play random audio sound bites, one after another without having them overlap on an HTML page using jquery. I have code that plays random sound bites on a timer, but sometimes they overlap and sometimes there is a pause in between the sounds. I had looked into ended and other EventListeners but I really have no idea what I am doing. Here is a portion my code:
<html>
<audio id="audio1">
<source src="cnn.mp3"></source>
</audio>
<audio id="audio2">
<source src="sonycrackle.mp3"></source>
</audio>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('audio').each(function(){
this.volume = 0.6;
});
var tid = setInterval(playIt, 2000);
});
function playIt() {
var n = Math.ceil(Math.random() * 2);
$("#audio"+n).trigger('play');
};
Is there a way to just continuously play these sounds bites one after another right after the previous sound plays? FWIW I have many sound bites but I am just showing two above for reference.
So I dabbled a bit, here's a full pure JavaScript solution.
Should be cross-browser, haven't tested (/lazy). Do tell me if you find bugs though
var collection=[];// final collection of sounds to play
var loadedIndex=0;// horrible way of forcing a load of audio sounds
// remap audios to a buffered collection
function init(audios) {
for(var i=0;i<audios.length;i++) {
var audio = new Audio(audios[i]);
collection.push(audio);
buffer(audio);
}
}
// did I mention it's a horrible way to buffer?
function buffer(audio) {
if(audio.readyState==4)return loaded();
setTimeout(function(){buffer(audio)},100);
}
// check if we're leady to dj this
function loaded() {
loadedIndex++;
if(collection.length==loadedIndex)playLooped();
}
// play and loop after finished
function playLooped() {
var audio=Math.floor(Math.random() * (collection.length));
audio=collection[audio];
audio.play();
setTimeout(playLooped,audio.duration*1000);
}
// the songs to be played!
init([
'http://static1.grsites.com/archive/sounds/background/background005.mp3',
'http://static1.grsites.com/archive/sounds/background/background006.mp3',
'http://static1.grsites.com/archive/sounds/background/background007.mp3'
]);
Some quick suggestions is add the attribute preload="auto" to the audio element and change the script to be $(window).onload instead of document ready. Document ready fires when html is in place but not necessarily when audio and other assets (like images) have loaded.
You could also look into using the AudioBuffer Interface in the new Web Audio API, it's described as "this interface represents a memory-resident audio asset (for one-shot sounds and other short audio clips)." which sounds like what you need. I believe part of the issues you're having (random pauses/delays/sound glitches with the audio element) are one of the reasons why it's being developed.
Read more here:
https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html#AudioBuffer
Unfortunately it's only Chrome and lastest Safari supported with Firefox support supposedly in the next 6(ish) months and no word yet on IE support.