Tuesday, June 8, 2021

How to Play a Mp3 Sound File in ReactJS

 

Are you 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 an example Mp3 file that sounds like a bell ringing.

Here's what the code looks like (we'll explain everything after):

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://assets.coderrocketfuel.com/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.

Advertisement
Learn to Build a Full-Stack React.js Application
Build and deploy a complete Hacker News clone with React.js, Node.js, and MongoDB.
VIEW COURSE

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's another example of playing the audio file on a button click user action:

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://assets.coderrocketfuel.com/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!

No comments:

Post a Comment

Technology’s generational moment with generative AI: A CIO and CTO guide

 Ref:  A CIO and CTO technology guide to generative AI | McKinsey 1. Determine the company’s posture for the adoption of generative AI As us...