Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play a JavaScript sound file without a delay

I have a HTML5 canvas game with sounds, but one of the problems that I am running into is that when the sound is played, all other action stops until the sound has finished playing. I used this code

document.getElementById("music").innerHTML="<embed src=\""+surl+"\" hidden=\"true\" autostart=\"true\" loop=\"false\" />"


Where surl is the url of the sound and music of the span element that is playing the music. Does anyone know how to play a sound without delaying the entire program?


I tried it with a considerably larger file, and it turns out that while it DOES play in the background, there is still a considerable delay between starting the sound and continuing the game.

like image 833
scrblnrd3 Avatar asked Feb 26 '13 00:02

scrblnrd3


1 Answers

Try using the native HTML5 Audio API. First, create the instances of the sounds you will need:

var ping = new Audio("ping.ogg");

Note: You do not need to insert these audio instances into the DOM at any point.

When you're ready to play the sound, e.g. when someone clicks:

document.querySelector(".ping").addEventListener("click", function() {

    // ping clicked, play ping sound:
    ping.play()
})

Because the ping instance is pre-loaded there should be no delay in playing the sound, and you can play it as many times as you like.

Keep in mind that codec support is not consistent cross-browser, so you will have to have an ogg source and an MP3 source, or another combination (support tables can be found here http://en.wikipedia.org/wiki/HTML5_Audio#.3CAudio.3E_element_format_support).

If you want a more backwards-compatible approach I recommend SoundManager2 as a complete solution with an easy API: http://www.schillmania.com/projects/soundmanager2/

Otherwise, the documentation for the native HTML5 Audio API can be found here: https://developer.mozilla.org/en-US/docs/HTML/Element/audio and here https://developer.mozilla.org/en-US/docs/DOM/HTMLAudioElement

like image 60
Luke Channings Avatar answered Nov 03 '22 01:11

Luke Channings