Skip to content

Instantly share code, notes, and snippets.

@hhyyg
Created December 2, 2021 02:31
Show Gist options
  • Save hhyyg/89d5681db9ced05909e0eebb3379455d to your computer and use it in GitHub Desktop.
Save hhyyg/89d5681db9ced05909e0eebb3379455d to your computer and use it in GitHub Desktop.
Web Audio API. This code works in Chrome 96 but not in Safari 15.1
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8>
<title></title>
</head>
<body>
<button id="start-button">start</button>
<script type="module" src="/index.js"></script>
</body>
</html>
const somePromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, 1000);
});
const startButton = document.getElementById('start-button');
let audioContext = new window.AudioContext();
startButton.addEventListener('click', () => {
audioContext.close().then(() => { // In Safari, it works: audioContext.close();
console.log('closed');
audioContext = new window.AudioContext();
const osc = audioContext.createOscillator();
osc.frequency.value = 800;
const gainNode = audioContext.createGain();
gainNode.gain.value = 1;
gainNode.gain.exponentialRampToValueAtTime(1, 0.001);
gainNode.gain.exponentialRampToValueAtTime(0.001, 0.17);
gainNode.connect(audioContext.destination);
osc.connect(gainNode);
osc.start(0);
osc.stop(0.3);
});
});
setInterval(() => {
if (audioContext) {
console.log(`audioContext.currentTime: ${audioContext.currentTime}`);
}
}, 1000)

This code works in Chrome 96 but not in Safari 15.1

But In Safari, the following code will work.

startButton.addEventListener('click', () => {
    audioContext.close();
    //...

In Safari, if I create an instance of AudioContext after the completion of audioContext.close(), will it not start playing?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment