"转换"在jQuery中有一个多轨道的音频播放器

时间:2015-06-18 00:21:35

标签: javascript jquery audio

我有一个跟踪列表,我想只用一个播放和暂停按钮来预览3首歌曲。

这是我现在在JS中的凌乱片段:

$(".social").on({
    mouseenter: function () {
        $(this).data("original-src", $(this).attr("src"))
            .stop(true, true).fadeOut(250, function () {
            $(this).attr("src", $(this).attr("data-src"));
        }).fadeIn(250);
    },
    mouseleave: function () {
        $(this).stop(true, true).fadeOut(250, function () {
            $(this).attr("src", $(this).data("original-src"));
        }).fadeIn(250);
    }
});

对于HTML中的每首曲目:

var playing = false;
playpause01.addEventListener('click', function () {
    if (!playing) {
        document.getElementById('player01').play();
        this.src = 'files/img/pause.png';
    } else {
        document.getElementById('player01').pause();
        this.src = 'files/img/play.png';
    }
    playing = !playing;
});
playpause04.addEventListener('click', function () {
    if (!playing) {
        document.getElementById('player04').play();
        this.src = 'files/img/pause.png';
    } else {
        document.getElementById('player04').pause();
        this.src = 'files/img/play.png';
    }
    playing = !playing;
});
playpause13.addEventListener('click', function () {
    if (!playing) {
        document.getElementById('player13').play();
        this.src = 'files/img/pause.png';
    } else {
        document.getElementById('player13').pause();
        this.src = 'files/img/play.png';
    }
    playing = !playing;
});

现在,此代码段有两个问题: 1)我需要单独定位3个不同的元素(对于我要预览的每首歌) 2)如果我在播放一首新歌时播放2首歌曲重叠。

我认为在jQuery中重写代码片段会容易得多。我怎么能解决这两个问题?

这里是开始的JsFiddle: http://jsfiddle.net/multiformeingegno/jdk0b5L4/

1 个答案:

答案 0 :(得分:0)

您可以使用这样的常见侦听器:

$('ol').on('click', 'li img', playAudio);
var currentlyPlaying;
function playAudio(e){
    var audElement = $(e.target).siblings('audio')[0];
    window.aa = audElement;
    if(audElement && audElement.paused){
        if(currentlyPlaying)
            currentlyPlaying.pause();            
        currentlyPlaying = audElement;
        addListeners(currentlyPlaying);
        currentlyPlaying.play();            
    }else if(audElement){
        audElement.pause();
    }
}

function addListeners(aud){
    aud.removeEventListener('ended', onPause);  // remove done to remove previous listener
    aud.removeEventListener('pause', onPause);
    aud.removeEventListener('playing', onPlay);
    aud.addEventListener('ended', onPause);
    aud.addEventListener('pause', onPause);
    aud.addEventListener('playing', onPlay);
}

function onPlay(e){
    $(e.target).siblings('img')[0].src = 'http://luca-longobardi.com/files/img/pause.png';
}
function onPause(e){
    e.target.currentTime = 0;   // reset to beginning
    $(e.target).siblings('img')[0].src = 'http://luca-longobardi.com/files/img/play.png';
}

fiddle demo