简体   繁体   中英

How to dynamically import sound files in react?

  const [soundFile, setSoundFile] = useState(null);

  useEffect(() => {
    async function importFile() {
      const file = await import(
        `../../assets/media/${teamimType}/humash/${teamimType}-parasha.wav`
      );
      setSoundFile(file);
    }
    importFile();
  }, []);

the import is working without errors, but when i use it in the sound component -

<AudioPlayer
   className="audio-player"
   style={{ direction: 'ltr' }}
   showJumpControls={false}
   autoPlay
   src={soundFile}  // <=====
/>

i get the following error: Uncaught (in promise) TypeError: Cannot convert object to primitive value ...

after the import, if i log the file i get 文件导入日志

probably the import method is wrong but i dont know what to do.. thanks!

i got it!

1. just use require instead of import =>

  useEffect(() => {
    const file = require(`../../assets/media/${teamimType}/humash/${teamimType}-parasha.wav`);
    setSoundFile(file);
  }, []);

2. or stay with import() but pass to the Audio component file.default (look at the picture in the question) =>

useEffect(() => {
    async function importFile() {
      const file = await import(
        `../../assets/media/${teamimType}/humash/${teamimType}-parasha.wav`
      );
      setSoundFile(file.default); // <==========
    }
    importFile();
  }, []);

You'd better use url than import and use it in AudioPlayer.

useEffect(() => {
         setSoundFile(`../../assets/media/${teamimType}/humash/${teamimType}-parasha.wav`)
    }
)
...
<AudioPlayer
   className="audio-player"
   style={{ direction: 'ltr' }}
   showJumpControls={false}
   autoPlay
   src={soundFile}
/>

In the AudioPlayer component, you can read file by async and process it.

Hope helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM