Hooks version (React 16.8+):

Minimal version.

Place your music file (mp3) in the public folder.

import React from 'react';

function App() {
  let audio = new Audio("/christmas.mp3")

  const start = () => {
    audio.play()
  }

  return (
    < div >
      <button onClick={start}>Play</button>
    </div >
  );
}

export default App;
Answer from Hunter on Stack Overflow
Discussions

Playing sound with React
Hi all. I’ve been trying to get my code to play a sound in React. Off course I tried with the element in my React render method first, but that didn’t work. I have this now: [https://codepen.io/cynthiab72/pen/BazyvLg?editors=0111] from what I read here on the forums , others were having ... More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
0
0
October 11, 2020
A simple MP3 player with React.js
I've been learning React.js for the last few days and am working on a simple MP3 player. I have a few years experience with JavaScript, however, I am just trying to get used to the idea of components in React.js. More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
May 9, 2017
reactjs - How to load self hosted mp3 files on click in React Player - Stack Overflow
I use 16 React Players on my site and imported 16 different mp3 files. I´m worried about the loading time, so I thought it might be a good solution, if the mp3 file is only loaded, when the play bu... More on stackoverflow.com
🌐 stackoverflow.com
playing audio file while loading file in react
Well, you're going too have too pipe the audio from your api so that you can receive chunks and then use the web audio api to be able to play the audio, this is not one of simplest tasks lol, you can look at his to maybe help https://github.com/audiojs/web-audio-stream More on reddit.com
🌐 r/reactjs
2
2
July 8, 2021
🌐
Medium
theshubhagrwl.medium.com › you-might-not-need-a-sound-library-for-react-a265870dabda
You might not need a sound library for React | by Shubh Agrawal | Medium
December 8, 2022 - There are several buttons and when the user clicks on the button a certain audio is played. ... JavaScript takes care of the types but with TypeScript you gotta watch your step. Till now I have only worked with images in React so I googled how to use audio files and two libraries shot up. ... The work of libraries is to make the implementation simple and these perfectly do that. I implemented as it says in the docs. import useSound from 'use-sound'; import boopSfx from '../../sounds/boop.mp3'; const BoopButton = () => { const [play] = useSound(boopSfx); return <button onClick={play}>Boop!</button>; };
🌐
Clue Mediator
cluemediator.com › how-to-play-an-mp3-file-in-reactjs
How to play an mp3 file in ReactJS - Clue Mediator
In this short article, we’ll create an example to play an mp3 sound file in React.js.
🌐
Coderrocketfuel
coderrocketfuel.com › article › how-to-play-a-mp3-sound-file-in-react-js
How to Play a Mp3 Sound File in React.js
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> ) } }
🌐
GitHub
github.com › riyaddecoder › react-audio-play
GitHub - riyaddecoder/react-audio-play: A simple audio player component for react. · GitHub
import { useRef } from 'react'; import { AudioPlayer, AudioPlayerRef } from 'react-audio-play'; function App() { const playerRef = useRef<AudioPlayerRef>(null); const handlePlay = () => { playerRef.current?.play(); }; const handlePause = () => { playerRef.current?.pause(); }; const handleStop = () => { playerRef.current?.stop(); }; const handleFocus = () => { playerRef.current?.focus(); }; return ( <div> <AudioPlayer ref={playerRef} src="path/to/audio.mp3" autoPlay /> <button onClick={handlePlay}>Play</button> <button onClick={handlePause}>Pause</button> <button onClick={handleStop}>Stop</button> <button onClick={handleFocus}>Focus</button> </div> ); }
Starred by 39 users
Forked by 8 users
Languages   TypeScript 81.8% | CSS 13.6% | JavaScript 4.6%
🌐
npm
npmjs.com › package › react-mp3-player
react-mp3-player - npm
October 11, 2019 - Latest version: 0.8.2, last published: 6 years ago. Start using react-mp3-player in your project by running `npm i react-mp3-player`. There are no other projects in the npm registry using react-mp3-player.
      » npm install react-mp3-player
    
Published   Oct 11, 2019
Version   0.8.2
Author   Liam Riley
Find elsewhere
🌐
GitHub
github.com › akinozgen › react-youtube-mp3-player
GitHub - akinozgen/react-youtube-mp3-player: MP3 Player powered with youtube database.
import React from 'react'; const Store = React.createContext({ playlists: [], queue: [], search_query: '', search_results: [], current_song: null, is_playing: false, queue_position: 0, current_song_url: 'https://raw.githubusercontent.com/anars/blank-audio/master/5-seconds-of-silence.mp3', progress: 0 }); export default Store;
Starred by 18 users
Forked by 6 users
Languages   JavaScript 72.0% | CSS 22.3% | HTML 5.7% | JavaScript 72.0% | CSS 22.3% | HTML 5.7%
🌐
LogRocket
blog.logrocket.com › home › building an audio player in react to play sound or music
Building an audio player in React to play sound or music - LogRocket Blog
August 7, 2024 - Now, if we change the progress bar, the audio playback jumps to the specified position. Be aware that the time is static for now and the range progress color is not progressing. We will get there! In the context store, we’ll define their respective states with default values: export const AudioPlayerProvider = ({ children, }: { children: ReactNode; }) =>{ const [timeProgress,setTimeProgress] = useState<number>(0); const [duration, setDuration] = useState<number>(0); // ...
🌐
Josh W. Comeau
joshwcomeau.com › react › announcing-use-sound-react-hook
use-sound | a React hook that lets you play sound effects • Josh W. Comeau
The first thing we need to do is ... with this hook. If you're using something like create-react-app/Gatsby, you should be able to import MP3 files the same way you import other forms of media like images:...
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Playing sound with React - JavaScript
October 11, 2020 - Hi all. I’ve been trying to get my code to play a sound in React. Off course I tried with the <audio src="link to file" etc> element in my React render method first, but that didn’t work. I have this now: [https://c…
🌐
Stackademic
blog.stackademic.com › audioplayer-8277805853f1
AudioPlayer. How to Effortlessly Load MP3 in React… | by Studio Roma | Stackademic
February 27, 2024 - Welcome to our comprehensive guide on how to load MP3 files in React applications with ease. In this article, we will walk you through the step-by-step process of incorporating audio elements into your React projects, ensuring smooth playback and optimal performance.
🌐
GitHub
github.com › Khandakar227 › react-mp3
GitHub - Khandakar227/react-mp3: A minimalistic, simple Audio player using react js.
//ES6 import AudioPlayer from ...0/300.jpg?hmac=hMEuvTcrLNhrMSSGnaRit4YgalzJJ66stNu-UT70DKw'} ] } ]}/> ) } Now you can use useAudio hook to change audio track, play, pause and much more from anywhere in your react ...
Author   Khandakar227
🌐
SheCodes
shecodes.io › athena › 4615-how-to-play-local-audio-files-in-reactjs-app-component
[React] - How to Play Local Audio Files in ReactJS App | SheCodes
Learn how to use the React Audio Player package to play local audio files in your ReactJS app component with an example step-by-step guide.
🌐
Tomroth
tomroth.dev › react-sound
Playing a sound file with React and Webpack · Tom Roth
November 4, 2019 - import soundfile from '../sound.mp3'; Put this in whatever function you need to play the soundfile. let sound = new Audio(soundfile); sound.play(); Or if you define it in the component constructor, you can play and stop it with different functions. class App extends React.Component { ...
Top answer
1 of 1
5

First off, well done on getting it to work - that's often the most important and anything beyond that comes with experience and following the docs and guidelines.

First question:

In my experience your intuition to use a prop instead of storing the sounds in state is the right one. It is essentially ok the way you have it in state, but the less state your component stores and has to keep track of the easier it will be to reason about your code and track down any future bugs.

So something like:

var sounds = [...];

ReactDOM.render(
    <MusicPlayer sounds={sounds} />,
    document.getElementById('app')
);

Second question:

For this I would look at using a lifecyle hook [1], specifically componentDidMount() in your MusicPlayer class.

So, for example:

var MusicPlayer = React.createClass({            
    componentDidMount: function() {
        this.player = document.getElementById('audio_player');
    }
    ...
})

As a side note: I know too little about the player to actually comment on it's load() and play() functions. If you want that reviewed I'd need more info.

Just some general observations/suggestions:

I would look to make the Sound and Controls components stateless functional components [2]. As well as create an own stateless component for AudioPlayer that just takes a single prop of mp3src. And, in the process of doing that, move all state up and into the MusicPlayer to have that as your single point of truth (which, again, as mentioned above will make it easier to reason about your code and track down any bugs that may occur).

So, in the end the MusicPlayer's render function would resemble something like:

var MusicPlayer = React.createClass({            
    ...
    render: function () {       
        return(
            <div id="music_player">
                <Sounds />
                <Controls />
                <AudioPlayer />
            </div>  
        );  
    }
})

Also, as you can tell above, I would convert the Sound into more of a Sounds list component and move the DOM elements for it out of the MusicPlayer, meaning that the MusicPlayer need not be concerned with it's content.

Something like:

var Sounds = function(props) {
    return (
        <div className="scrollable_container scrollable">
            <ul id="list_of_sounds">
            {props.sounds.map(function(sound) {
                return (
                    <li className="sound_list_item">
                      <span className="sound_title">{sound.soundTitle}</span>
                      <span className="sound_length">{sound.soundLength}</span>
                    </li>
                );
            })}
            </ul>
        </div> 
    );
}

Additionally, I would look to simplify the way you set the next and previous sounds as the current sound, by simply setting the currentSoundIndex and using that to determine the mp3src prop that is handed down to the stateless components that require it in the MusicPlayer's render function. Using that you can reduce the complexity of the class functions and remove the need for a getSoundInfo function.

[1] https://facebook.github.io/react/docs/state-and-lifecycle.html

[2] https://facebook.github.io/react/docs/components-and-props.html#functional-and-class-components

🌐
CodeSandbox
codesandbox.io › s › reactplaysound-p47gk
React-play-sound - CodeSandbox
June 5, 2019 - React-play-sound by tian-yi using react, react-dom, react-scripts
Published   Jun 04, 2019
Author   tian-yi
🌐
GitHub
github.com › slash9494 › react-modern-audio-player
GitHub - slash9494/react-modern-audio-player: 🔊 Simple, accessible and flexible audio player
import AudioPlayer from 'react-modern-audio-player'; const playList = [ { name: 'name', writer: 'writer', img: 'image.jpg', src: 'audio.mp3', id: 1, }, ] function Player (){ return ( <AudioPlayer playList={playList} /> ) } interface AudioPlayerProps { playList: PlayList; audioInitialState?: InitialStates; audioRef?: React.MutableRefObject<HTMLAudioElement>; activeUI?: ActiveUI; customIcons?: CustomIcons; coverImgsCss?: CoverImgsCss; placement?: { player?: PlayerPlacement; playList?: PlayListPlacement; interface?: InterfacePlacement; volumeSlider?: VolumeSliderPlacement; }; rootContainerProps?: RootContainerProps } Prop ·
Starred by 331 users
Forked by 26 users
Languages   TypeScript 96.4% | HTML 1.6% | CSS 1.6% | TypeScript 96.4% | HTML 1.6% | CSS 1.6%
🌐
Stack Overflow
stackoverflow.com › questions › 63210869 › how-to-load-self-hosted-mp3-files-on-click-in-react-player
reactjs - How to load self hosted mp3 files on click in React Player - Stack Overflow
import React from 'react'; import ReactAudioPlayer from 'react-audio-player'; import Badge from 'react-bootstrap/Badge'; import mp3_file from '../assets/music/mein_ahnenland_peru_maintheme_titel_torben_jan_mueller.mp3'; import action from '../assets/music/99firefilm2018_torben_jan_mueller_16bit_48khz_v3m_action.mp3'; import adventure from '../assets/music/schmonz_ep2_goldgraeber3_torben_jan_mueller_ueberarbeitet_n_cut.mp3'; import animation from '../assets/music/revolution_radio_torben_jan_mueller_16bit_48khz_final_m.mp3'; import comedy from '../assets/music/99firefilm2018_torben_jan_mueller_1
🌐
npm
npmjs.com › package › react-h5-audio-player
react-h5-audio-player - npm
3 weeks ago - Latest version: 3.10.1, last published: 6 months ago. Start using react-h5-audio-player in your project by running `npm i react-h5-audio-player`. There are 64 other projects in the npm registry using ...
      » npm install react-h5-audio-player
    
Published   Aug 24, 2025
Version   3.10.1
Author   Hanz Luo