[英]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.我正在尝试使用 React 播放位于目录内的每个音频文件。 I can play one file as follows but I do not want to import each file since there 70 files in the folder:我可以按如下方式播放一个文件,但我不想导入每个文件,因为文件夹中有 70 个文件:
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?如何导入和播放所有音频文件并将它们放入数组或 object 中?
EDIT: My .wav
files are named 1.wav
to 70.wav
, if that helps.编辑:如果有帮助,我的.wav
文件被命名为1.wav
到70.wav
。
Thank you.谢谢你。
I had te same problem and at the end i installed a package.我遇到了同样的问题,最后我安装了一个软件包。
https://www.npmjs.com/package/react-audio-player 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是开源的,要么检查代码要么在你的项目中使用它......这可以帮助你
So this is the way I managed to solved it:所以这就是我设法解决它的方式:
I have my videos in the public
folder.我的视频在public
中。 For the purpose of this example, they are named: video1.mp4
and video2.mp4
.出于本示例的目的,它们被命名为: video1.mp4
和video2.mp4
。
I used react-player
library.我使用react-player
库。
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.我希望它有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.