日本語

How to Draw an Audio File’s Waveform in React

​​React​Canvas API,Playwright,TypeScript,Web Audio API

You can draw the waveform of an audio file the user selects in the browser without a library. Use decodeAudioData() from the Web Audio API to turn the file into a sequence of numbers from -1 to 1. Then split the numbers into as many segments as the canvas is wide in pixels, and draw a vertical line for each segment from its min to its max on a <canvas>.

Here I build a component that draws the waveform, colors the part that has been played light blue, and seeks to a position when the waveform is clicked. I also cover how taking the wrong value from each segment makes short sounds disappear, and how much memory a long file uses, along with the test results.

Note

The test environment was Ubuntu 24.04, Node.js 22.23.4, and Chromium 153. I used React 19.3.1, TypeScript 7.0.2, and Playwright 1.63.0. The audio files were test files made with ffmpeg (WAV, MP3, AAC in M4A, Opus in Ogg, and FLAC), and I selected them in Playwright to check. I did not test Firefox, Safari, smartphone browsers, real files with recorded voices or music, or how long an audio file can be before memory runs out.

Choosing a file shows a gray waveform. Pressing play turns it light blue from the left. Clicking about a quarter of the way in from the right of the waveform moves the playback position to the 9-second mark, and light blue continues from there
Choosing a file, playing, and seeking by clicking the waveform (the cursor, the number of operations, and the playback position display are overlaid for the GIF)

Turning the Audio File into a Sequence of Numbers

First, decode the file contents with decodeAudioData(). From the resulting AudioBuffer, you can get a Float32Array for each channel with getChannelData(). The waveform processing does not depend on React, so I put it in waveform.ts.

ts
export type Peaks = { min: Float32Array; max: Float32Array };

// Decode the audio file to PCM (a sequence of numbers from -1 to 1).
// Nothing is played, so an OfflineAudioContext is used. The decoded result is converted to this 44100Hz
export async function decodeAudio(file: Blob): Promise<AudioBuffer> {
  const data = await file.arrayBuffer();
  const ctx = new OfflineAudioContext(1, 1, 44100);
  return ctx.decodeAudioData(data);
}

AudioContext also has decodeAudioData(), but since no sound is played here, I used OfflineAudioContext. Its arguments are the number of channels, the length, and the sample rate. It is only used for decoding, so the length is set to 1.

The decoded result is converted to the sample rate of the context, not the sample rate of the original file. In the test environment, a 48000Hz Opus file and a 22050Hz mono WAV file both became an AudioBuffer with sampleRate 44100. When I created the OfflineAudioContext at 8000Hz, the same WAV became 8000Hz. If you only want to see the shape of the waveform, you do not need to worry about this conversion.

The test also revealed two other things.

  • After decodeAudioData() runs, the ArrayBuffer you passed in has byteLength 0. If you need the same data for something else, make a copy with slice() first.
  • When I passed a file that was not actually audio, decoding failed with EncodingError (the message was "Unable to decode audio data"). When I loaded the same file into an <audio> element, error.code was 4 (the format is not supported).

Decoding worked in Chromium 153 for all five formats I tried.

File Original sample rate After decoding
WAV (16-bit, stereo) 44100Hz 44100Hz, 2ch, 12.000 seconds
MP3 (128kbps) 44100Hz 44100Hz, 2ch, 12.000 seconds
AAC in M4A (128kbps) 44100Hz 44100Hz, 2ch, 12.000 seconds
Opus in Ogg (96kbps) 48000Hz 44100Hz, 2ch, 12.000 seconds
FLAC 44100Hz 44100Hz, 2ch, 12.000 seconds

Taking the Min and Max for Each Segment

A 12-second audio file at 44100Hz has 529,200 numbers per channel. To draw it on a canvas 600px wide, split these numbers into 600 segments and make one vertical line per segment. The top end of the line is the segment's max, and the bottom end is its min.

ts
// Split the whole into `columns` segments and take the min and max of each (all channels are looked at together)
export function computePeaks(buffer: AudioBuffer, columns: number): Peaks {
  const channels = Array.from({ length: buffer.numberOfChannels }, (_, c) => buffer.getChannelData(c));
  const min = new Float32Array(columns);
  const max = new Float32Array(columns);
  for (let i = 0; i < columns; i++) {
    const start = Math.floor((i * buffer.length) / columns);
    const end = Math.max(start + 1, Math.floor(((i + 1) * buffer.length) / columns));
    let lo = 0;
    let hi = 0;
    for (const data of channels) {
      for (let j = start; j < end; j++) {
        const v = data[j];
        if (v < lo) lo = v;
        if (v > hi) hi = v;
      }
    }
    min[i] = lo;
    max[i] = hi;
  }
  return { min, max };
}

The code checks every value in each segment because if you only use the first value of the segment, short sounds disappear from the waveform. I compared the two approaches on a file with a 3-second quiet sound and a loud sound lasting only 0.5ms in the middle.

Top: a waveform drawn with only the first value of each segment. A thin gray band continues, and the loud sound is not visible. Bottom: a waveform drawn with the min and max of each segment. A line sticks up from the light blue band
The same audio drawn in 600 columns in two ways. Only the bottom shows the 0.5ms loud sound

When this file is split into 600 segments, each segment has about 220 values. In the segment with the loud sound, the first value was 0.048, and the max was 0.945. Since 0.5ms is about 22 values, it does not appear in the waveform unless it falls on the first value of a segment.

Drawing on the Canvas

drawWaveform() draws the min and max of each segment as a vertical line. Lines to the left of progress (0 to 1) are light blue, and lines to the right are gray. A dark line is drawn at the playback position.

ts
// Draw each segment as one vertical column from its max down to its min. Segments left of progress (0–1) use the played color
export function drawWaveform(canvas: HTMLCanvasElement, peaks: Peaks, progress: number) {
  const dpr = window.devicePixelRatio || 1;
  const w = canvas.clientWidth;
  const h = canvas.clientHeight;
  canvas.width = Math.round(w * dpr);
  canvas.height = Math.round(h * dpr);
  const ctx = canvas.getContext('2d')!;
  ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  ctx.clearRect(0, 0, w, h);

  const n = peaks.min.length;
  const colW = w / n;
  const mid = h / 2;
  for (let i = 0; i < n; i++) {
    const top = mid - peaks.max[i] * mid;
    const bottom = mid - peaks.min[i] * mid;
    ctx.fillStyle = (i + 0.5) / n <= progress ? '#00c8e8' : '#c5ccd0';
    ctx.fillRect(i * colW, top, colW, Math.max(1, bottom - top));
  }
  // Playback position line
  ctx.fillStyle = '#1f2a30';
  ctx.fillRect(Math.min(progress * w, w - 2), 0, 2, h);
}

The canvas pixel count is set to the display size multiplied by devicePixelRatio, so the drawing does not look blurry on high-resolution screens. On a screen with a devicePixelRatio of 2, the display size stayed 600×120, and the canvas pixel count became 1200×240.

A silent segment has a min and max of 0, so its line would have zero height and be invisible. Math.max(1, …) keeps a 1px line. As in the GIF above, silent parts appear as a horizontal line through the middle.

Putting Playback and Seeking into a Component

AudioWaveform takes the selected File and displays the waveform and an <audio> element.

tsx
import { type MouseEvent, useEffect, useRef, useState } from 'react';
import { computePeaks, decodeAudio, drawWaveform, type Peaks } from './waveform';

type Props = { file: File; width?: number; height?: number };

export function AudioWaveform({ file, width = 600, height = 120 }: Props) {
  const audioRef = useRef<HTMLAudioElement>(null);
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [peaks, setPeaks] = useState<Peaks | null>(null);
  const [error, setError] = useState('');
  const [src, setSrc] = useState('');
  const [progress, setProgress] = useState(0);

  // When the file changes, create the playback URL and rebuild the waveform data
  useEffect(() => {
    let ignore = false;
    setPeaks(null);
    setError('');
    setProgress(0);
    const url = URL.createObjectURL(file);
    setSrc(url);
    decodeAudio(file)
      .then((buffer) => {
        if (!ignore) setPeaks(computePeaks(buffer, width));
      })
      .catch((e: unknown) => {
        if (!ignore) setError(`波形を作れませんでした(${e instanceof Error ? e.name : 'Error'})`);
      });
    return () => {
      ignore = true;
      URL.revokeObjectURL(url);
    };
  }, [file, width]);

  useEffect(() => {
    if (peaks) drawWaveform(canvasRef.current!, peaks, progress);
  }, [peaks, progress]);

  // During playback, read the playback position on every screen redraw
  useEffect(() => {
    const audio = audioRef.current!;
    let id = 0;
    const update = () => setProgress(audio.duration ? audio.currentTime / audio.duration : 0);
    const loop = () => {
      update();
      id = requestAnimationFrame(loop);
    };
    const start = () => {
      cancelAnimationFrame(id);
      loop();
    };
    const stop = () => {
      cancelAnimationFrame(id);
      update();
    };
    audio.addEventListener('play', start);
    audio.addEventListener('pause', stop);
    audio.addEventListener('seeked', update);
    return () => {
      cancelAnimationFrame(id);
      audio.removeEventListener('play', start);
      audio.removeEventListener('pause', stop);
      audio.removeEventListener('seeked', update);
    };
  }, []);

  // Seek to the clicked position on the waveform
  const seek = (e: MouseEvent<HTMLCanvasElement>) => {
    const audio = audioRef.current!;
    if (!audio.duration) return;
    const rect = e.currentTarget.getBoundingClientRect();
    audio.currentTime = ((e.clientX - rect.left) / rect.width) * audio.duration;
  };

  return (
    <div>
      {error ? <p role="alert">{error}</p> : !peaks && <p>波形を作っています…</p>}
      <canvas
        ref={canvasRef}
        onClick={seek}
        style={{ width, height, display: peaks ? 'block' : 'none', cursor: 'pointer' }}
      />
      <audio ref={audioRef} src={src || undefined} controls />
    </div>
  );
}

The caller passes the file chosen with <input type="file">. In the test page, I put this inside StrictMode.

tsx
function App() {
  const [file, setFile] = useState<File | null>(null);
  return (
    <>
      <input type="file" accept="audio/*" onChange={(e) => setFile(e.target.files?.[0] ?? null)} />
      {file && <AudioWaveform file={file} />}
    </>
  );
}

Waiting for Decoding Inside an Effect

Decoding is asynchronous, so another file might be selected while the first one is still being decoded. As in the official reference example for fetching data with an Effect, the cleanup sets ignore to true, so the result of an old file never goes into the state.

In the development build under StrictMode, decodeAudioData() was called twice when I selected the first file. React runs the setup and cleanup of an Effect one extra time only in development, and the result of the first run was discarded by ignore. In the production build, it was called once. When I selected the second and later files, it was called once each time, even in the development build.

The playback URL is also created in the same Effect, and the cleanup calls URL.revokeObjectURL() to release it. If you select a file that cannot be decoded, a message saying the waveform could not be created, with the error name EncodingError, appears, and the waveform is hidden.

Reading the Playback Position with requestAnimationFrame

The timeupdate event, which reports changes in the playback position, fires at a rate that depends on system load, about 4 to 66 times per second. In the test environment, I pressed play and waited 2 seconds, and timeupdate fired 7 times. If you move the line on each of these events, it moves only about once every 0.3 seconds.

So I start a requestAnimationFrame() loop on the play event, and read currentTime each time the screen is redrawn. During the same 2 seconds, the canvas was redrawn 116 times. Redrawing happens in an Effect that runs when progress changes, so during playback AudioWaveform also re-renders about the same number of times. To keep the code short, I made progress a state. Changing a ref does not cause a re-render, so you could store the playback position in a ref and redraw the canvas directly. I did not test that approach in this article. The loop stops on the pause event, so during the 1 second of pausing, the canvas was not redrawn at all. When playback reached the end, the events fired in the order pause, then ended, so the same handler stopped the loop.

Seeking to the Clicked Position

In seek, the code finds where the click falls across the width of the canvas, multiplies by duration, and sets the result as currentTime. For a 12-second audio file, clicking at 75% of the waveform's width while paused set currentTime to 9.00, and the canvas was redrawn once. This is because the progress state is updated by the seeked event that fires when the seek finishes, while playback is stopped.

To convert the clicked position to a time, the code uses the duration of the <audio> element, not the length of the AudioBuffer. For the Opus file, the AudioBuffer length was 12.000 seconds and the <audio> duration was 12.007 seconds, a small difference. The display offset is less than 1px, so I did not worry about it here.

Memory Use for Long Audio Files

Decoded data is an uncompressed Float32Array, so it is much larger than the original file. When I decoded a 3-minute stereo MP3 (4.1MB), it contained 2 channels × 7,938,000 numbers, and the Float32Array alone was 60.6MB. In the test environment, I ran it three times. Decoding took 0.3 to 0.8 seconds, and taking the min and max for the 600 segments took 37 to 56ms.

To reduce memory, you can lower the sample rate of the OfflineAudioContext. At 8000Hz, the same MP3 was 11.0MB. However, the conversion changes the values slightly. For the file with the 0.5ms loud sound, the max went from 0.945 to 0.965. If you only want the shape of the waveform, the difference is small. But if you want to show the values directly as volume, it is safer to keep the sample rate at 44100Hz, as in this code.

The size of the decoded data is proportional to its length. Since the 3-minute file was 60.6MB, a 1-hour stereo file at 44100Hz would be about 20 times that, roughly 1.2GB by calculation. The MDN explanation of AudioBuffer also says that AudioBuffer is mainly meant for short sounds, under 45 seconds.

​Posted by 86