日本語

How to Play a Sound Effect on Button Click in React

​​React​HTMLAudioElement,Playwright,TypeScript,Vite

To play a sound effect when a button is clicked in React, create an Audio from the audio file's URL, keep it in a useRef, and call play() in the click handler. This works for cases where you want a short sound to play the moment a button is pressed: a correct-answer sound in a quiz, a button sound in a game, or a notification sound when a form is submitted.

However, if you only call play(), the second and later presses don't play the sound when you press repeatedly. Here I try three ways of playing the sound, compare the differences, and bundle the approach into a hook called useSound. I also check why the sound can't play right after the screen opens.

Note

The test environment was Ubuntu 24.04, Node.js 22.23.4, and Chromium 153. I used a project created with the react-ts template of npm create vite (Vite 8.3.8, React 19.3.1, TypeScript 7.0.2) and placed a 0.4-second WAV file created with Node.js in it. I didn't use my ears to check whether the sound played. Instead, I used Playwright 1.63.0 to record the result of play() and the playing and ended events. I did not test Firefox, Safari, smartphone browsers, or playing sound with the Web Audio API.

Importing an audio file gives you a URL

In a Vite project, if you put an audio file under src and import it, you get the file's URL as a string. This works the same way as images, as described in Vite's static asset guide.

tsx
import clickUrl from './assets/click.wav'

The tsconfig.app.json in the react-ts template includes "types": ["vite/client"], and the type definitions in vite/client declare '*.wav'. So the type check passed without writing any type declarations yourself. .mp3 and .ogg are also declared in the same type definitions.

In my test, the value of clickUrl was /src/assets/click.wav under the dev server. In a page built and opened with vite preview, it was /assets/click-DoYyBeFc.wav. The 35,324-byte WAV file was output to dist/assets as a separate file.

Creating a new Audio on every press

The shortest approach is to create an Audio on every click and play it.

tsx
function NewEachTime() {
  const handleClick = () => {
    const audio = new Audio(clickUrl)
    audio.play()
  }
  return <button onClick={handleClick}>鳴らす</button>
}

I pressed the button three times, 100 milliseconds apart, for a 0.4-second sound and recorded the results. A separate audio element was created for each press, and all three reached playing. The three sounds overlapped, and each one played to the end (the 0.4-second position) and then fired ended.

If overlapping sounds are acceptable, this approach works. However, each press creates a new element and starts loading the file. As stated in the MDN description of the Audio() constructor, new Audio(url) sets preload to auto and starts loading as soon as the object is created. With the hook introduced later, you create one Audio when the screen opens, so loading can start before the first click.

Reusing one Audio makes repeated presses silent

Next, I tried keeping one Audio in useRef and calling only play() in the click handler.

tsx
function ReuseOnly() {
  const audioRef = useRef<HTMLAudioElement | null>(null)
  useEffect(() => {
    audioRef.current = new Audio(clickUrl)
  }, [])
  const handleClick = () => {
    audioRef.current?.play()
  }
  return <button onClick={handleClick}>鳴らす</button>
}

When I pressed the button three times, 100 milliseconds apart, only the first press reached playing. The second and third play() calls were made on an element that was already playing (paused was false), and their playback positions at that time were 0.027 seconds and 0.144 seconds. Those Promises resolved successfully, but the sound never restarted from the beginning, and ended fired only once.

Calling play() on an element that is already playing just continues the sound. To play it from the beginning, you need to move the playback position back to the start.

Setting currentTime to 0 before calling play()

Setting a value on currentTime moves the playback position to that point. When I set currentTime = 0 before calling play(), the sound restarted from the beginning on every press. For all three presses 100 milliseconds apart, the playback position was 0 at the time of play(), and playing fired each time.

The following image compares the two approaches with a 2-second sound. On a single click, I played two audio elements at once: one that only calls play(), and one that sets currentTime = 0 and then calls play(). The playback position of each is shown.

A screen where the sound-effect button is clicked three times at about 0.6-second intervals. The top row, labeled in Japanese (meaning "call only play()"), keeps advancing its playback position without stopping, up to 2 seconds. The bottom row, labeled in Japanese (meaning "set currentTime = 0, then play()"), resets its playback position to near 0 seconds on the second and third clicks.
Both methods played on a single click, with each audio’s playback position shown (2-second sound). The labels in the image are in Japanese: the top one means 'call only play()’, and the bottom one means 'set currentTime = 0, then play()’.

In the top row, which only calls play(), the playback position keeps advancing on the second and third presses, and the sound stops at 2 seconds. In the bottom row, the playback position returns to near 0 seconds on each press.

Choose between overlapping the same sound and restarting it from the beginning based on what you are building. If you want overlapping sounds, use the new Audio on every press approach from earlier.

Bundling it into a useSound hook

Here I bundle what I've covered into a hook that any component can use.

ts
// src/useSound.ts
import { useCallback, useEffect, useRef } from 'react'

type Options = {
  volume?: number
}

export function useSound(src: string, { volume = 1 }: Options = {}) {
  const audioRef = useRef<HTMLAudioElement | null>(null)

  useEffect(() => {
    const audio = new Audio(src)
    audioRef.current = audio
    return () => {
      audio.pause()
      audioRef.current = null
    }
  }, [src])

  useEffect(() => {
    if (audioRef.current) audioRef.current.volume = volume
  }, [src, volume])

  return useCallback(() => {
    const audio = audioRef.current
    if (!audio) return
    audio.currentTime = 0
    audio.play().catch((error: unknown) => {
      console.warn('効果音を再生できませんでした', error)
    })
  }, [])
}

I keep the Audio in a ref rather than in state because it isn't something that affects what's displayed. As described in the useRef reference, changing ref.current does not trigger a re-render.

I create the Audio inside an effect and call pause() in the cleanup. This stops a sound that is still playing when the component is removed from the screen. In development, StrictMode runs effects a second time, so Audio is created twice. The first one is paused by the cleanup, and the ref ends up holding the second one. In my test, play() was called on only one element.

The component that uses the hook just passes the returned function to onClick.

tsx
import clickUrl from './assets/click.wav'
import { useSound } from './useSound'

function QuizAnswerButton() {
  const playClick = useSound(clickUrl, { volume: 0.5 })
  return <button onClick={playClick}>答える</button>
}

volume takes a value from 0 to 1. In my test, the element's volume was 0.5 at the time of play(). In a page built and opened with vite preview, the sound also restarted from the beginning on all three presses, the same as under the dev server.

It doesn't play just because the screen opened

I tried playing the sound from an effect right after the screen opened, instead of when the button was pressed. In the Chromium test environment, play() failed. The Promise was rejected with the following error.

text
NotAllowedError: play() failed because the user didn't interact with the document first. https://goo.gl/xX8pDD

This is caused by the browser's autoplay restriction. According to the MDN autoplay guide, media with sound is generally allowed to autoplay only when a condition is met, such as the media being muted or the user having interacted with the site (clicking, tapping, pressing a key). The exact conditions differ between browsers. As noted in the play() documentation, this restriction also applies to play() called from a script.

If you call play() without a catch, the rejection is left unhandled. In my test, an unhandledrejection event fired, and Playwright reported it as a page error. The user can continue operating the page even when the sound doesn't play, so useSound catches the rejection and only logs a warning to the console.

In Chromium, I also found that once the user has clicked somewhere on the page, play() can be called outside an event handler. I clicked somewhere other than the button, then called play() from a timer 3 seconds later, and the sound played. However, as noted above, the exact conditions differ between browsers. To be safe, play sound effects inside event handlers such as clicks.

​Posted by 86