Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import a sound file into react typescript component?

I have a small mp3 file located in project_root/src/audio/alarm.mp3.

I try to import like so:

  import alarm from "./audio/alarm.mp3";

But when I try to import it into App.tsx, I get this compiler error:

  Cannot find module './audio/alarm.mp3'.

But I can import images just fine.

like image 724
PatMan10 Avatar asked Nov 29 '22 21:11

PatMan10


2 Answers

Place the audio in the assets and write a custom typing file called audio.d.ts with the following code :-

declare module '*.mp3';

and place it in the root of your project under any name, ex: ./custom_typings/audio.d.ts.

Here, I have just done it for an mp3 file. After this go to your tsconfig.json and under "typeRoots" add the custom_typings folder.

"typeRoots": [
  "node_modules/@types",
  "custom_typings/"
] 

Once this is done you can just import the audio file from anywhere and use it normally as you would.

import {audioFile} from '../../../../assets/audio/audioFile.mp3';

TrackPlayer.add({
id: '1',
url: audioFile,
title: 'Example title',
artist: 'Example Artist',
artwork: 'https://picsum.photos/100',
});
like image 60
Amogh Wagh Avatar answered Dec 02 '22 10:12

Amogh Wagh


Found a solution to the issue. Instead of using ES6 import use ES5 require() for audio files. It works and the typescript compiler doesn't complain.

const alarm = require("./audio/alarm.mp3");

like image 41
PatMan10 Avatar answered Dec 02 '22 09:12

PatMan10