我正在修改一个脚本来播放我在 Codepen 上找到的 mp3,以使其在 Safari 上运行。在 Firefox 和 Chrome 中它工作正常,但 Safari 提示:“未处理的 promise 拒绝:TypeError:没有足够的参数 index.html:25"
我读过 https://developer.apple.com/library/archive/documentation/AudioVideo/Conceptual/Using_HTML5_Audio_Video/PlayingandSynthesizingSounds/PlayingandSynthesizingSounds.html这涉及比我需要的更高级的东西。我只想播放我的 mp3 中的声音。不过我需要网络音频,因为这是让它在 iOS Safari 上运行的唯一方法。
有谁知道如何使 Safari 快乐?
https://codepen.io/kslstn/full/pagLqL
(function () {
if('AudioContext' in window || 'webkitAudioContext' in window) {
// Check for the web audio API. Safari requires the webkit prefix.
const URL = 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/123941/Yodel_Sound_Effect.mp3';
var AudioContext = window.AudioContext || window.webkitAudioContext;
var context = new AudioContext(); // Make it crossbrowser
const playButton = document.querySelector('#play');
let yodelBuffer;
window.fetch(URL)
.then(response => response.arrayBuffer())
.then(arrayBuffer => context.decodeAudioData(arrayBuffer))
.then(audioBuffer => {
yodelBuffer = audioBuffer;
});
playButton.onclick = () => play(yodelBuffer);
function play(audioBuffer) {
const source = context.createBufferSource();
source.buffer = audioBuffer;
source.connect(context.destination);
source.start();
}
}
}());
<button id="play">Yodel!</button>
最佳答案
Safari(Webkit) 不支持 BaseAudioContext.decodeAudioData() 基于 Promise 的语法。在以下链接中查看详细的浏览器兼容性
https://developer.mozilla.org/en-US/docs/Web/API/BaseAudioContext/decodeAudioData
因此您需要使用如下旧的回调语法。它适用于 6.0 以上的 Safari 和 10 以上的 Chrome
window.fetch(URL)
.then(response => response.arrayBuffer())
.then(arrayBuffer => context.decodeAudioData(arrayBuffer,
audioBuffer => {
yodelBuffer = audioBuffer;
},
error =>
console.error(error)
))
关于javascript - 如何使用网络音频 API 播放声音文件 Safari?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48597747/