这篇文章似乎已有3年历史了。那时的浏览器自动播放策略并没有真正影响Web Audio API的使用。那已经改变了。现在需要具有用户手势(通常是单击事件)才能启动AudioContext。
被引用的文章的第一个示例将看起来像这样:
const $playButton = document.getElementById('play-button');
$playButton.addEventListener('click', () => {
const context = new AudioContext();
const oscillator = context.createOscillator();
oscillator.type = 'sine';
oscillator.connect(context.destination);
oscillator.start();
};
这确实假定您在HTML中的某个位置有一个ID为play-button
的按钮。
<button id="play-button">play</button>