2015-01-17 3 views
1

저는 html5 및 jQuery를 사용하여 간단한 오디오 플레이어를 만들려고합니다. 하나의 파일/스트림을 재생하거나 다음/미리보기 또는 재생 목록의 다른 파일을 클릭 할 때 잘 작동합니다.html5 및 jQuery로 모든 오디오 소스를 재생하는 방법

하지만 재생 목록의 모든 파일을 자동으로 재생할 수있는 플레이어가 필요합니다. 내가 여기에 코드의 일부 표시 할 수 있습니다

I에 $ .each(), 내가 작업 ... recusive 기능을 시도하지만 성공을 시도

... : 그래서

var el = $('#playerbox'); 
var soundType = el.data('page-soundtype'); 
var soundFile = el.data('page-soundfile'); 
var soundFiles = el.data('page-soundfiles');//playlist, paths to sources 
var audio = $("<audio preload />"); 
//make 2 types of sources for different browsers: 
var source1= $('<source />').attr('type', 'audio/mpeg'); // original, mp3 format 
var source2= $('<source />').attr('type', 'audio/ogg'); // a copy, ogg format 
audio.append(source1).append(source2); 
el.append(audio); 
var player=audio[0]; 
player.volume=0; 
var i=0; //The play list counter, in case we have it 
var op={}; //player options 

var runPlayer = function(op){ 
    var fadetime = (op.fadetime || 1000); 
    player.oncanplay = function(){ 
     player.play(); 
     audio.animate({volume: 1}, fadetime); 
    } 
    if(soundType === 'list'){ 
     player.addEventListener('ended', function(){ 
      i++; 
      if(soundFiles[i].length>0){ 
       source1.attr('src', soundFiles[i]); 
       source2.attr('src', soundFiles[i].replace(".mp3", ".ogg")); 
       op.fadetime = 1500; 
       player.pause(); 
       runPlayer(op); 
      } 
     }, false) 
     } 
} 
//set sources 
if(soundType==='list' && $.isArray(soundFiles)){ 
    //prepare playlist 
    source1.attr('src', soundFiles[i]); 
    source2.attr('src', soundFiles[i].replace(".mp3", ".ogg")); 
    op.fadetime = 1;    
} 
else if(soundType==='sound'){ 
    //prepare sound 
    source1.attr('src', soundFile); 
    source2.attr('src', soundFile.replace(".mp3", ".ogg")); 
} 
runPlayer(op); 

를, 최초의 오디오 소스가 잘 플레이어의 "SRC"에 다음 두 번째 부하를 재생하지만 재생되지 않습니다 :(

어디 내 실수? 감사합니다.

+0

일단 새 소스를 추가했으면 source1.play()를 호출 한 적이 있습니까? –

+0

새 소스를 추가하지 않고 기존 소스의 SRC를

+0

그게 전부입니다. 그래서 일단 src 속성을 업데이트하면, 오디오 요소에 .play()를 호출해야한다고 생각합니다. –

답변

1

새로운 SRC는 당신,로드되면 그 요소 여기

에() .play를 호출 할 것이다 것은 큐

var el = $('#playerbox'); //assuming here that el is your <audio> element 
var audioSources = [song1.mp3, song2.mp3....]// here is your array of filenames 
var index = 0; 

function playNext(index){ 
    el.attr('src', audioSources[index]); 
    el.play(); //this will play the element 
    el.on('ended', function(){ //this will bind a function to the "ended" event 
    //increment the index to target the next element 
    index++; 
    if(index < audioSources.length){ 
     //plays the next song and binds the function to the ended event again until the queue is empty 
     playNext(index);   
    } 
    } 
} 
playNext(index); 

당신을 위해이 일을 하는가에 모든 오디오 파일을 재생하는 방법의 예입니다?

+0

: 재생 목록의 각 요소에

+0

그냥 내 대답을 편집했습니다. 새 버전에서는 질문에 더 적합한 다음

+0

제 생각과 똑같은 일을했습니다. 그러나 그것은 효과가 없습니다. 나는 당신의 샘플을 시도 할 것이지만, 당신은 oncanplay를 사용하지 않는 것이 어떻습니까? –