Play audio onHover with jQuery


The simplest way to play audio files in your page without the need of flash is the usage of HTML5 tag <audio> as follow:

<audio autoplay="autoplay" controls="controls" loop="loop" preload="preload">
        <source src="beep.ogg" type="audio/ogg">
        <source src="beep.mp3" type="audio/mpeg">Your Browser doesn't support audio

For our example we only need the attributes “autoplay” and the two tags “source” to define the url of the audio files. Just like this:

<audio autoplay="autoplay">
        <source src="beep.ogg" type="audio/ogg">
        <source src="beep.mp3" type="audio/mpeg">

Now we let jQuery take over by embedding the html code for all <a> tags whenever onMouseOver is done:

    var audioFileName = "beep";
    var mp3File = audioFileName + ".mp3";
    var oggFile = audioFileName + ".ogg";

    $('body').append('<div id="audio" style="position:absolute; top:-200px;"></div>');
        $('#audio').html('<audio autoplay="autoplay">'+
        '<source src="' + oggFile + '" type="audio/ogg">'+
        '<source src="' + mp3File + '" type="audio/mpeg"></audio>');
    function(){ });

Thats it!

DEMO: Check the upper menu of this page to hear how it works

Useful Links:

Convert mp3 to ogg online

Free Mp3 sound effects

HTML5 audio tag generator