Search code examples
htmlcontrollerhtml5-audio

HTML5 audio control stop button (as opposed to pause)


I've been absolutely everywhere (I think) and can't seem to find a way to call a stop event in an html5 audio controller. My audio controller has a playlist where each track will play when selected or cycle through each track to the next. There's also a next button which works.

My play/pause button looks like this:

function playPause() {
    var audioPlayer = document.getElementsByTagName('audio')[0];
    if(audioPlayer!=undefined) {
        if (audioPlayer.paused) {
            audioPlayer.play();
        } else {
            audioPlayer.pause();
        }
    } else {
        loadPlayer();
    }
}

I need a "Stop" button that stops the audio and goes back to the beginning of the track currently being played. I thought about using the current playback postion somehow, but can't get my head around that.

I've also tried this (adapted by advice here in another question), to no avail:

function stop() {
    var audioPlayer = document.getElementsByTagName('audio');
    addEventListener('loadedmetadata', function() {
        this.currentTime = 0;
    }, false);
}

Any ideas?


Solution

  • If your play/pause is working, this should work for stop:

    function stop() {
        var audioPlayer = document.getElementsByTagName('audio')[0];
        audioPlayer.pause();
        audioPlayer.currentTime = 0;
    }