随机排列的音频总是从 0 开始?
Shuffled Array Audio Always Starts with 0?
我正在尝试制作一种音乐,其中曲目是随机选择的,一个接一个地出现(并最终逐渐消失,使一个曲目与下一个曲目重叠,从而形成随意的音乐,也许最终有点自我-作曲等)
我 "randomizing" 通过将音频文件放在一个数组中然后对数组进行洗牌来播放曲目。然而,每次我加载页面时,虽然数组被打乱,但数组中的第一个选择总是#1。换句话说,如果我的数组是 [1,3,4,7,9] 并且我 运行 脚本三次,曲目将播放 [1,3,7,4,9],然后 [1, 4,7,9,3],然后是 [1,3,9,7,4],其中第一首曲目始终为 1。我希望第一首曲目也是随机的。有什么建议吗?
var audio = new Audio(),
i = 0;
var playlist = new Array('TRACKS/1.ogg', 'TRACKS/2.ogg', 'TRACKS/3.ogg', 'TRACKS/4.ogg', 'TRACKS/5.ogg', 'TRACKS/6.ogg', 'TRACKS/7.ogg', 'TRACKS/8.ogg', 'TRACKS/9.ogg');
audio.addEventListener('timeupdate', function(){
var buffer = .8
if(this.currentTime > this.duration - buffer){
i = ++i < playlist.length ? i : 0;
console.log(i)
audio.src = playlist[i];
readFiles()
}}, false);
audio.volume = 0.3;
audio.loop = false;
audio.src = playlist[0];
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
function readFiles(){
playlist = shuffle(playlist);
for(var i = 0; i < playlist.length; ++i){
audio.play();
}
readFiles(); //to read undefinitly
}
readFiles();
好的,我只需要在 readFiles() 函数之前调用 shuffle(playlist) 即可。简单...谢谢。
我正在尝试制作一种音乐,其中曲目是随机选择的,一个接一个地出现(并最终逐渐消失,使一个曲目与下一个曲目重叠,从而形成随意的音乐,也许最终有点自我-作曲等)
我 "randomizing" 通过将音频文件放在一个数组中然后对数组进行洗牌来播放曲目。然而,每次我加载页面时,虽然数组被打乱,但数组中的第一个选择总是#1。换句话说,如果我的数组是 [1,3,4,7,9] 并且我 运行 脚本三次,曲目将播放 [1,3,7,4,9],然后 [1, 4,7,9,3],然后是 [1,3,9,7,4],其中第一首曲目始终为 1。我希望第一首曲目也是随机的。有什么建议吗?
var audio = new Audio(),
i = 0;
var playlist = new Array('TRACKS/1.ogg', 'TRACKS/2.ogg', 'TRACKS/3.ogg', 'TRACKS/4.ogg', 'TRACKS/5.ogg', 'TRACKS/6.ogg', 'TRACKS/7.ogg', 'TRACKS/8.ogg', 'TRACKS/9.ogg');
audio.addEventListener('timeupdate', function(){
var buffer = .8
if(this.currentTime > this.duration - buffer){
i = ++i < playlist.length ? i : 0;
console.log(i)
audio.src = playlist[i];
readFiles()
}}, false);
audio.volume = 0.3;
audio.loop = false;
audio.src = playlist[0];
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
function readFiles(){
playlist = shuffle(playlist);
for(var i = 0; i < playlist.length; ++i){
audio.play();
}
readFiles(); //to read undefinitly
}
readFiles();
好的,我只需要在 readFiles() 函数之前调用 shuffle(playlist) 即可。简单...谢谢。