我一直在思考一些关于使用Web使用JavaScript可以做些什么的想法。我知道,取决于用户的浏览器,我知道,如果没有用户的某种手势,有时它不会让您播放音频。我一直在做一些关于如何去做的研究,它们是非常有用的方法,但问题是一些开发人员找到了不同的方法来实现它。例如:
audioContext.resume()
和audioContext.suspend()
方法通过更改web音频的状态来解锁它: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网站中被提及。另外,作为一个额外的问题(你不需要回答),如果这两种方法都是有用的,那么如果你知道我的意思的话,能不能把它们放在一起呢?对不起,如果这要求很高的话。谢谢:)
资源:
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
发布于 2019-12-03 15:57:21
这两种方法都有效,但我发现第一种方法(用户手势中的恢复上下文)更简洁。AudioBufferSource方法是一种对旧站点的向后兼容性的严重攻击,这些站点开始以用户的姿态播放缓冲区。如果不从手势启动缓冲区,则此方法不起作用。(我想)
你想用哪一个取决于你。
https://stackoverflow.com/questions/59150956
复制相似问题