0

Is there a way that I could play a sound on an event in JavaScript with JavaScript or jQuery? It would be best if it was simple. Here's an example:

function play_song() {
    i = 0;
    b = 1;
    if (b > i) {
        play_sound(beep.mp3);
    }
}

Also, if it's a library, I'm looking for something that would actually work into JS functions, not any HTML. Thanks.

Jack Davis
  • 81
  • 1
  • 8

1 Answers1

1

I found this way:

<div id="sound_element">
    <embed src=sound_file_url hidden=true autostart=true loop=false>   
</div>

With javascript:

document.getElementById("sound_element").innerHTML= 
    "<embed src='"+sound_file_url+"' hidden=true autostart=true loop=false>";

There're even easier ways with HTML5.

But please don't use it in sites I use, thanks.

gdoron
  • 147,333
  • 58
  • 291
  • 367
  • Firefox doesn't support mp3 playback in HTML5 `audio` tags as far as I remember, so your `embed` is probably better for cross-browser compatibility and older IE versions. – Fabrício Matté Jun 14 '12 at 22:17
  • @FabrícioMatté. It's supported since 3.5 [MDN](https://developer.mozilla.org/en/HTML/Element/audio) I added all the options, choose what you like the most. – gdoron Jun 14 '12 at 22:20
  • Are you 100% sure? I remember testing it after Nightly 15a release and it returned a "mp3 format playback is not supported" (or similar) error in the console (while working perfectly fine on Chrome), that's a little off-topic so I'll post a question if I can't sort it out by myself. – Fabrício Matté Jun 14 '12 at 22:23
  • [Why doesn't Firefox support mp3 file format in – Fabrício Matté Jun 14 '12 at 22:33
  • Can I do this without creating a div? – Jack Davis Jun 15 '12 at 00:44