【发布时间】:2020-07-20 21:52:05
【问题描述】:
以下代码适用于 Chrome 80.0 和 Firefox 74.0 (OSX 10.14.6)。但是,在 OSX Safari 13.0.5 或 iOS 上(在 Chrome、Safari 中测试),<div> 元素永远不会变成蓝色,这表明 onended 回调不会触发。这是一个错误吗?
const ctx = new (window.AudioContext || window.webkitAudioContext)();
const buff = ctx.createBuffer(1, 32, ctx.sampleRate);
const buffSource = ctx.createBufferSource();
buffSource.buffer = buff;
buffSource.loop = false;
// attempt to add an event listener to the buffer source
buffSource.addEventListener('ended', () => {
document.getElementById('test').style.backgroundColor = 'blue';
});
// another slight variation using the named function
function changeBackground() {
document.getElementById('test').style.backgroundColor = 'blue';
}
buffSource.addEventListener('ended', changeBackground);
// the documentation suggestion modifying the function directly
buffSource.onended = function(){
document.getElementById('test').style.backgroundColor = 'blue';
};
// maybe binding would help?
buffSource.onended = function(){
document.getElementById('test').style.backgroundColor = 'blue';
}.bind(this);
document.getElementById('button').onclick = (e) => {
ctx.resume();
buffSource.start();
document.getElementById('message').innerText = "Pressed Button";
};
#test {
background-color: red;
width: 500px;
height: 500px;
}
#button {
cursor: pointer;
}
<!DOCTYPE html>
<html lang="en">
<body>
<button id = 'button'>Click me</button>
<div id = 'test'></div>
<div id = 'message'></div>
</body>
</html>
【问题讨论】:
标签: javascript ios safari webkit web-audio-api