2017-10-18 61 views
0

我有這樣的代碼,隨機化,並從他們的播放列表中的歌曲:隨機歌曲 - JavaScript的HTML5

var sounds = [ 
     "sounds/royksopp.mp3", 
     "sounds/9thwonder.mp3", 
     "sounds/thisbeat.mp3", 
     "sounds/mosdef.mp3", 
      "sounds/bewater.mp3", 
      "sounds/boutdre.mp3", 
      "sounds/masterflash.mp3", 
      "sounds/2ep.mp3", 
     "sounds/drewestcoast.mp3", 
      "sounds/poetry.mp3", 
      "sounds/mfdoom.mp3", 
     "sounds/dreams.mp3", 
     "sounds/oizo.mp3", ]; 

function StartOrStop(audioFile) { 
    srcAudio = sounds[Math.floor(Math.random() * sounds.length)]; 
    var audie = document.getElementById("myAudio"); 
    audie.addEventListener('ended', function() { 
     this.currentTime = 0; 
     this.play(); 
    }, false); 

    if (audie.paused == false) { 
     audie.pause(); 
    } else { 
     audie.src = srcAudio; 
     audie.play(); 
    } 
} 

當歌曲停止播放,它與第一個相同的重新啓動。我該如何做到這一點,當音樂結束時,它會從我的列表中抓取一首新歌並自動播放它?

回答

1

問題是,您只需在ended事件偵聽器中調用this.play()即可。相反,你應該更新src屬性與歌曲的隨機選擇與this.src = srcAudio,類似於你如何初步選擇:

function StartOrStop(audioFile) { 
    srcAudio = sounds[Math.floor(Math.random() * sounds.length)]; 
    var audie = document.getElementById("myAudio"); 
    audie.addEventListener('ended', function() { 
     this.currentTime = 0; 
     this.src = srcAudio; 
     this.play(); 
    }, false); 

    if (audie.paused == false) { 
     audie.pause(); 
    } else { 
     audie.src = srcAudio; 
     audie.play(); 
    } 
} 

希望這有助於! :)

+0

將'.src'設置爲'else'語句內'audie.src = srcAudio'的目的是什麼? – guest271314

+0

好問題,但它在原代碼中,所以我認爲它是有意的行爲。 –

+0

「終止」處理程序中的'srcAudio'與'else'語句中的'srcAudio'設置相同嗎? – guest271314