MinionAttack
MinionAttack

Reputation: 540

Different behaviour of WebAudio API on Google Chrome

I'm doing a sound player with a spectrum visualizer. On Firefox works very well but in Google Chrome I'm getting problems. I came from this question I made the other day My previous question

On Firefox I can go forward or go previous on the track list all the times I want without a problem, but in Google Chrome I get this error when I press "next/previous"

Failed to execute 'createMediaElementSource' on 'BaseAudioContext': 
HTMLMediaElement already connected previously to a different MediaElementSourceNode.

I don't know why Google Chrome complains and Firefox doesn't. The code of the visualizer it's:

 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();
  }

And after press the "next/previous" button I do immediately:

if (closeAudioContext && context !== undefined) {
      context.close();
}
context = new AudioContext();

And then:

visualizer(audio);
musicPlay();

So my question is, why in Firefox the audio player works fine but in Google Chrome crashes?

I'm using Bowser to check what browser the user is using because as the new policy of Chrome to mute all sounds if its activated the autoplay (in this case I set the autoPlay to false and if the user press play the sound it's not muted). So, if I have to make a different code for Google Chrome I can make an "if" with that code.

Regards.

Upvotes: 0

Views: 479

Answers (1)

Raymond Toy
Raymond Toy

Reputation: 6048

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.

Upvotes: 1

Related Questions