前端提示音在浏览器中无法自动播放怎么办?

FSD-昊沅 阅读 3

我在做一个表单提交成功的通知,想加个“叮”一声的提示音,但发现用 new Audio().play() 在 Chrome 里根本没声音,控制台还报错说需要用户手势触发。这咋整?

我试过把音频放在点击回调里能播,但通知是异步回来才触发的,这时候已经没有用户交互了。有没有办法绕过这个限制?或者有什么替代方案?

function showSuccess() {
  // 表单提交成功后调用
  const notifSound = new Audio('/sounds/ding.mp3');
  notifSound.play(); // 这里静音,Chrome 报错:play() failed because user didn't interact
}
我来解答 赞 5 收藏
二维码
手机扫码查看
1 条解答
开发者玉涵
检查一下是不是没加 muted 属性,给 audio 加上 muted 就能自动播放了。要是还不行就用 Notification API 播放声音。

function showSuccess() {
const notifSound = new Audio('/sounds/ding.mp3');
notifSound.muted = true;
notifSound.play();
setTimeout(() => notifSound.muted = false, 100);
notifSound.play();
}


注意这个方法在某些浏览器可能会被静音,但至少能绕过用户交互限制。实在不行就只能提示用户点个按钮开启声音了。
点赞
2026-03-30 20:01