日本語

How to Change Audio and Video Playback Speed in React Without Changing Pitch

​​React​Playwright,TypeScript,Web Audio API

To change the playback speed of audio or video in React, set a multiplier on the playbackRate of the audio or video element. While preservesPitch is true (the default), the pitch of the voice does not change. You cannot pass playbackRate as a JSX prop, so receive the element with a ref and set the value inside useEffect. Set preservesPitch the same way. This is useful for building a player that lets listeners play audio at double speed or slow it down.

Note

The test environment was Ubuntu 24.04, Node.js 22.23.4, and Chromium 153. I used react and react-dom 19.3.1, @types/react 19.3.0, typescript 7.0.2, esbuild 0.28.2, and Playwright 1.63.0. I type-checked the .tsx file with tsc, transformed it with esbuild, and ran it in a development build. The audio was a 12-second sine wave at 440 Hz made with ffmpeg (Opus in WebM). The browser was opened with Playwright at a screen width of 375 px. I did not test Firefox, Safari, the video element, or audio recorded from a human voice.

A component that switches speed and pitch

I placed six speed buttons and a "Keep pitch" checkbox (labeled in Japanese in the UI). The selected value is kept in state and applied to the audio element in useEffect.

tsx
import { useEffect, useRef, useState } from 'react';

const RATES = [0.5, 0.75, 1, 1.25, 1.5, 2];

type Props = { src: string };

export function SpeedPlayer({ src }: Props) {
  const audioRef = useRef<HTMLAudioElement>(null);
  const [rate, setRate] = useState(1);
  const [keepPitch, setKeepPitch] = useState(true);

  // Apply the selected speed to the audio element. Also setting defaultPlaybackRate keeps it from resetting when src changes
  useEffect(() => {
    const audio = audioRef.current;
    if (!audio) return;
    audio.defaultPlaybackRate = rate;
    audio.playbackRate = rate;
  }, [rate]);

  useEffect(() => {
    const audio = audioRef.current;
    if (!audio) return;
    audio.preservesPitch = keepPitch;
  }, [keepPitch]);

  return (
    <div className="player">
      {/* When the speed changes elsewhere, such as from the browser's built-in menu, onRateChange updates the display to match */}
      <audio
        ref={audioRef}
        src={src}
        controls
        preload="metadata"
        onRateChange={(e) => setRate(e.currentTarget.playbackRate)}
      />
      <div className="rates" role="group" aria-label="再生速度">
        {RATES.map((r) => (
          <button key={r} type="button" aria-pressed={r === rate} onClick={() => setRate(r)}>
            {r}倍
          </button>
        ))}
      </div>
      <label className="pitch">
        <input type="checkbox" checked={keepPitch} onChange={(e) => setKeepPitch(e.target.checked)} />
        声の高さを変えない
      </label>
    </div>
  );
}
Below the audio controls is a row of six speed buttons, from 0.5x to 2x (the labels are in Japanese). Only the 1.5x button has a light-blue border and bold light-blue text. Below them is a checked checkbox labeled "Keep pitch" (the label is in Japanese)
Stopped after playing at 1.5x. The selected button changes color through aria-pressed (the labels in the image are in Japanese)

playbackRate is a multiplier where normal speed is 1.0 (MDN: playbackRate). preservesPitch is a boolean that decides whether the pitch is corrected when the speed changes. Its default is true (MDN: preservesPitch). Both are properties of HTMLMediaElement, which audio and video share, so the same code works with a video element.

According to the MDN browser compatibility table, preservesPitch is available from Chrome 86, Firefox 101, and Safari 17.2. Older versions of Safari were listed as having the prefixed name webkitPreservesPitch. The TypeScript DOM type definitions (typescript 7.0.2) include preservesPitch, and the code compiled without adding any types.

Writing playbackRate in JSX does not change the speed

Passing it as a prop, as in <audio playbackRate={2} />, does not work. React does not treat it as a property of the element. In the test environment, playbackRate stayed at 1, and the element only received an HTML attribute named in lowercase, playbackrate. The development build also logs this error to the console:

text
props に書いた場合 {"playbackRate":1,"attributes":["src","controls","playbackrate"]}
React does not recognize the `playbackRate` prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase `playbackrate` instead. If you accidentally passed it from a parent component, remove it from the DOM element.

TypeScript also reports a type error, because the props of the audio element have no playbackRate. That is why the component above sets the value inside useEffect on the element it received through the ref.

Checking with a 440 Hz tone that the pitch does not change

For each combination of speed and preservesPitch, I measured the pitch of the output. I connected the audio element to a Web Audio API AnalyserNode and read the frequency with the strongest peak. To keep the previous setting from mixing into the next measurement, I reopened the page for each combination, pressed the speed button, unchecked the box when the value was false, and then played.

A bar chart with two bars for each speed. The light-blue bars for preservesPitch: true are all 439 Hz. The gray bars for false are 221 Hz at 0.5x and 880 Hz at 2x, so the pitch rises in proportion to the speed
Measured pitch (Hz) at each speed. The original tone is 440 Hz

With preservesPitch set to true, the pitch stayed at 439 Hz at both 0.5x and 2x. (The analyzer reads the frequency in fixed-width bins, so a 440 Hz tone shows up as 439.) With false, the pitch was 221 Hz at 0.5x and 880 Hz at 2x, changing in proportion to the speed.

text
速さ 2 倍・声の高さを変えない true {"playbackRate":2,"preservesPitch":true,"peakHz":[439,439,439],"advPerSec":2}
速さ 2 倍・声の高さを変えない false {"playbackRate":2,"preservesPitch":false,"peakHz":[880,880,880],"advPerSec":2}

peakHz holds three measurements taken every 0.5 seconds, starting 1 second after playback began. advPerSec is how many seconds of playback position advanced per second of real time. Even when the pitch is kept, the playback position advances at 2x. The HTML specification also says that when playbackRate is not 1.0 and preservesPitch is true, the element corrects the audio so that the original pitch is kept.

I also tested unchecking the box during playback. When I unchecked it while playing at 2x, the pitch changed from 439 Hz to 880 Hz after one second. I did not need to stop and play again.

text
再生中(2倍・チェックあり) 439
再生中にチェックを外して1秒後 [880,false]

Changing src resets the speed to 1x, so also set defaultPlaybackRate

In the component above, I set the same value on defaultPlaybackRate as well as on playbackRate. This keeps the speed from reverting when src changes, as in a playlist. When src changes, the browser reloads the element, and during that process it sets playbackRate back to the value of defaultPlaybackRate (HTML specification: media element load algorithm).

For comparison, I also made a component that sets only playbackRate. After choosing 2x and then changing src, the results were as follows. The naive at the start of the output is the result from this component. It has no checkbox, so checked is null.

text
naive 2倍にしたあと {"playbackRate":2,"defaultPlaybackRate":1,"preservesPitch":true,"pressed":"2倍","checked":null,"src":"tone.webm"}
naive src を変えたあと {"playbackRate":1,"defaultPlaybackRate":1,"preservesPitch":true,"pressed":"2倍","checked":null,"src":"tone2.webm"}

When only playbackRate was set, it returned to 1 after src changed. The 2x button stayed selected on screen, so the display and the actual speed did not match. The state rate did not change, so useEffect did not run again.

With SpeedPlayer, which also sets defaultPlaybackRate, the speed stayed at 2 after src changed. preservesPitch did not revert through the reload either, and it stayed false (the box was unchecked). The switch at the start of the next output is the result from SpeedPlayer.

text
switch 2倍にしたあと {"playbackRate":2,"defaultPlaybackRate":2,"preservesPitch":false,"pressed":"2倍","checked":false,"src":"tone.webm"}
switch src を変えたあと {"playbackRate":2,"defaultPlaybackRate":2,"preservesPitch":false,"pressed":"2倍","checked":false,"src":"tone2.webm"}

Using onRateChange to sync the display with a speed set in the browser's built-in menu

In Chromium, the browser's built-in controls, shown by the controls attribute, let you change the speed from the ︙ menu. When the speed changes on the element this way, a ratechange event fires (MDN: ratechange event). In React, you can receive it by putting onRateChange on the audio or video element (React reference: common props). In the component above, the state is updated to match the element's value at that point.

When I chose 1.5 in the menu, playbackRate became 1.5, and the 1.5x button on screen changed to the selected state. When I set audio.playbackRate = 1.25 from other code, the display likewise changed to 1.25x. I ran the playbackRate = 1.25 case on the page where I had already unchecked the box during playback, so preservesPitch stayed false. In the output, the first label, which means "controls," refers to the browser's built-in controls.

text
操作部品のメニューで 1.5 を選んだあと {"playbackRate":1.5,"defaultPlaybackRate":1.5,"preservesPitch":true,"pressed":"1.5倍","checked":true,"src":"tone.webm"}
外から playbackRate = 1.25 にしたあと {"playbackRate":1.25,"defaultPlaybackRate":1.25,"preservesPitch":false,"pressed":"1.25倍","checked":false,"src":"tone.webm"}

defaultPlaybackRate also has the same value because onRateChange changed the state, and that caused the useEffect above to run and set the value again.

The range of speeds you can set

If you set playbackRate to a value the browser does not support, a NotSupportedError exception is thrown (HTML specification: playbackRate). The specification does not define how wide the supported range is. In the Chromium test environment, 0.0625 and 16 were accepted. 0.05, 17, and -1 threw an exception, and the value stayed at the previous 1. 0 was accepted without an exception.

text
playbackRate = 0.05 {"ok":false,"error":"NotSupportedError: Failed to set the 'playbackRate' property on 'HTMLMediaElement': The provided playback rate (0.05) is not in the supported playback range.","playbackRate":1}
playbackRate = 17 {"ok":false,"error":"NotSupportedError: Failed to set the 'playbackRate' property on 'HTMLMediaElement': The provided playback rate (17) is not in the supported playback range.","playbackRate":1}

If you want to let users enter any speed in an input field, wrap the code that sets playbackRate in try and catch to handle the exception.

The MDN playbackRate page also says that audio is muted when the speed is too fast or too slow to be useful. As an example, it notes that Firefox (Gecko) mutes audio outside the range of 0.25 to 4. All six buttons in this article were chosen to fall within that range.

​Posted by 86