Skip to content Skip to sidebar Skip to footer

Playing Local Mp3 Files With React Js Without Importing

I want to create an app that shows different songs i've chosen, with react.js The problem is that it doesn't work with local files. Path is ok (just checked in the DOM) I've tried

Solution 1:

Due to security issues, you won't be able to access local files programatically from JavaScript running in browser.

The only way you can get a hold of local files is by:

  1. User selecting the file via a file <input>
  2. User drag and dropping the files into your application

This way the user is explicitly giving you access to those files.

You can either design your application around those interactions, or

You can start a web server locally where it has access to your audio files and stream those to your app or upload the files to a cloud service.


Solution 2:

you can do it by using this code:

const SongCard = (props) => {
const playAudio = () => {
    let path = require("./" + props.song.path).default;
    const audio = new Audio(path);
    const audioPromise = audio.play();
    if (audioPromise !== undefined) {
        audioPromise
            .then(() => {
                // autoplay started
                console.log("works");
            })
            .catch((err) => {
                // catch dom exception
                console.info(err);
            });
    }
};

return (
    <div className="songCard">
        <div className="coverContainer">
            <img src="" />
        </div>
        <div className="infoContainer">
            <div className="playPauseButton" onClick={playAudio}></div>
            <div className="songTitle">{props.song.nom}</div>
        </div>
    </div>
);
};

export default SongCard;

it'll work if you change the "./" in the require to the relative path of the audio's dictionary, and send only the name of the audio file in the parent's props

I hope I was help you


Solution 3:

Have you tried to use the <audio /> tag ?

Here is a React working audio exemple.

class App extends React.Component {
  render() {
    return (
     <div>
         <audio ref="audio_tag" src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3" controls autoPlay/>

     </div>
    );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById("app")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>

Find more information about the <audio /> tag here: https://www.w3schools.com/html/html5_audio.asp


Post a Comment for "Playing Local Mp3 Files With React Js Without Importing"