首页 > 解决方案 > 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”。

问候。

标签: javascriptgoogle-chromefirefoxweb-audio-api

解决方案


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.


推荐阅读