我正在尝试设置音频播放,我无法在Safari 14.0.3上工作,但在Chrome 88.0.4324.146上可以正常工作。我有一个返回AudioContext或webkitAudioContext的函数。我遵循了这个答案:https://stackoverflow.com/a/29373891/586006
var sounds;
var audioContext
window.onload = function() {
audioContext = returnAudioContext()
sounds = {
drop : new Audio('sounds/drop.mp3'),
slide : new Audio('sounds/slide.mp3'),
win : new Audio('sounds/win.mp3'),
lose : new Audio('sounds/lose.mp3'),
}
playSound(sounds.drop)
}
function returnAudioContext(){
var AudioContext = window.AudioContext // Default
|| window.webkitAudioContext // Safari and old versions of Chrome
|| false;
if (AudioContext) {
return new AudioContext;
}
}
function playSound(sound){
audioContext.resume().then(() => {
console.log("playing sound")
sound.play();
});
}活生生的例子:http://www.mysterysystem.com/stuff/test.html
发布于 2021-02-10 06:20:06
我已经尽了最大的努力来创建一个仅使用Web Audio API的示例,但是遗憾的是,Safari与此API的兼容性不是很好。虽然它可以与HTMLAudioElement结合使用,但除非你想操纵音频,否则你不需要它。
下面的示例将在您单击文档中的任意位置时播放drop声音。它可能需要2次点击,因为浏览器中的音频可以非常严格地规定何时播放或不播放。
playSound函数检查play()方法是否返回promise。如果是这样,那么promise应该有一个.catch()块。否则它将在Safari中抛出Unhandled Promise Rejection错误。
const sounds = {
drop: new Audio('sounds/drop.mp3'),
slide: new Audio('sounds/slide.mp3'),
win: new Audio('sounds/win.mp3'),
lose: new Audio('sounds/lose.mp3'),
};
function playSound(audio) {
let promise = audio.play();
if (promise !== undefined) {
promise.catch(error => {
console.log(error);
});
}
}
document.addEventListener('click', () => {
playSound(sounds.drop);
});如果你确实需要使用Web Audio API来做一些事情,请让我知道。
https://stackoverflow.com/questions/66126397
复制相似问题