GoogleChromeLabs / web-audio-samples

Web Audio API samples by Chrome Web Audio Team
https://bit.ly/web-audio-samples
Apache License 2.0
686 stars 196 forks source link

Audio visualisation not working when connected to AudioWorkletNode? #340

Closed ukaj808 closed 1 year ago

ukaj808 commented 1 year ago

Hey everyone!

I'm following this doc here, in an attempt to implement the frequency bar graph in my app. I cant seem to get the bars to appear.

I've hooked up the analyser into my graph (note that its source connection is an AudioWorkletNode):

    this.audioWorklet.connect(this.analyser);
    this.analyser.connect(this.audioContext.destination);
    this.audioContext.resume();

And i've hooked into a canvas element on my page and implemented the draw function:

    this.auxAudioPlayer.startListening();
    this.listening = true;
    this.toggleDisconnectOverlay();
    const draw = () => {
      this.drawVisual = requestAnimationFrame(draw);
      this.analyser.getByteFrequencyData(this.buffer);
      this.canvasCtx.fillStyle = 'rgb(0, 0, 0)';
      this.canvasCtx.fillRect(0, 0, this.audioCanvas.width, this.audioCanvas.height);

      const barWidth = (this.audioCanvas.width / this.analyser.frequencyBinCount) * 2.5;
      let barHeight;

      let x = 0;

      for (let i = 0; i < this.analyser.frequencyBinCount; i++) {
        barHeight = this.buffer[i] / 2;

        this.canvasCtx.fillStyle = `rgb(${barHeight + 100}, 50, 50)`;
        this.canvasCtx.fillRect(x, this.audioCanvas.height - barHeight / 2, barWidth, barHeight);

        x += barWidth + 1;
      }
    }
    draw();

I was wondering if the analyser works when hooked up to a AudioWorkletNode? I noticed in the docs that you use a MediaStreamAudioSourceNode and in the voice-change-o-matic source code you use another type of node:

    convolver.connect(gainNode);
    echoDelay.placeBetween(gainNode, analyser);
    analyser.connect(audioCtx.destination);

Here's my code for extra reference: where connection to graph is made where draw function is called

ukaj808 commented 1 year ago

Extra Context:

Screenshot from 2023-07-04 22-54-23

The canvas fills correctly, so the draw function is running;

The indivudual samples in the dataArray (buffer) are always "-Infinity" when I log them

My audio has a single output source, with 2 channels (L, R)

ukaj808 commented 1 year ago

This is a non-issue. I had a bug in my code... I was reinitialzing the analyser before connecting it to the audio worklet node. Apologies ):