Search code examples
javascriptjqueryaudiomp3html5-audio

Javascript: How to pause/stop currently playing audio?


I have the following code to play audio on my website. The problem is playing audio does not stop or pause to play a new one. All the files are playing together like crazy.

$().ready(function () {
    PlayMp3('sounds/file1.mp3');
    PlayMp3('sounds/file2.mp3');
    PlayMp3('sounds/file3.mp3');
    PlayMp3('sounds/file4.mp3');
});
    function PlayMp3(file) {
            var isiPad = navigator.userAgent.match(/iPad/i) != null;
            var isiPhone = navigator.userAgent.match(/iPhone/i) != null;
            var isiPod = navigator.userAgent.match(/iPod/i) != null;
            pauseAllAudio();

            if (navigator.userAgent.indexOf("Firefox") != -1) {
                file = file.replace("mp3", "ogg");            
                $('#content').append('<audio src="' + file + '" controls preload="auto" autobuffer autoplay="autoplay" style="display:none"></audio>');
            }
            else if (isiPad || isiPhone || isiPod) {           
                var snd = new Audio(file);
                snd.load();
                snd.play();            
            }
            else {
                $('#content').append('<embed height="0" width="0" src="' + file + '">');
            }


        }

        function pauseAllAudio() {
            $('video, audio').each(function () {
                $(this)[0].pause();
            });
            var allAudioEls = $('audio');
            allAudioEls.each(function () {
                var a = $(this).get(0);
                a.pause();
            });

            $('audio').remove();
            if (snd != undefined) {
                snd.pause();
            }
        }

This is not a duplicate question. I have tried all solutions from similar questions here and none of the solutions works for me. Thanks.


Solution

  • Thanks to Praveen Kumar. Without him, I couldn't have found the problem to remove 'embed'. After adding $('embed').remove(); to function pauseAllAudio(). It solves for all browsers but Firefox. That firefox doesn't like mp3 or <embed> tag. I had to do some more research to make it work for only that browser.

    jPlayer looks great and it solves my problem. The solution is as follow.

     function PlayMp3(file) {
        $('embed').remove();
        if (navigator.userAgent.indexOf("Firefox") != -1) {
                file = file.replace("mp3", "ogg");
                $('#jquery_jplayer').jPlayer("pauseOthers");
                $('#jquery_jplayer').jPlayer("setMedia", { oga: file });
                $('#jquery_jplayer').jPlayer("play");
        }
        else {
            $('#content').append('<embed height="0" width="0" src="' + file + '">');
    }
    

    I had to give up on HTML 5 <audio> tag. :(