'How to import and play all audio files from a directory in React?
I am trying to play each audio file located inside a directory using React. I can play one file as follows but I do not want to import each file since there 70 files in the folder:
import {useEffect} from 'react';
import audio1 from '../../Storage/Audio/1.wav';
const Mp3player = () => {
const audioEl = new Audio(audio1);
const handlePlay = () =>{
audioEl.play();
}
useEffect(() => {
audioEl.load();
}, []);
return (
<div>
<h1>Player </h1>
<button onClick={handlePlay}> Play </button>
</div>
);
}
export default Mp3player;
I tried this:
import {useEffect} from 'react';
const r = require.context('../../Storage/Audio', false, /\.(wav)$/);
let audios = [];
r.keys().forEach((item) => {audios.push('file:../../Storage/Audio/' + String(item).substring(2))});
console.log(audios)
const Mp3player = () => {
const audioEl = new Audio(audios[0]);
console.log(audios[0]);
const handlePlay = () =>{
audioEl.play();
console.log("playing");
}
useEffect(() => {
audioEl.load();
}, []);
return (
<div>
<h1>Player </h1>
<button onClick={handlePlay}> Play </button>
</div>
);
}
export default Mp3player;
But no success playing the file.
How can I import and play all the audio files and get them inside an array or object?
EDIT: My .wav
files are named 1.wav
to 70.wav
, if that helps.
Thank you.
Solution 1:[1]
So this is the way I managed to solved it:
I have my videos in the
public
folder. For the purpose of this example, they are named:video1.mp4
andvideo2.mp4
.I used
react-player
library.
This is the resulting code:
import ReactPlayer from "react-player";
function App() {
const videoNames = [];
for (let i = 1; i < 3; i++) {
videoNames.push(`video${i}.mp4`);
}
const Videos = () => {
return (
<div>
{videoNames.map((videoName) => {
return (
<div>
<h1>{videoName}</h1>
<ReactPlayer url={videoName} controls={true} />;
</div>
);
})}
</div>
);
};
return <Videos />;
}
export default App;
I hope it helps.
Solution 2:[2]
I had te same problem and at the end i installed a package.
https://www.npmjs.com/package/react-audio-player
Is open source, Either to check the code or use it in your project... this could help you
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | programandoconro |
Solution 2 | Jose Javier Sanahuja |