Несколько экземпляров аудиоплеера jQuery HTML5 - PullRequest
3 голосов
/ 26 марта 2012

Я создал собственный аудиоплеер HTML5 с использованием jQUery в соответствии с руководством, найденным здесь: http://neutroncreations.com/blog/building-a-custom-html5-audio-player-with-jquery/

Мой сценарий выглядит следующим образом:

    jQuery(document).ready(function() {

        audio = jQuery('div#artificial-brothers audio').get(0);
        loadingIndicator = jQuery('div#artificial-brothers #loading');
        positionIndicator = jQuery('div#artificial-brothers #handle');
        timeleft = jQuery('div#artificial-brothers #timeleft');

        if ((audio.buffered != undefined) && (audio.buffered.length != 0)) {
            jQuery(audio).bind('progress', function() {
                var loaded = parseInt(((audio.buffered.end(0) / audio.duration) * 100), 10);
                loadingIndicator.css({width: loaded + '%'});
            });
        } else {
            loadingIndicator.remove();
        }

        jQuery(audio).bind('timeupdate', function() {

            var rem = parseInt(audio.duration - audio.currentTime, 10),
                    pos = (audio.currentTime / audio.duration) * 100,
                    mins = Math.floor(rem/60,10),
                    secs = rem - mins*60;

            timeleft.text('-' + mins + ':' + (secs < 10 ? '0' + secs : secs));
            //if (!manualSeek) { 
                positionIndicator.css({width: pos + '%'});
            // }
            //if (!loaded) {
            //  loaded = true;

            jQuery('div#artificial-brothers #gutter').slider({
                value: 0,
                step: 0.01,
                orientation: "horizontal",
                range: "min",
                max: audio.duration,
                animate: true,          
                slide: function() {             
                    manualSeek = true;
                },
                stop:function(e,ui) {
                    manualSeek = false;         
                    audio.currentTime = ui.value;
                }
            });

        }).bind('play',function(){
            jQuery('div#artificial-brothers #playtoggle').addClass('playing');      
        }).bind('pause ended', function() {
            jQuery('div#artificial-brothers #playtoggle').removeClass('playing');       
        });     

        jQuery('div#artificial-brothers #playtoggle').click(function() {            
            if (audio.paused) { audio.play();   } 
            else { audio.pause(); }         
        });

        jQuery('div#artificial-brothers #stoptoggle').click(function() {            
            if (audio.play) {   audio.pause();  } 
            audio.currentTime = 0;      
        });
});

Моя проблема в том, что мне нужно запустить несколько экземпляров указанного игрока на одной странице, и я не могу этого добиться. Я попытался скопировать / вставить скрипт и изменить идентификатор (искусственные братья), но тогда только скрипт, написанный в последний раз, будет работать. Любые идеи о том, как позвонить игроку более одного раза на странице, были бы великолепны!

// Каспер

РЕДАКТИРОВАТЬ: Согласно информации, предоставленной @charlieftl, мой код теперь выглядит так:

jQuery(document).ready(function() {

    jQuery('.player').each(function(){

        var container = jQuery(this);
        var audio = container.find('audio').get(0);
        var loadingIndicator = container.find('.loading');
        var positionIndicator = container.find('.handle');
        var slider = container.find('.gutter');
        var timeleft = container.find('.timeleft');

        if ((audio.buffered != undefined) && (audio.buffered.length != 0)) {
            jQuery(audio).bind('progress', function() {
                var loaded = parseInt(((audio.buffered.end(0) / audio.duration) * 100), 10);
                loadingIndicator.css({width: loaded + '%'});
            });
        } else {
           loadingIndicator.remove();
        }

        jQuery(audio).bind('timeupdate', function() {

            var rem = parseInt(audio.duration - audio.currentTime, 10),
                    pos = (audio.currentTime / audio.duration) * 100,
                    mins = Math.floor(rem/60,10),
                    secs = rem - mins*60;

            timeleft.text('-' + mins + ':' + (secs < 10 ? '0' + secs : secs));
            //if (!manualSeek) { 
                positionIndicator.css({width: pos + '%'});
            // }
            //if (!loaded) {
            //  loaded = true;

            slider.slider({
                value: 0,
                step: 0.01,
                orientation: "horizontal",
                range: "min",
                max: audio.duration,
                animate: true,          
                slide: function() {             
                    manualSeek = true;
                },
                stop:function(e,ui) {
                    manualSeek = false;         
                    audio.currentTime = ui.value;
                }
            });
        });

        container.find('.playtoggle').click(function() {            
            if (audio.paused) { audio.play();   } 
            else { audio.pause(); }         
        });

        container.find('.stoptoggle').click(function() {            
            if (audio.play) {   audio.pause();  } 
            audio.currentTime = 0;      
        });

        jQuery(audio).bind('play',function(){
            container.find('.playtoggle').addClass('playing');      
        });

        jQuery(audio).bind('pause ended', function() {
            container.find('.playtoggle').removeClass('playing');       
        }); 
    });

});

1 Ответ

0 голосов
/ 26 марта 2012

Судя по использованию селекторов jQuery, я подозреваю, что вы повторяете идентификаторы элементов на своей странице. Идентификаторы должны быть уникальными, поэтому большинство ваших селекторов должны отражать только фактический идентификатор элемента. Когда элемент имеет идентификатор, нет никакой причины запускать селектор на более высоком уровне ... сам идентификатор является наиболее эффективным из доступных селекторов

Из вашего кода:

    jQuery('div#artificial-brothers #loading');

Должно быть:

    jQuery('#loading');

Чтобы обойти вашу проблему, вам нужно вместо этого заменить повторяющиеся идентификаторы на класс. Оберните каждый HTML-экземпляр вашего аудио в контейнер с общим классом

   <div class="audio_wrap">
      <!--All html associated with a single audio-->
    </div>

Теперь вы можете перебрать все эти экземпляры, используя $.each. Внутри цикла вы всегда ищете только элементы в этом экземпляре.

Следующее не является полной перепиской всего вашего кода, но достаточно для примера, чтобы установить шаблон, который позволит вам сохранять экземпляры изолированными друг от друга

    $('.audio_wrap').each(function(){

            /* cache the container instance in a variable*/
            var $container=$(this);
            /* searching within the container instance for each 
            component insulates multiple instances on page*/

            var $audio= $container.find('audio');
            var $slider=$container.find('.sliderClass');

            /*now events will only be bound to this instance*/ 
            $audio.bind('play',function(){
                /* within event callbacks keep searches within the main container element*/                     
                $container.find('.playtoggleClass').addClass('playing'); 

            });
    });
...