'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.



Solution 1:[1]

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

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

Solution 2:[2]

You can add typing to the mp3 files, if you are using typescript. To do this, create a types directory at the root directory with a defined file asset.d.ts and include in your configuration file:

types/asset.d.ts

declare module "*.mp3" {
  const value: any;
  export default value;
}

Then, add this to tsconfig.json:

tsconfig.json

{
  "compilerOptions": {
    //...
  },
  "include": [
    "src/*",
    "types/*"
  ]
}

Solution 3:[3]

Place it in the assets folder in order to access it. The following is on how to use it with images, however it works the same with audio files:

How to load image (and other assets) in Angular an project?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 PatMan10
Solution 2 Yan Pietro Barcellos Galli
Solution 3 PieterSchool