Playing Local Mp3 Files With React Js Without Importing
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:
- User selecting the file via a file
<input> - 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:
constSongCard = (props) => {
constplayAudio = () => {
let path = require("./" + props.song.path).default;
const audio = newAudio(path);
const audioPromise = audio.play();
if (audioPromise !== undefined) {
audioPromise
.then(() => {
// autoplay startedconsole.log("works");
})
.catch((err) => {
// catch dom exceptionconsole.info(err);
});
}
};
return (
<divclassName="songCard"><divclassName="coverContainer"><imgsrc="" /></div><divclassName="infoContainer"><divclassName="playPauseButton"onClick={playAudio}>
►
</div><divclassName="songTitle">{props.song.nom}</div></div></div>
);
};
exportdefaultSongCard;
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.
classAppextendsReact.Component {
render() {
return (
<div><audioref="audio_tag"src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3"controlsautoPlay/></div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById("app")
);<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script><divid="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"