我正在制作一个包装 html audio 和 source 标签的组件。目前,它在从外部源播放 mp3 文件时有效,例如此声音剪辑 https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3。同时,在尝试定位本地mp3文件时返回GET 404错误。这是为什么?
成分:
type Props = {
captionText: string,
src: string,
type?: string,
allowDownload: boolean,
}
export default function AudioPlayButton({
captionText,
src,
type = "mp3",
allowDownload = true,
}: Props) {
return <div>
<figure style={{...Style.column, ...Style.spaceAround}}>
<figcaption style={Style.caption}>{captionText}:</figcaption>
<audio controls>
{
type == "mp3" ?
<source src={src} type="audio/mp3"></source>
:
<></>
}
</audio>
<p>
{
allowDownload && type == "mp3" ?
<span>Download <a href={src}>MP3</a></span>
:
<></>
}
</p>
</figure>
</div>;
}
在最上面的页面.tsx:
'use client'
import AudioPlayButton from '@/components/showcase/ui/AudioPlayButton';
export default function Home() {
return (
<main>
This correctly shows sound player UI but with length 0:00 and can't load sound file. Console Returns ERROR 404 GET localhost:3000/name.mp3
<AudioPlayButton captionText={'Play Pronunciation'} src={"./name.mp3"} allowDownload={true}></AudioPlayButton>
This correctly loads mp3 and can play the sound by clicking the ui
<AudioPlayButton captionText={'Play Pronunciation'} src={"https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3"} allowDownload={true}></AudioPlayButton>
</main>
)
}
如果我尝试添加
import namePronunciation from "./name.mp3";
并将 src 更改为
<AudioPlayButton captionText={'Play Pronunciation'} src={namePronunciation } allowDownload={true}></AudioPlayButton>
NextJs VSCode 终端打印“找不到模块:无法解析'./name.mp3'”,我不明白?
据我所知,mp3 需要可用于
audio
标签的 GET 请求才能获取它。这意味着它必须可以通过网络调用使用(将其下载/流式传输到客户端浏览器)。
在您的应用程序中,这意味着您需要将 mp3 放在您的公共文件夹(或您指出的遥控器)中,以便可以通过
http://<your host>:<your port>/<path-to-mp3>.mp3
访问它
从您在代码中使用的路径来看,它似乎位于您的源代码中。
因此,通过一些文件夹结构,mp3 文件将驻留在
public/music/name.mp3
中,然后您可以使用如下 URL 发送它:
<AudioPlayButton captionText={'Play Pronunciation'} src={"/music/name.mp3"} allowDownload={true}></AudioPlayButton>
请注意,它以
/
开头,前面没有 .
。
在本地运行时的默认设置下,这意味着 mp3 在
http://localhost:3000/music/name.mp3
可用