微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Javascript webkitAudioContext 在 Safari 中没有播放

如何解决Javascript webkitAudioContext 在 Safari 中没有播放

我正在尝试设置无法在 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

解决方法

我已尽最大努力制作了一个仅使用 Web Audio API 的示例,但遗憾的是,Safari 与此 API 不太兼容。尽管可以将它与 HTMLAudioElement 结合使用,但除非您想操纵音频;你不需要它。

以下示例将在您单击文档中的任意位置时播放放置声音。它可能需要 2 次点击,因为浏览器中的音频对何时播放或不播放非常严格。

playSound 函数检查 play() 方法是否返回承诺。如果是,那么该承诺应该有一个 .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 来做一些事情,请告诉我。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。