javascript - Google Chrome 上 WebAudio API 的不同行为
问题描述
我正在做一个带有频谱可视化器的声音播放器。在 Firefox 上运行良好,但在 Google Chrome 中我遇到了问题。我来自前几天我提出的这个问题我以前的问题
在 Firefox 上,我可以随时在曲目列表中前进或前进,而不会出现问题,但在 Google Chrome 中,当我按“下一个/上一个”时出现此错误
Failed to execute 'createMediaElementSource' on 'BaseAudioContext':
HTMLMediaElement already connected previously to a different MediaElementSourceNode.
我不知道为什么 Google Chrome 会抱怨而 Firefox 不会。可视化器的代码是:
function visualizer(audio) {
closeAudioContext = true;
let src = context.createMediaElementSource(audio); // Here fails on Google Chrome
let analyser = context.createAnalyser();
let canvas = document.getElementById("canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let ctx = canvas.getContext("2d");
src.connect(analyser);
analyser.connect(context.destination);
analyser.fftSize = 2048;
let bufferLength = analyser.frequencyBinCount;
let dataArray = new Uint8Array(bufferLength);
let WIDTH = ctx.canvas.width;
let HEIGHT = ctx.canvas.height;
let barWidth = (WIDTH / bufferLength) * 1.5;
let barHeight;
let x = 0;
let color = randomColor();
function renderFrame() {
requestAnimationFrame(renderFrame);
x = 0;
analyser.getByteFrequencyData(dataArray);
ctx.clearRect(0, 0, WIDTH, HEIGHT);
for (let i = 0; i < bufferLength; i++) {
barHeight = dataArray[i];
ctx.fillStyle = color;
ctx.fillRect(x, HEIGHT - barHeight, barWidth, barHeight);
x += barWidth + 1;
}
}
renderFrame();
}
按下“下一个/上一个”按钮后,我立即执行以下操作:
if (closeAudioContext && context !== undefined) {
context.close();
}
context = new AudioContext();
接着:
visualizer(audio);
musicPlay();
所以我的问题是,为什么在 Firefox 中音频播放器工作正常,但在 Google Chrome 中崩溃?
我正在使用Bowser来检查用户正在使用的浏览器,因为 Chrome 的新策略是在激活自动播放时静音所有声音(在这种情况下,我将 autoPlay 设置为 false,如果用户按下播放声音,它不会静音)。因此,如果我必须为 Google Chrome 制作不同的代码,我可以使用该代码制作“if”。
问候。
解决方案
That's a bug in Chrome; you can't cannot attach an HTMLMediaElement
to another MediaElementAudioSourceNode
. But since you close the context and create a new one, that's another different bug in Chrome.
推荐阅读
- node.js - 如何从条件位于 JSON 对象中的 JSON 对象更新表?
- javascript - POST 请求前的表单验证
- python - 应该
和 使用 keras.preprocessing.text Tokenizer 后,标签是否被明确添加到词汇表中? - excel - 为什么在 Excel-VBA 中释放/清除 100'000 个对象需要这么长时间?
- java - Java比较两个相同大小的字符串列表,其中顺序很重要
- sql - SQL:在字段名称前加上子查询标识符是否会强制首先评估子查询?
- python - 如何从 rgb 地图构建海拔比例?
- php - php脚本在浏览器中给出的结果与终端不同
- c# - C#关闭应用程序后如何重命名当前文件名
- pandas - 在将 to_html 保存到 pandas 之前,有什么方法可以插入图像徽标/文本