【发布时间】:2019-01-24 21:32:25
【问题描述】:
我正在尝试在 keydown 上播放声音。 为此,我看到解决方案是克隆声音并播放新实例:
var promise = sound.cloneNode(true).play();
在线复制: https://jsfiddle.net/alvarotrigo/up4c6m95/13/
这似乎在 Chrome 和 Firefox 中运行良好。但是在 Safari 中,这会导致性能不佳。
尝试用双手快速打字以重现错误。
请注意,我添加了一个 gif 图像,在快速输入时会出现延迟。 这当然也可以在 Safari 开发工具上注意到,如下图所示:
完整代码在这里:
var sound = new Audio('https://www.w3schools.com/html/horse.mp3');
document.addEventListener('keydown', playSound);
function playSound() {
//in order to play the same sound over itself
var promise = sound.cloneNode(true).play();
//we just dont want to show the console error when autoplay is disabled :)
if (typeof promise !== undefined) {
promise.then(function() {
// Autoplay started!
}).catch(function(error) {
//error
});
}
}
【问题讨论】:
标签: javascript html safari webkit html5-audio