[英]How to get a random song to play using an array in javascript?
The page loads and the rand variable randomizes the song. 页面加载,rand变量使歌曲随机化。 I want the playagain button to pause the song and call the rand varibale again so it randomises the song again.
我希望再次使用播放按钮暂停歌曲,然后再次致电rand varibale,以便再次将歌曲随机化。 so when i press the playbutton it will then play a different song.
因此,当我按下播放按钮时,它将播放另一首歌曲。 the playagain button is pausing the song however the rand variable is not randomizing again.
playagain按钮正在暂停歌曲,但是rand变量不会再次随机化。 is there a way to fix that?
有办法解决吗?
HTML: 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: 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)';
}
}
It doesn't look like you're declaring the variable audioPlaying correctly. 您似乎没有正确声明变量audioPlaying。 You also don't need audioPlaying[] surrounding your statement for rand.
您也不需要在rand语句周围使用audioPlaying []。 Try this instead:
尝试以下方法:
var audioPlaying = [mytrackJS, gdJS];
var rand = Math.floor(Math.random() * audioPlaying.length);
Since you initialized rand variable once, its value is going to remain the same throughout. 由于您一次初始化rand变量,因此它的值将始终保持不变。
To see expected results move it to playOrPause function. 要查看预期结果,请将其移至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)';
}
}
I'm not sure if this is what you're looking for, but instead of selecting between two different audio
elements, I would just change the src
attribute of a single one. 我不确定这是否是您要寻找的东西,但是我只是在更改单个
audio
的src
属性,而不是在两个不同的audio
元素之间进行选择。 This way you could have an array of file names and randomly select from those using array[Math.random()*array.length]
这样,您可以拥有一个文件名数组,并使用
array[Math.random()*array.length]
从文件名中随机选择
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.