javascript - 解锁网络音频的最佳解决方案
问题描述
我一直在想一些关于我可以使用 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 网站中被提及。另外作为一个奖励问题(您不必回答),如果这两种方法都有用,那么如果您知道我的意思,是否可以将它们组合在一起?对不起,如果有很多问题要问。谢谢 :)
资源:
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
解决方案
这两种方法都有效,但我发现第一种(在用户手势中恢复上下文)更简洁。AudioBufferSource 方法是一种用于向后兼容以用户手势开始播放缓冲区的旧网站的粗俗技巧。如果您不从手势启动缓冲区,则此方法不起作用。(我认为。)
您想使用哪一个取决于您。
推荐阅读
- python-3.x - 将在 Gensim 中创建的自定义训练词向量加载到 Spacy 时遇到问题
- python - Pandas:将所有不包含在列表中的 col2 一个元素的组删除
- python - 如何从 .dat 文件中提取表格,同时使用 python 保存其形状?
- java - 带有 Spring Boot 和事务边界的 graphql-spqr
- java - 如何翻转地图
- , 列表
> 进入地图 >? - javascript - 从 getUserMedia 将约束应用于音轨
- c# - .Net core EF,将记录保存到多对多类型表
- r - R 如何通过其字符串名称注释变量?
- r - ifelse inside 观察闪亮 - 不等待触发
- android - Android Recyclerview 自动水平滚动