Playing sound in reactjs

share link

by vsasikalabe dot icon Updated: Feb 16, 2023

technology logo
technology logo

Solution Kit Solution Kit  

The audio player is a technology that allows you to listen to audio files such as Mp3 and Wav audio formats, allowing you to add an audio player to your website for people to listen to and dance to 😀. Audio players can be added in a react component using the HTML audio element. 


The audio HTML tag makes play sounds directly from web applications using the below points: 

  • The src is the path of the audio file you want to import. 
  • The controls attribute enables the audio player to control features such as the play button, pause button, volume control bar, fast forward button, and back forward button buttons. 

You can take the example of the audio file in ReactJS Using Audio Class. You can also set the default state value of the song as not playing to make a function to handle the Play/Pause of the song. We can do these operations using the audio class's play() and pause() functions.  

The toggle method updates the player state value based on the following logic: 

  • Suppose an audio player is currently working (i.e., audio is playing), and the toggle technic targets this active player. You activated 'play' while another audio file was already playing. In that case, the playing state is false, and the targeted player's state is true. 
  • And, if the player is currently active, revert the targeted player's playing state to false [you clicked on 'pause'] 
  • If there is no player currently active, set the targeted player's state to true [you clicked on 'play' while no audio file was currently playing] 

Actual audio file control works in useEffect but is slightly more difficult as we have to iterate through the entire array of audio objects with every update. Event listeners for audio file 'ended' events are handled in a second useEffect. 


Here is an example of how to play a sound in reactjs: 

Preview of the output that you will get on running this code from your IDE

Code:

In this solution we use the React library.

class Music extends React.Component {
  state = {
    play: false
  }
  audio = new Audio(this.props.url)

  componentDidMount() {
    audio.addEventListener('ended', () => this.setState({ play: false }));
  }

  componentWillUnmount() {
    audio.removeEventListener('ended', () => this.setState({ play: false }));  
  }

  togglePlay = () => {
    this.setState({ play: !this.state.play }, () => {
      this.state.play ? this.audio.play() : this.audio.pause();
    });
  }

  render() {
    return (
      <div>
        <button onClick={this.togglePlay}>{this.state.play ? 'Pause' : 'Play'}</button>
      </div>
    );
  }
}

export default Music;

import React, { useState, useEffect } from "react";

const useAudio = url => {
  const [audio] = useState(new Audio(url));
  const [playing, setPlaying] = useState(false);

  const toggle = () => setPlaying(!playing);

  useEffect(() => {
      playing ? audio.play() : audio.pause();
    },
    [playing]
  );

  useEffect(() => {
    audio.addEventListener('ended', () => setPlaying(false));
    return () => {
      audio.removeEventListener('ended', () => setPlaying(false));
    };
  }, []);

  return [playing, toggle];
};

const Player = ({ url }) => {
  const [playing, toggle] = useAudio(url);

  return (
    <div>
      <button onClick={toggle}>{playing ? "Pause" : "Play"}</button>
    </div>
  );
};

export default Player;

import React, { useState, useEffect } from 'react'

const useMultiAudio = urls => {
  const [sources] = useState(
    urls.map(url => {
      return {
        url,
        audio: new Audio(url),
      }
    }),
  )

  const [players, setPlayers] = useState(
    urls.map(url => {
      return {
        url,
        playing: false,
      }
    }),
  )

  const toggle = targetIndex => () => {
    const newPlayers = [...players]
    const currentIndex = players.findIndex(p => p.playing === true)
    if (currentIndex !== -1 && currentIndex !== targetIndex) {
      newPlayers[currentIndex].playing = false
      newPlayers[targetIndex].playing = true
    } else if (currentIndex !== -1) {
      newPlayers[targetIndex].playing = false
    } else {
      newPlayers[targetIndex].playing = true
    }
    setPlayers(newPlayers)
  }

  useEffect(() => {
    sources.forEach((source, i) => {
      players[i].playing ? source.audio.play() : source.audio.pause()
    })
  }, [sources, players])

  useEffect(() => {
    sources.forEach((source, i) => {
      source.audio.addEventListener('ended', () => {
        const newPlayers = [...players]
        newPlayers[i].playing = false
        setPlayers(newPlayers)
      })
    })
    return () => {
      sources.forEach((source, i) => {
        source.audio.removeEventListener('ended', () => {
          const newPlayers = [...players]
          newPlayers[i].playing = false
          setPlayers(newPlayers)
        })
      })
    }
  }, [])

  return [players, toggle]
}

const MultiPlayer = ({ urls }) => {
  const [players, toggle] = useMultiAudio(urls)

  return (
    <div>
      {players.map((player, i) => (
        <Player key={i} player={player} toggle={toggle(i)} />
      ))}
    </div>
  )
}

const Player = ({ player, toggle }) => (
  <div>
    <p>Stream URL: {player.url}</p>
    <button onClick={toggle}>{player.playing ? 'Pause' : 'Play'}</button>
  </div>
)


export default MultiPlayer

import React from 'react'
import './App.css'
import MultiPlayer from './MultiPlayer'

function App() {
  return (
    <div className="App">
      <MultiPlayer
        urls={[
          'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3',
          'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3',
          'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-3.mp3',
        ]}
      />
    </div>
  )
}

export default App

Instructions

Follow the steps carefully to get the output easily.

  1. Install the Node.js and React on your IDE(preferable Visual Studio Code).
  2. Create React Application using npx create-react-app foldername.
  3. cd foldername.
  4. Open the folder in IDE.
  5. Copy the code using "copy" button above and create a Multiplayer.js file paste (from line no 66 to 149) it in that file(refer DEMO for additional files).Copy the code line no 150 to 168 and paste it into the App.js file.(remove earlier code from App.js)
  6. Open the terminal from IDE.
  7. npm start to run the file.


You can also refer this url DEMO for getting the above output easily.

I hope you found this useful. I have added the link to dependent libraries, version information in the following sections.


I found this code snippet by searching for Playing sound in reactjs in kandi. You can try any such use case!

Environment Tested

I tested this solution in the following versions. Be mindful of changes when working with other versions.

  1. The solution is created in VS Code 1.73.1 version.
  2. The solution is tested on Nodejs 16.14.2 version.
  3. react 18.2.0 version.


Using this solution, we are able to play sound in reactjs with simple steps. This process also facilities an easy way to use, hassle-free method to create a hands-on working version of code which would help us to play sound in reactjs.

Dependent Libraries

create-react-appby facebook

JavaScript doticonstar image 100082 doticonVersion:v5.0.1doticon
License: Permissive (MIT)

Set up a modern web app by running one command.

Support
    Quality
      Security
        License
          Reuse

            create-react-appby facebook

            JavaScript doticon star image 100082 doticonVersion:v5.0.1doticon License: Permissive (MIT)

            Set up a modern web app by running one command.
            Support
              Quality
                Security
                  License
                    Reuse

                      You can search for any dependent library on kandi like react.

                      Support

                      1. For any support on kandi solution kits, please use the chat
                      2. For further learning resources, visit the Open Weaver Community learning page

                      See similar Kits and Libraries