Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to play mp3 url in the background in reactjs app?

How do you add a mp3 url to your reactjs app and let it autoPlay in loop in the background?

I installed both reactplayer and react audio player packages.

Here's my code:

import "./App.css";
import ReactAudioPlayer from "react-audio-player";

function App() {
  return (
    <div className="App">
      <ReactAudioPlayer
        src="https://www.mboxdrive.com/SolarSymphony.mp3"
        autoPlay
        loop
      />
    </div>
);
}

export default App;
like image 339
nonameno Avatar asked Jan 22 '26 03:01

nonameno


1 Answers

You can load an mp3 file from an audio element.

  1. Make sure you move your music.mp3 into the /public folder. enter image description here
  2. Add an audio element inside the <body> of your index.html
    <audio id="audio" loop autoplay> 
      <source src="%PUBLIC_URL%/music.mp3" type="audio/mpeg">
    </audio>
    

Done!

If you want to control the audio to Play/Pause/Stop the music.

const audio: Partial<HTMLAudioElement> = document.getElementById('audio')

audio.pause()

You can call this from anywhere, remember to remove autoplay prop from the audio element if you don't want it to play when the app starts.

like image 60
Kuza Grave Avatar answered Jan 23 '26 16:01

Kuza Grave



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!