【发布时间】:2018-11-12 10:27:49
【问题描述】:
我正在做一个带有频谱可视化器的声音播放器。在 Firefox 上运行良好,但在 Google Chrome 中我遇到了问题。我来自前几天提出的这个问题My previous question
在 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 的新策略是在激活自动播放时静音所有声音(在这种情况下,我将自动播放设置为 false,如果用户按下播放它没有静音的声音)。因此,如果我必须为 Google Chrome 制作不同的代码,我可以使用该代码制作“如果”。
问候。
【问题讨论】:
标签: javascript google-chrome firefox web-audio-api