Blog Article: How to Add and Control Audio in ReactJS Using HTML <audio> Tag and Refs
Vivek Neupane
IT DEPENDS - FullStack Developer | ReactJS | NextJS | Astro | NodeJS | Express | MongoDB | Firebase | AWS | React Native
React allows us to build powerful and interactive interfaces, and adding sound to your React app can enhance the user experience. In this tutorial, we'll walk you through adding an audio element with play functionality using a React ref.
We'll use the <audio> HTML tag with a direct URL to a beep sound from the freeCodeCamp GitHub repository. By following this guide, you'll have a button that plays a sound when clicked.
Table of Contents
1. Why Use the <audio> Tag in React
The <audio> tag in HTML is the standard way to add audio playback to web pages. When used with React, it becomes a dynamic part of your component, giving you more control over when and how audio plays.
2. Setting Up the Audio Component
To set up audio in a React component, we’ll use the <audio> tag with a ref. A React ref allows us to directly access and control the HTML element.
The sound file we’re using is hosted online, so there’s no need to download it. Instead, we’ll use this URL directly: https://raw.githubusercontent.com/freeCodeCamp/cdn/master/build/testable-projects-fcc/audio/BeepSound.wav.
领英推荐
3. Using Refs in React
React refs provide a way to interact directly with DOM elements. This is particularly useful when dealing with media elements like audio or video. In our example, we'll use a ref to play the audio file.
4. Full Code Example
Let’s dive into the full code example below.
Full Code Example
import React, { useRef } from "react";
const AudioComponent = () => {
// Create a ref for the audio element
const audioRef = useRef(null);
// Function to play the audio
const playAudio = () => {
if (audioRef.current) {
audioRef.current.play();
}
};
return (
<div>
<h1>Play a Sound in React</h1>
<p>Click the button below to play a beep sound.</p>
{/* Audio element with ref and source */}
<audio ref={audioRef} src="https://raw.githubusercontent.com/freeCodeCamp/cdn/master/build/testable-projects-fcc/audio/BeepSound.wav" />
{/* Button to play the sound */}
<button onClick={playAudio}>Play Beep Sound</button>
</div>
);
};
export default AudioComponent;
5. Conclusion
Using the <audio> HTML tag with React’s ref system provides an effective and easy way to add sounds to your React applications. This approach works well for small audio files or simple interactions like notifications, alerts, or sound effects.
With these skills, you can make your app more engaging by adding sound-based feedback. Try experimenting with different audio sources and playback controls to enhance the audio experience further!