Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery to control HTML5 <audio> element

I'm trying to use jQuery to control an HTML5 audio element, but I'm no genius with JS. What I want is for the player to start on page load, which I've done, but when the play button is clicked, I want to check whether or not the audio is playing. If it's playing when clicked: Stop the audio. If it's not playing when clicked: Play the audio.

If you could help, it'd be much appreciated.

Source here: http://www.julake.co.uk/media/loader.php?page=contact

Many thanks,

like image 207
futureslay Avatar asked Mar 06 '12 08:03

futureslay


2 Answers

you should use a single play/pause toggle button in which you need to check if your audio is paused or not

var audioplayer = document.getElementById("audio-player");
$("#play-bt").click(function(){
    if (audioplayer.paused) {
       audioplayer.play();
    }   
    else {
       audioplayer.pause();
    }
    $(this).toggleClass('pause');  /* style your toggle button according to 
                                      the current state */
})
like image 177
Fabrizio Calderan Avatar answered Nov 10 '22 12:11

Fabrizio Calderan


var audio = new Audio("http://www.w3schools.com/html5/song.ogg"); //or you can get it with getelementbyid

audio.addEventListener('canplay', function() {
//code, when audio can play
audio.play(); //this function will start the music
})

with audio.play() function you can start it. You don't need JQuery

like image 21
Danny Fox Avatar answered Nov 10 '22 12:11

Danny Fox