✅ Solved: mic input event/listener in Rive JS runtime

Hello, I’ve managed to have a mic input waveform visualizer created with html/JS to be overlayed on my Rive JS runtime project. It reacts to your voice/sound. Rive file is being displayed and interactions are working. The issue is that it’s not being triggered in the runtime to appear and disappear at specific moments based on the Rive timeline.

I am not sure if my JS runtime is wrong or if the event/listeners are set up wrong in Rive. Or both.

I’ve attached the JS code, .riv and .rev for troubleshooting/debugging. Any help would be appreciated.

JS code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Rive + Mic Visualizer Overlay - 78 Bars</title>
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <style>
    html, body {
      margin: 0; height: 100%;
      background-color: #343434;
      display: flex;
      justify-content: center;
      align-items: center;
      overflow: hidden;
    }
    #animation-container {
      position: relative;
      width: 650px;
      height: 823px;
      user-select: none;
    }
    #rive-canvas {
      position: absolute;
      top: 0; left: 0;
      width: 650px; height: 823px;
      cursor: pointer;
      z-index: 0;
    }
    #waveCanvas {
      position: absolute;
      top: 260px;
      left: 107px;
      width: 436px;
      height: 823px;
      z-index: 1;
      pointer-events: none;
      background: transparent;
    }
  </style>
  <script src="https://unpkg.com/@rive-app/webgl2"></script>
</head>
<body>
  <div id="animation-container">
    <canvas id="rive-canvas"></canvas>
    <canvas id="waveCanvas" width="650" height="823"></canvas>
  </div>

  <script>
    // --- Rive animation setup ---
    const riveCanvas = document.getElementById('rive-canvas');
    const riveScale = 2;
    riveCanvas.width = 650 * riveScale;
    riveCanvas.height = 823 * riveScale;
    riveCanvas.style.width = '650px';
    riveCanvas.style.height = '823px';

    const riveInstance = new rive.Rive({
      src: './biometric_scan_wip.riv', // <-- Adjust path as needed
      canvas: riveCanvas,
      autoplay: true,
      artboard: 'MAIN WIP',
      stateMachines: 'State Machine 1',
      fit: rive.Fit.contain,
      onLoad() {
        riveInstance.resizeDrawingSurfaceToCanvas();
      }
    });

    window.addEventListener('resize', () => {
      riveInstance.resizeDrawingSurfaceToCanvas();
    });

    // --- Mic visualizer setup ---
    const canvas = document.getElementById('waveCanvas');
    const ctx = canvas.getContext('2d', { alpha: true });

    // Canvas dimensions (match width & height attributes)
    const W = canvas.width;  // 650
    const H = canvas.height; // 823

    let audioCtx, analyser, dataArray, source;
    let idlePhase = 0;

    // Visualizer config
    const barCount = 78;
    const maxBarWidth = 8;          // fixed bar width (px)
    const visualWidth = 650;        // width matches canvas width
    const spacing = visualWidth / barCount;  // ~8.33 px spacing between bars
    const xOffset = 0;              // start at left edge of waveCanvas
    const verticalOffset = 0;       // adjust vertical position if needed

    let currentHeights = new Array(barCount).fill(H * 0.2);
    const volumeThreshold = 15;
    const amplitudeScale = 0.65 * 0.8 * 0.65 * 0.4; // cumulative amplitude reduction (~68.6%)

    function lerp(a, b, t) {
      return a + (b - a) * t;
    }

    function getAverageVolume(data) {
      let sum = 0;
      for(let i = 0; i < data.length; i++) sum += data[i];
      return sum / data.length;
    }

    function setGlowStyle() {
      ctx.shadowColor = '#3BBBE4';
      ctx.shadowBlur = 6;
      ctx.shadowOffsetX = 0;
      ctx.shadowOffsetY = 0;
    }

    function clearGlowStyle() {
      ctx.shadowColor = 'transparent';
      ctx.shadowBlur = 0;
    }

    function drawBars(heights) {
      ctx.strokeStyle = '#3BBBE4';
      ctx.lineWidth = 0.5;
      ctx.fillStyle = '#3BBBE4';
      setGlowStyle();

      for(let i = 0; i < barCount; i++) {
        const height = heights[i];
        const x = xOffset + i * spacing + (spacing - maxBarWidth) / 2;
        const yTop = ((H - height) / 2) + verticalOffset;
        const yBottom = yTop + height;

        ctx.beginPath();
        ctx.moveTo(x + maxBarWidth / 2, yTop);
        ctx.lineTo(x + maxBarWidth / 2, yBottom);
        ctx.stroke();

        ctx.fillRect(x + maxBarWidth / 2 - 2, yTop - 2, 4, 4);
        ctx.fillRect(x + maxBarWidth / 2 - 2, yBottom - 2, 4, 4);
      }

      clearGlowStyle();
    }

    function drawIdleRow() {
      ctx.fillStyle = '#3BBBE4';
      setGlowStyle();
      idlePhase += 0.065;

      for(let i = 0; i < barCount; i++) {
        const x = xOffset + visualWidth - (i + 1) * spacing + (spacing - maxBarWidth) / 2 + maxBarWidth / 2 - 2;
        const sineValue = (Math.sin(idlePhase + i * 0.3) + 1) / 2;
        const size = lerp(2, 6, sineValue);
        const y = (H / 2 - size / 2) + verticalOffset;
        ctx.fillRect(x, y, size, size);
      }

      clearGlowStyle();
    }

    function getCenterOutMappedHeights(data) {
      const heights = new Array(barCount).fill(H * 0.2);
      const center = Math.floor(barCount / 2);

      for (let i = 0; i < barCount / 2; i++) {
        const leftIndex = Math.min(data.length - 1, i);
        const rightIndex = Math.min(data.length - 1, i + 10);

        const leftValue = data[leftIndex];
        const rightValue = data[rightIndex];

        const leftHeight = (leftValue / 255) * H * 0.6 * amplitudeScale;
        const rightHeight = (rightValue / 255) * H * 0.6 * amplitudeScale;

        heights[center - 1 - i] = leftHeight;
        heights[center + i] = rightHeight;
      }

      return heights;
    }

    function draw() {
      requestAnimationFrame(draw);
      ctx.clearRect(0, 0, W, H);

      if (!analyser) {
        drawIdleRow();
        return;
      }

      analyser.getByteFrequencyData(dataArray);
      const avgVol = getAverageVolume(dataArray);

      if (avgVol < volumeThreshold) {
        drawIdleRow();
        for(let i = 0; i < barCount; i++) {
          currentHeights[i] = lerp(currentHeights[i], H * 0.2, 0.05);
        }
      } else {
        const liveHeightsRaw = getCenterOutMappedHeights(dataArray);
        const liveHeights = liveHeightsRaw.map((h, i) => lerp(currentHeights[i], h, 0.2));
        currentHeights = liveHeights;
        drawBars(liveHeights);
      }
    }

    draw();

    navigator.mediaDevices.getUserMedia({ audio: true })
      .then(stream => {
        audioCtx = new (window.AudioContext || window.webkitAudioContext)();
        analyser = audioCtx.createAnalyser();
        analyser.fftSize = 128;
        dataArray = new Uint8Array(analyser.frequencyBinCount);

        source = audioCtx.createMediaStreamSource(stream);
        source.connect(analyser);
      })
      .catch(err => {
        alert('Microphone access is required to run the visualizer.');
        console.error(err);
      });
  </script>
</body>
</html>


biometric_scan_wip.rivbiometric_scan_wip.rev