我一直在尝试思考一些有关使用Web Audio API使用JavaScript的想法。我知道,根据用户的浏览器,我知道有时候没有某种用户的手势,它就不会让您播放音频。我一直在研究如何做,这是非常有用的方法,但是问题是有些开发人员发现了不同的方法。例如:
audioContext.resume()
和audioContext.suspend()
方法通过更改状态来解锁网络音频:function unlockAudioContext(context) {
if (context.state !== "suspended") return;
const b = document.body;
const events = ["touchstart", "touchend", "mousedown", "keydown"];
events.forEach(e => b.addEventListener(e, unlock, false));
function unlock() {context.resume().then(clean);}
function clean() {events.forEach(e => b.removeEventListener(e, unlock));}
}
var unlocked = false;
var context = new (window.AudioContext || window.webkitAudioContext)();
function init(e) {
if (unlocked) return;
// create empty buffer and play it
var buffer = context.createBuffer(1, 1, 22050);
var source = context.createBufferSource();
source.buffer = buffer;
source.connect(context.destination);
/*
Phonograph.js use this method to start it
source.start(context.currentTime);
paulbakaus.com suggest to use this method to start it
source.noteOn(0);
*/
source.start(context.currentTime) || source.noteOn(0);
setTimeout(function() {
if (!unlocked) {
if (source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE) {
unlocked = true;
window.removeEventListener("touchend", init, false);
}
}
}, 0);
}
window.addEventListener("touchend", init, false);
我大部分都知道这两种方法如何工作,但是
我的问题是这里发生了什么,有什么区别,哪种方法更好?
有人可以请source.playbackState
向我解释一下此AudioBufferSourceNode
吗?我以前从未听说过那里的财产。它甚至没有文章,也没有在Mozilla MDN Website中被提及。
也是一个额外的问题(您不必回答),如果这两种方法都有用,那么如果您知道我的意思,是否可以将它们组合为一个?
抱歉,有很多问题要问。谢谢:)
资源:
https://paulbakaus.com/tutorials/html5/web-audio-on-ios/
https://github.com/Rich-Harris/phonograph/blob/master/src/init.ts
https://www.mattmontag.com/web/unlock-web-audio-in-safari-for-ios-and-macos
答案 0 :(得分:0)
两种方法都可以,但是我发现第一个方法(用户手势中的恢复上下文)更加简洁。 AudioBufferSource方法是一种粗暴的技巧,目的是与以用户手势开始播放缓冲区的旧站点向后兼容。如果您不从手势启动缓冲区,则此方法不起作用。 (我认为。)
您要使用哪一个取决于您。