Adding sound to page using jquery

crazyDiamond picture crazyDiamond · Nov 28, 2011 · Viewed 7.9k times · Source

What is the preferred method to add sound to a page using jquery?

I am considering using jPlayer but have my doubts about it. Depending on the messages being displayed on the screen, I need to customize the sound.

Thanks in advance.

Answer

Meisam Mulla picture Meisam Mulla · Nov 28, 2011

Personally I find random audio on a website really annoying but here you go:

<audio>
        <source src="audio/audio.mp3"></source>
        <source src="audio/audio.ogg"></source>
        HTML5 Needed
</audio>

<script>
    var audio = $("audio")[0];
    audio.play();
</script>

or something like:

$("<audio></audio>").attr({
    'src':'audio/something.mp3',
    'volume':0.4,
    'autoplay':'autoplay'
}).appendTo("body");

Both these examples use HTML5 but with small modifications you can use flash to play the audio.