Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pause all other players besides activated one. jQuery audio plugin for <audio> element

I've got this plugin which applies different style to html5 <audio> element and provides flash fallback to browsers that don't support .mp3 file format. Problem I encountered is that once you start playing one song, and then click play on any other song, all of them will play at the same time, which is bad user experience.

I was trying to figure out how to edit plugin to make it only play one song at a time, so say if user listens to one song and then click play on other, first one should pause, and so on. I'm not entirely sure, but I think something need's to be edited along these lines:

    playPause: function() {
      if (this.playing) this.pause();
      else this.play();
    },

However, there are various places in the plugin which seem to deal with playing and pausing song, so I'm not sure that this is exact correct line for this. I'm still very new to jQuery, and can't entirely figure out how this big audio library works, I've been reading through code comment's , but still am unable to figure this out.

Full code of the plugin is available here: http://freshbeer.lv/mg/js/audio.min.js

Official plugin website: http://kolber.github.io/audiojs/

You can visit my demo page to see the issue, just click play on several players and you will see that they all play at the same time: http://freshbeer.lv/mg/index.html

like image 393
Ilja Avatar asked Mar 25 '23 08:03

Ilja


1 Answers

Use the addEventListener and the play event. This pauses all players except the one that the play button has been pressed on.

        audiojs.events.ready(function () {
            var as = audiojs.createAll();

            $('audio').each(function () {
                var myAudio = this;
                this.addEventListener('play', function () {
                    $('audio').each(function () {
                        if (!(this === myAudio)) {
                            this.pause();
                        }
                    });
                });
            });
        });
like image 80
atreeon Avatar answered Apr 05 '23 23:04

atreeon