页面加载,rand变量使歌曲随机化。我希望playagain按钮暂停歌曲并再次调用rand varibale,以便再次随机化歌曲。因此,当我按下播放按钮时,它将播放不同的歌曲。 playagain按钮暂停了歌曲但是rand变量没有再次随机化。有没有办法解决这个问题?
HTML:
<audio id="mytrack" controls>
<source src="Song1.wav" type = "audio/wav"/>
</audio>
<audio id="gd" controls>
<source src="Song2.mp3" type = "audio/mp3"/>
</audio>
<button type="button" id="playButton"></button>
<button type="button" id="playagain"></button>
JavaScript的:
var mytrackJS = document.getElementById('mytrack');
var playButtonJS = document.getElementById('playButton');
var playagainJS = document.getElementById('playagain');
var gdJS = document.getElementById('gd');
var audioPlaying = [mytrackJS, gdJS];
var rand = audioPlaying[Math.floor(Math.random() * audioPlaying.length)];
playButtonJS.addEventListener('click', playOrPause, false);
playagainJS.addEventListener('click', random, false);
function random() {
var rand = [Math.floor(Math.random() * audioPlaying.length)];
playOrPause();
}
function playOrPause() {
if (!rand.paused && !rand.ended){
rand.pause();
playButtonJS.style.backgroundImage = 'url(playbutton.svg)';
}
else{
rand.play();
playButtonJS.style.backgroundImage = 'url(pausebutton.png)';
}
}
答案 0 :(得分:0)
您似乎没有正确地声明变量audioPlaying。你也不需要围绕你的rand声明的audioPlaying []。试试这个:
var audioPlaying = [mytrackJS, gdJS];
var rand = Math.floor(Math.random() * audioPlaying.length);
答案 1 :(得分:0)
由于您初始化 rand 变量一次,因此其值始终保持不变。
要查看预期结果,请将其移至 playOrPause 功能。
function playOrPause() {
var rand = audioPlaying[Math.floor(Math.random() * audioPlaying.length)];
if (!rand.paused && !rand.ended){
rand.pause();
playButtonJS.style.backgroundImage = 'url(playbutton.svg)';
} else{
rand.play();
playButtonJS.style.backgroundImage = 'url(pausebutton.png)';
}
}
答案 2 :(得分:0)
我不确定这是否是您正在寻找的内容,但我不会在两个不同的audio
元素之间进行选择,而只会更改单个src
属性一。这样,您可以拥有一组文件名,并从使用array[Math.random()*array.length]