我正在创建一个系统,其中JavaScript正在Websocket上侦听来自IoT按钮的单击或双击。当JavaScript收到单击声时,应该开始播放随机播放的音频元素数组中的第一首歌曲。然后,一旦第一个音频元素播放完毕,就应该播放数组中的下一首歌曲。这将一直持续到被双击(表示暂停)中断为止。当到达最后一首歌曲的结尾时,它会重新洗牌并从头开始。但是,我无法使“歌曲结尾”功能正常工作。现在,它播放第一首歌曲,然后停止。如果我再点击一次,它将从头开始播放第一个。
Javascript:
<!DOCTYPE html>
<head>
<title>Pusher Test</title>
<script src="https://js.pusher.com/4.1/pusher.min.js"></script>
<script>
function shuffle (input) {
for (var i = input.length-1; i >=0; i--) {
var randomIndex = Math.floor(Math.random()*(i+1));
var itemAtIndex = input[randomIndex];
input[randomIndex] = input[i];
input[i] = itemAtIndex;
}
return input;
}
function startShuffle(songs){
current = 0;
for (var i = 0; i < songs.length - 1; i++) {
songs[i].onended = function () {
songs[i+1].play();
current = i + 1;
}
}
songs[songs.length - 1].onended = function () {
songs = shuffle(songs);
startShuffle(songs);
}
}
Pusher.logToConsole = true;
var current = 0;
var songs = [];
for (i = 0; i <= 100; i++) {
songs[i] = new Audio('/Users/eliavhamburger/Desktop/Ser Dree/Music/' + i + '.mp3');
}
songs = shuffle(songs);
startShuffle(songs);
var pusher = new Pusher('APIKeyHidden', {
cluster: 'us2',
encrypted: true
});
var channel = pusher.subscribe('my-channel');
channel.bind('my-event', function(data) {
document.getElementById("demo").innerHTML = JSON.stringify(data);
if (JSON.stringify(data) == '"SINGLE"') {
songs[current].play();
}
if (JSON.stringify(data) == '"DOUBLE"') {
songs[current].pause();
}
});
</script>
</head>
<body>
<h1>Pusher Test</h1>
<p>
Try publishing an event to channel <code>my-channel</code>
with event name <code>my-event</code>.
</p>
<p ID="demo"></p>
<p ID="nums"></p>
</body>
答案 0 :(得分:0)
疯狂的猜测:onended
未实现。尝试通过替换两次出现的{p> 1来重写startShuffle
方法
songs[/* some index */].onended = function () { /* do something */ };
使用
songs[/* some index */].addEventListener('ended', function () { /* do something */ });
这似乎是the official way(滚动到最后一个例子)。