在CRA /打字稿中导入mp3文件



我有一个简单的应用程序内置在CRAv3.2.0。我使用默认设置的TypeScript(见下文tsconfig.ts(。/src/sounds/我有一个 mp3 文件"click_hi.mp3",我想在组件中使用,但我无法导入带有错误Cannot find module 'sounds/click_hi.mp3'.ts(2307)的 mp3 .

我尝试将文件放在与组件相同的文件夹中,以确保避免路径中的拼写错误。但是没有运气...如何导入 mp3 文件?

App.tsx

import React, { useState, useRef, useEffect } from "react";
import ReactDOM from "react-dom";
import { Sampler } from "tone";
import ClickHi from 'sounds/click_hi.mp3'

export default function ExercisePage() {
const [isLoaded, setLoaded] = useState(false);
const sampler = useRef(null);
useEffect(() => {
sampler.current = new Sampler(
{ "A1": ClickHi },
{
onload: () => {
setLoaded(true);
}
}
).toMaster();
}, []);
const handleClick = () => sampler.current.triggerAttack("A1");
return (
<div>
<button disabled={!isLoaded} onClick={handleClick}>
start
</button>
</div>
);
}

tsconfig.ts

{
"compilerOptions": {
"baseUrl": "src",
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react"
},
"include": ["src"]
}

对于仍然有此问题的任何人,就像我一样,不想将资产放在公共文件夹中,请使用">default"执行以下操作:

const path = require('../assets/audio/some_audio.mp3');
setAudio(new Audio(path.default));

注意:我只在使用TypeScript时遇到过这个问题。您需要为 mp3 声明一个模块,方法是将一个名为"audio.d.ts"的文件添加到项目 src 文件夹中,内容如下declare module '.*mp3';

简单应用程序工作的示例,使用以下命令:https://geocarlos.github.io/leiamos/

我通过将音频文件放在public文件夹中并像这样引用它来修复它:

useEffect(() => {
sampler.current = new Sampler(
{ A1: `${process.env.PUBLIC_URL}/audio/click_hi.mp3`},
() => {
setLoaded(true);
}
).toMaster();
}, []);

最新更新