我试图在同一页面上创建两个音频播放器。我已经看过类似的question,它建议,"过滤每个音频元素和音频值的任务,"但是我的播放器与那个问题中的播放器是如此不同,以至于我不确定如何将它应用到我的播放器中。
每当我尝试播放第一个播放器时,第二个播放器会启动,如果我开始点击则会中断。两个播放器的脚本都在不同的文件中,我已经更改了ID,因此没有重复,我也尝试更改变量和函数名称,认为它们可能会产生一些影响。没有任何效果。
我为每个玩家使用相同的代码,但每个ID都有不同的前缀:
/* global $ */
var audio;
//Hide Pause
$('#pause').hide();
initAudio($('#playlist').find('li:first-child'));
$('#playlist').on('click', function(event) {
initAudio($(event.target));
});
// Initiate play sequence
function initAudio(element){
var recording = element.attr('data-id');
var title = element.text();
var artist = element.attr('data-artist');
//Create audio object
audio = new Audio('public/audio_files/'+ recording);
//Insert audio info
$('.artist').text(artist);
$('.title').text(title);
$('#playlist li').removeClass('active');
element.addClass('active');
// Set timer to 0
$('#duration').html('0:00');
// Maintain volume on song change
audio.volume = $('#volume').val() / 100;
}
//Play button
$('#play').click(function() {
audio.play();
showPause();
showDuration();
});
//Pause button
$('#pause').click(function() {
audio.pause();
showPlay();
});
//Next button
$('#next').click(function() {
audio.pause();
var next = $('#playlist li.active').next();
if(next.length == 0){
next = $('#playlist li:first-child');
}
showPause();
initAudio(next);
audio.play();
showDuration();
});
//Prev button
$('#prev').click(function() {
audio.pause();
var prev = $('#playlist li.active').prev();
if(prev.length == 0){
prev = $('#playlist li:last-child');
}
showPause();
initAudio(prev);
audio.play();
showDuration();
});
//Playlist song click
$('#playlist li').click(function() {
audio.pause();
initAudio($(this));
showPause();
audio.play();
showDuration();
});
//Volume control
$('#volume').change(function() {
audio.volume = parseFloat(this.value / 100);
});
// Show play button, hide pause
function showPlay() {
$('#play').show();
$('#pause').hide();
}
// Show pause button, hide play
function showPause() {
$('#play').hide();
$('#pause').show();
}
// Automatically play next song
function autoPlayNext() {
if(audio.currentTime == audio.duration) {
var next = $('#playlist li.active').next();
if(next.length == 0){
next = $('#playlist li:first-child');
}
showPause();
initAudio(next);
audio.play();
showDuration();
}
}
// Time/Duration
function showDuration() {
$(audio).bind('timeupdate', function() {
//Get hours and minutes
var s = parseInt(audio.currentTime % 60, 10);
var m = parseInt(audio.currentTime / 60, 10) % 60;
if(s < 10) {
s = '0' + s;
}
$('#duration').html(m + ':'+ s);
var value = 0;
if(audio.currentTime > 0){
value = Math.floor((100 / audio.duration) * audio.currentTime);
}
$('#progress').css('width', value + '%');
autoPlayNext();
});
}
// Skip time via progress bar click
$('#progress-bar').bind('click', function (e) {
var $div = $(e.target);
var offset = $div.offset();
var x = e.clientX - offset.left;
audio.currentTime = ((x / 2.3)/(100 / audio.duration)); /* length of progress-bar is 230px hence (x/2.3) */
});
有什么见解?