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.
So this is the way I managed to solve it:
I have my videos in the public
folder. For the purpose of this example, they are named: video1.mp4
and video2.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.