2015-11-03 111 views
1

我有這段代碼讓我們點擊圖片(聲音不在下面的代碼上工作,但它在我的網站上工作)時播放一首音樂,並暫停音樂我再次點擊它。播放我的播放列表中的隨機音樂onclick圖片

我的疑問是,每次有人進入我的網站並單擊圖像時,如何從我的var sounds播放列表中加載隨機音樂?

在此先感謝。

<script> 
 
    var sounds = [ 
 
\t "http://www.vtxfactory.com/sounds/royksopp.mp3", 
 
\t "http://www.vtxfactory.com/sounds/9thwonder.mp3", 
 
\t "http://www.vtxfactory.com/sounds/thisbeat.mp3", 
 
\t "http://www.vtxfactory.com/sounds/mosdef.mp3", 
 
\t "http://www.vtxfactory.com/sounds/oizo.mp3", 
 
\t "http://www.vtxfactory.com/sounds/dilla.mp3",]; 
 
\t 
 
\t function StartOrStop(audioFile) { 
 
     
 
\t \t var audie = document.getElementById("myAudio"); 
 
     if (!audie.src || audie.src !== audioFile) audie.src = audioFile; 
 
     console.log(audie.paused); 
 
     if (audie.paused == false) { 
 
      console.log('pause'); 
 
      audie.pause(); 
 
     } else { 
 
      console.log('play'); 
 
      audie.play(); 
 
     } 
 
    } 
 
</script>
<img src="http://vtxfactory.com/images/vtxfactorylogobw.png" onclick="StartOrStop('http://www.vtxfactory.com/sounds/oizo.mp3')" class="spin" align="left" onmouseover="this.src='http://vtxfactory.com/images/vtxfactorylogocolor.png'" onmouseout="this.src='http://vtxfactory.com/images/vtxfactorylogobw.png'" onmousedown="this.src='http://vtxfactory.com/images/vtxfactorylogocolor.png'" onmouseup="this.src='http://vtxfactory.com/images/vtxfactorylogobw.png'" width="165px" height="190px" > 
 
<audio id="myAudio"></audio>

回答

0

這工作

<script> 
    var sounds = [ 
     "http://www.vtxfactory.com/sounds/royksopp.mp3", 
     "http://www.vtxfactory.com/sounds/9thwonder.mp3", 
     "http://www.vtxfactory.com/sounds/thisbeat.mp3", 
     "http://www.vtxfactory.com/sounds/mosdef.mp3", 
     "http://www.vtxfactory.com/sounds/oizo.mp3", 
     "http://www.vtxfactory.com/sounds/dilla.mp3" 
    ]; 

    function StartOrStop(audioFile) { 
     var audie = document.getElementById("myAudio"); 
     if (audie.paused) { 
      audie.src = sounds[Math.floor(Math.random() * sounds.length)]; 
      audie.play(); 
     } else { 
      audie.pause(); 
     } 
    } 
</script> 

<img src="http://vtxfactory.com/images/vtxfactorylogobw.png" onclick="StartOrStop()" class="spin" align="left" onmouseover="this.src = 'http://vtxfactory.com/images/vtxfactorylogocolor.png'" onmouseout="this.src = 'http://vtxfactory.com/images/vtxfactorylogobw.png'" onmousedown="this.src = 'http://vtxfactory.com/images/vtxfactorylogocolor.png'" onmouseup="this.src = 'http://vtxfactory.com/images/vtxfactorylogobw.png'" width="165px" height="190px" > 
<audio id="myAudio"></audio> 
+0

它的工作!感謝:D –

0

您只需創建一個getter函數來實現這一目標。

function getRandom (arr) { 
    var rand = Math.floor(Math.random() * (arr.length - 1)) + 0; 
    return arr[rand]; 
} 

audie.src = getRandom(sounds); 
audie.play(); 
0

取下功能StartOrStop的參數,將其添加爲音頻源

audie.src = sounds[Math.floor(Math.random()*sounds.length)];