Javascript HTML 音频重复播放函数只调用一次
Javascript HTML Audio repeats play function when only called once
我有以下功能,它是更大功能的一部分,但我删除了所有不属于问题的部分。
该函数创建一个音频标签并将其放入主体中。我正在使用此方法而不是音频 API,因为我使用的是 createMediaElementSource
,它需要 HTML 元素。
在 ended
事件结束并单击 replay
按钮后,play
函数被调用两次,尽管只触发了一次。
我尝试将代码放在片段中,但无法重现问题,所以我不得不将其放在 fiddle 中。 - https://jsfiddle.net/6n2f34eh/
在完整功能上,有用户交互激活播放。
<button type="button" class="btn-replay">REPLAY</button>
var func = function() {
that = this;
that.sound;
this.init = function() {
document.querySelector(".btn-replay").addEventListener("click", that.play);
tag = document.createElement("audio");
tag.className = "player";
document.body.appendChild(tag);
that.sound = document.querySelector(".player");
that.sound.src = 'https://www2.cs.uic.edu/~i101/SoundFiles/CantinaBand3.wav';
that.sound.addEventListener("canplaythrough", this.play);
that.sound.addEventListener("ended", this.ended);
}
this.ended = function() {
console.log("ended")
}
this.play = function() {
console.log("play")
that.sound.play();
}
this.init();
}
test = new func();
您有两个事件侦听器,它们会调用播放功能 - 按钮上的“单击”和声音上的“canplaythrough”。单击按钮后,音频会立即从 link 加载,因此两个事件都会被触发。
我有以下功能,它是更大功能的一部分,但我删除了所有不属于问题的部分。
该函数创建一个音频标签并将其放入主体中。我正在使用此方法而不是音频 API,因为我使用的是 createMediaElementSource
,它需要 HTML 元素。
在 ended
事件结束并单击 replay
按钮后,play
函数被调用两次,尽管只触发了一次。
我尝试将代码放在片段中,但无法重现问题,所以我不得不将其放在 fiddle 中。 - https://jsfiddle.net/6n2f34eh/
在完整功能上,有用户交互激活播放。
<button type="button" class="btn-replay">REPLAY</button>
var func = function() {
that = this;
that.sound;
this.init = function() {
document.querySelector(".btn-replay").addEventListener("click", that.play);
tag = document.createElement("audio");
tag.className = "player";
document.body.appendChild(tag);
that.sound = document.querySelector(".player");
that.sound.src = 'https://www2.cs.uic.edu/~i101/SoundFiles/CantinaBand3.wav';
that.sound.addEventListener("canplaythrough", this.play);
that.sound.addEventListener("ended", this.ended);
}
this.ended = function() {
console.log("ended")
}
this.play = function() {
console.log("play")
that.sound.play();
}
this.init();
}
test = new func();
您有两个事件侦听器,它们会调用播放功能 - 按钮上的“单击”和声音上的“canplaythrough”。单击按钮后,音频会立即从 link 加载,因此两个事件都会被触发。