在react.js中导入和使用音频
我正在尝试创建一个UseAudio自定义挂钩,该挂钩将由我的应用程序中的声音效果按钮使用。
我已经像这样写了它:
import { useMemo, useEffect, useState } from 'react';
// import rain from 'assets/audio/rain.mp3'; --> hardcoded import I've tried
const useAudio = (url) => {
const audio = useMemo(() => new Audio(url), [url]);
const [playing, setPlaying] = useState(false);
const toggle = () => setPlaying(!playing);
useEffect(() => {
audio.loop = true;
playing ? audio.play() : audio.pause();
}, [playing, audio]);
useEffect(() => {
audio.addEventListener('ended', () => setPlaying(false));
return () => {
audio.removeEventListener('ended', () => setPlaying(false));
};
}, [audio]);
return [playing, toggle];
};
export default useAudio;
然后我使用它来尝试使其从外部重复使用:
const [playing, toggle] = useAudio(
require(`assets/audio/${props.audio}.mp3`)
);
两者都以裸路路径或内部require()给出此错误:
"Uncaught Error: The error you provided does not contain a stack trace"
"useAudio.js:14 Uncaught (in promise) DOMException: The element has no supported sources."
然后我尝试使用内部的硬编码文件导入钩子和它确实有效。知道我如何以可重复使用的方式写它吗?我想不出一种使进口动态的方法。
还希望了解路径参考,require()和导入的路径有什么区别,以及为什么反应以这种方式工作。谢谢
I am trying to create a useAudio custom hook that will be used by a sound effect button in my app.
I've written it like this:
import { useMemo, useEffect, useState } from 'react';
// import rain from 'assets/audio/rain.mp3'; --> hardcoded import I've tried
const useAudio = (url) => {
const audio = useMemo(() => new Audio(url), [url]);
const [playing, setPlaying] = useState(false);
const toggle = () => setPlaying(!playing);
useEffect(() => {
audio.loop = true;
playing ? audio.play() : audio.pause();
}, [playing, audio]);
useEffect(() => {
audio.addEventListener('ended', () => setPlaying(false));
return () => {
audio.removeEventListener('ended', () => setPlaying(false));
};
}, [audio]);
return [playing, toggle];
};
export default useAudio;
Then I used it like this to try and make it reusable from the outside:
const [playing, toggle] = useAudio(
require(`assets/audio/${props.audio}.mp3`)
);
Both sending it with the naked path or inside require() gives this error back:
"Uncaught Error: The error you provided does not contain a stack trace"
"useAudio.js:14 Uncaught (in promise) DOMException: The element has no supported sources."
Then I tried using a hardcoded file import inside the hook and it does work. Any idea how I could write it in a reusable way? I can't think of a way to make the imports dynamic.
Also would love to learn what's the difference between a path reference, require() and import, and why react works this way. Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将相对路径传递到JavaScript中的音频API。
这样尝试
You can pass relative paths to Audio api in javascript.
try it like this
我终于使它起作用了!在此处浏览了很多帖子后,我遇到了``.default''的要求函数。
I finally made it work! After browsing a lot of posts here, I came across adding '.default' to the require function like so: