8

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,

3 Answers 3

11

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 */
})
Sign up to request clarification or add additional context in comments.

1 Comment

How is using jQuery lazy? It's there to be used, why can't people use it?
2
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

1 Comment

do you know how to play another song when ended?
2

If you wish to use a jquery selector or have a jquery selector already, you can add [0] to get the native dom element.

So an example that actually uses jquery would be.

$('audio')[0].pause()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.