How to dynamically import sound files in react?

Viewed 882
  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 file import log

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

2 Answers

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.

Related