How to Play a Mp3 Sound File in ReactJS
Looking for a way to play a short audio file or sound effect on your React website or application? In this article, we'll show you how to do that.
If you don't have a React application created already, you'll need one to get the code in this article to work.
We'll be playing a Mp3 file we use for our Pomodoro Timer. This is the sound we play whenever the timer ends.
Here's what the code looks like (we'll explain everything after):
JavaScript
 
import React, { Component } from "react"
 
export default class extends Component {
  componentDidMount() {
    const audioEl = document.getElementsByClassName("audio-element")[0]
    audioEl.play()
  }
 
  render() {
    return (
      <div>
        <audio className="audio-element">
          <source src="https://api.coderrocketfuel.com/assets/pomodoro-times-up.mp3"></source>
        </audio>
      </div>
    )
  }
}
Inside our render() function, we add an HTML <audio> element to embed the sound content in our page. Inside, we add a URL as the source of the Mp3 file.
Then, we grab the element with the getElementsByClassName() method. And actually play the sound with the audioEl.play() function.
So when you open that code in your browser, it will play the audio file when your React component is loaded in the componentDidMount() function.
Pretty sweet, huh? Here is another example of playing the audio file on a button click user action:
JavaScript
 
import React, { Component } from "react"
 
export default class extends Component {
  playAudio() {
    const audioEl = document.getElementsByClassName("audio-element")[0]
    audioEl.play()
  }
 
  render() {
    return (
      <div>
        <button onClick={this.playAudio}>
          <span>Play Audio</span>
        </button>
        <audio className="audio-element">
          <source src="https://api.coderrocketfuel.com/assets/pomodoro-times-up.mp3"></source>
        </audio>
      </div>
    )
  }
}
This code is the same as before, but with a couple changes.
First, we add a <button> with an onClick() method attached to it that calls our playAudio() function. And we play the audio with the same audioEl.play() function as before.
Whenever you click on the <button>, you should hear the timer ending sound.
Hopefully, this article helped in your coding journey! Thanks for reading and happy coding!