HTML5 Audio stop function

312,719

Solution 1

Instead of stop() you could try with:

sound.pause();
sound.currentTime = 0;

This should have the desired effect.

Solution 2

first you have to set an id for your audio element

in your js :

var ply = document.getElementById('player');

var oldSrc = ply.src;// just to remember the old source

ply.src = "";// to stop the player you have to replace the source with nothing

Solution 3

I was having same issue. A stop should stop the stream and onplay go to live if it is a radio. All solutions I saw had a disadvantage:

  • player.currentTime = 0 keeps downloading the stream.
  • player.src = '' raise error event

My solution:

var player = document.getElementById('radio');
player.pause();
player.src = player.src;

And the HTML

<audio src="http://radio-stream" id="radio" class="hidden" preload="none"></audio>

Solution 4

Here is my way of doing stop() method:

Somewhere in code:

audioCh1: document.createElement("audio");

and then in stop():

this.audioCh1.pause()
this.audioCh1.src = 'data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEAVFYAAFRWAAABAAgAZGF0YQAAAAA=';

In this way we don`t produce additional request, the old one is cancelled and our audio element is in clean state (tested in Chrome and FF) :>

Solution 5

This method works:

audio.pause();
audio.currentTime = 0;

But if you don't want to have to write these two lines of code every time you stop an audio you could do one of two things. The second I think is the more appropriate one and I'm not sure why the "gods of javascript standards" have not made this standard.

First method: create a function and pass the audio

function stopAudio(audio) {
    audio.pause();
    audio.currentTime = 0;
}

//then using it:
stopAudio(audio);

Second method (favoured): extend the Audio class:

Audio.prototype.stop = function() {
    this.pause();
    this.currentTime = 0;
};

I have this in a javascript file I called "AudioPlus.js" which I include in my html before any script that will be dealing with audio.

Then you can call the stop function on audio objects:

audio.stop();

FINALLY CHROME ISSUE WITH "canplaythrough":

I have not tested this in all browsers but this is a problem I came across in Chrome. If you try to set currentTime on an audio that has a "canplaythrough" event listener attached to it then you will trigger that event again which can lead to undesirable results.

So the solution, similar to all cases when you have attached an event listener that you really want to make sure it is not triggered again, is to remove the event listener after the first call. Something like this:

//note using jquery to attach the event. You can use plain javascript as well of course.
$(audio).on("canplaythrough", function() {
    $(this).off("canplaythrough");

    // rest of the code ...
});

BONUS:

Note that you can add even more custom methods to the Audio class (or any native javascript class for that matter).

For example if you wanted a "restart" method that restarted the audio it could look something like:

Audio.prototype.restart= function() {
    this.pause();
    this.currentTime = 0;
    this.play();
};
Share:
312,719

Related videos on Youtube

Alok Jain
Author by

Alok Jain

Hi, I am Alok Jain – an experienced designer and I develop websites. I am a graduate in multimedia sciences and have a major in IT. Designing has always fascinated me, even before I stepped into professional degree. My professional qualification in designing gave me a platform to explore this ocean of gradients, pick and drop, cropping and so on. Professionally, I started in 2003 and by now, I am quite experienced in working with HTML/XHTML, CSS and JavaScript to design interactive web user interface. I am more than comfortable using Photoshop, Illustrator, DreamWeaver, Flash, and ActionScript.

Updated on May 12, 2022

Comments

  • Alok Jain
    Alok Jain about 2 years

    I am playing a small audio clip on click of each link in my navigation

    HTML Code:

    <audio tabindex="0" id="beep-one" controls preload="auto" >
        <source src="audio/Output 1-2.mp3">
        <source src="audio/Output 1-2.ogg">
    </audio>
    

    JS code:

    $('#links a').click(function(e) {
        e.preventDefault();
        var beepOne = $("#beep-one")[0];
        beepOne.play();
    });
    

    It's working fine so far.

    Issue is when a sound clip is already running and i click on any link nothing happens.

    I tried to stop the already playing sound on click of link, but there is no direct event for that in HTML5's Audio API

    I tried following code but it's not working

    $.each($('audio'), function () {
        $(this).stop();
    });
    

    Any suggestions please?

  • Hossein
    Hossein over 9 years
    Best solution for audio streaming
  • Pieter
    Pieter over 9 years
    This is not working in Chrome. The audio element keeps loading audio, which is not what should happen.
  • Alok Jain
    Alok Jain over 9 years
    Same thing is explained by zaki in his answer above, without use of jquery.
  • user3062615
    user3062615 over 9 years
    I didn't experiment with it, but I wasn't sure that his method would work if there were multiple <source> tags.
  • Md. Arafat Al Mahmud
    Md. Arafat Al Mahmud almost 9 years
    well..that will make another network request for the audio source file
  • Abhi
    Abhi over 8 years
    Audio won't play until loaded, and this will cause unwanted delay in playing audio.
  • Alessandro Fazzi
    Alessandro Fazzi over 8 years
    #FlHolder seems a typo for #plHolder
  • Alessandro Fazzi
    Alessandro Fazzi over 8 years
    In reply to @alok-jain comment: I think this answer is completely different from the @zaki 's one. Here we are re-rendering an element in the DOM, in the other answer he's just "blanking" the src attribute of the player.
  • Alessandro Fazzi
    Alessandro Fazzi over 8 years
    In Chrome the <audio> keeps loading also with preload attribute forced to none and the <source>'s src stripped out.
  • Reahreic
    Reahreic over 7 years
    This works, thanks. On a side note i'd love to know why the w3c decided to not include a stop method in the spec.
  • lasec0203
    lasec0203 about 7 years
    function stopAudio(audio) { audio.pause(); this.audioStream.src = ""; } Doing this ended up working for me and removed the speaker icon in Chrome Browser that appears when audio is playing on the page. tested on Chrome Version 59.0.3071.109
  • namikiri
    namikiri almost 7 years
    A nice solution of the problem when playing a stream like internet radio and Firefox repeats the last chunk when pause/play is toggled. Thank you a lot.
  • milesaron
    milesaron about 4 years
    In general, I wouldn't recommend extending prototypes like this. An audio-heavy application may have different stop functions for different cases and messing with prototypes is likely to lead to bugs in the long-term imho
  • BReddy
    BReddy almost 4 years
    This works in Chrome and Firefox. However, in Firefox it results in the following error (in console) [Security Error: Content at https://localhost/url.html may not load data from blob:https://localhost/cac32534-78b0-4a62-8355-cc8f1e708d64.‌​] It appears to have no negative effect as the code continues to execute after this (unlike an uncaught Exception).
  • Said Pc
    Said Pc over 2 years
    thanks this worked perfectly