Code snippet performs as expected on Chrome 80.0 and Firefox 74.0 (OSX 10.14.6). However, when testing on OSX Safari 13.0.5 or iOS (using Chrome, Safari), the <div>
element fails to turn blue, suggesting that the onended
callback is not triggering. Could this be a potential issue?
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;
// trying to attach an event listener to the buffer source
buffSource.addEventListener('ended', () => {
document.getElementById('test').style.backgroundColor = 'blue';
});
// another approach with a named function
function changeBackground() {
document.getElementById('test').style.backgroundColor = 'blue';
}
buffSource.addEventListener('ended', changeBackground);
// following documentation's suggestion to directly modify the function
buffSource.onended = function(){
document.getElementById('test').style.backgroundColor = 'blue';
};
// perhaps using 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 = "Button Clicked";
};
#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>