13

UPDATE The problem lied with my lack of knowledge in the environment I was working on but the answers given below should be useful for others with similar problems.

EDIT: As it seems the problem is that there's something funky going on with trying to import my mp3 to my React app/component. The current issues is that when I try to use:

import soundfile from "../neure-resources/test.mp3"

I end up with an error of:

"Cannot find module "../neure-resources/test.mp3"

Solving this issue for any other import of an component would be to make sure that the component that is being imported has also been defined to be exportable but how would one go about doing this to an MP3-file?


So to start with I'm not sure if my problem has to do with importing/linking my mp3 file OR with how to play audio clips in React (or something else). I will edit the title once we figure out what my issue exactly is.

So I have an app where I have a button on the web page that the user can push to play a mp3-file. Simple stuff but I'm running constantly into the following error:

HTTP load failed with status 404. Load of media resource "..." failed.

Now while I am not super proficient in file paths etc. I'd figure by looking at guides and examples I could figure it out, but I haven't been able to.

My abbreviated file structure is something like (check bottom of post for more detailed description):

student/src/components

and under components I have my actual app in a folder and another folder under components where I planned to store my "resources" so:

components/my-app-folder/my-actual-app.tsx

components/my-resources/my.mp3

For the filepath as I understood

".."

signifies for the path to start from one folder above the current location which would be my

"/components" -folder

and my resources folder is under the component folder so I figured that should be fine. I looked up a few other SO questions about playing audio in React and found a question that suggested roughly the following:

Inside my

render()

let path = "../my-resources/test.mp3";
let audio = new Audio(path);

And then for the JSX part:

audioPlayer = (
            <div className="count-number-equivelance-audioPlayer">
                <button id="equivalence-audio-button" onClick={() => audio.play()}>Soundclip!</button>
            </div>
        ); 

I've tried:

let path = "../my-resources/test.mp3";

and

let path = "../../my-resources/test.mp3";

as I wasn't sure if one ".." pointed to the folder the actual app was nested in and required another ".." to actual point at the "components" folder but both of them produce the same error. I also tried using the whole path and moving the mp3 around to the same folder as the app itself but got the same result.

So I am thoroughly confused as to if I just suck at using external resources in my app or is my actual code and/or knowledge of React to blame here. The error I receive would lead me to believe that the resource isn't being located properly but I'm not sure if that's just a side effect of faulty code.

EDIT: I'm also working in a virtual environment, running my own stack locally if that makes some difference to the situation.

Also for reference a picture of the file tree:

The files opened in the picture contain the app in question and the resource it's trying to use:

File tree

The path leading up to components is the following (pic would be really big if I tried to grab the whole path in one picture).

/Users/"name of user"/arvio/client/student/src/components

3
  • Did you ever solve this? I have the same problem and would be grateful for tips
    – olefrank
    Jan 27, 2020 at 15:49
  • @olefrank In my case it was an issue with being new to the project and I hadn't been told yet that the environment I was working with assumed that the files were not local but on a server so I had to upload to a server that then fed me img/audio files to use in the project. I would assume that what Rahul Roy below said would work just fine in a local project on your own machine.
    – KsK
    Jan 28, 2020 at 8:43
  • 1
    I fixed it by putting the audio files in the "public" folder (Create React App) and referencing them like this: ${process.env.PUBLIC_URL}/audio/click.ogg
    – olefrank
    Jan 28, 2020 at 21:11

3 Answers 3

25

Inside the src/react-app-env.d.ts add this:

/// <reference types="react-scripts" />
declare module '*.mp3'; // '*.wav' if you're using wav format

Now you can use it like this:

import beep from './assets/beep.mp3';

const alarm = new Audio(beep);

By default, TypeScript won't allow you to import an audio file, so you need to declare it yourself.

This file react-app-env.d.ts references TypeScript types declarations that are specific to projects started with Create React App. By default, it only adds support for importing bmp, gif, jpeg, jpg, png, webp, and svg.

2
  • thanks for sharing this. Very insightful explanation.
    – Ebuka
    May 5, 2022 at 14:11
  • 3
    Avoiding any type with declare module '*.mp3' {const src: string; export default src} May 14, 2022 at 19:47
7

You can do something like

import React from "react";
const pokemon = require("./pokemon.mp3");

const sound = () => <audio src={pokemon} autoPlay />;

export default sound;

and then use it

import Soundify from "./soundify";
<Soundify />
2

Hi Ksk this is probably an error of wrong file path. Please test you file path in a separate tab on browser(chrome preferably). Enter the URL in new tab or using inspect element open the URL in new tab and check if you are able to access the mp3 file.

If the audio file gets played in the separate browser tab please share the file structure image.

<------------------- new edit ------------------->

Hi ksk to play an mp3 file or render an image in react you have to first import it as an alias and then at the path place you can use that alias. Take this example for clear understanding.

import React, { Component } from ‘react’;
import soundfile from ‘../assets/alert.mp3’

in the above the mp3 file is in a directory outside the code directory and then inside the assets folder. The .. operator is to move outside the current directory.

once you import the mp3 file you can render it in the html syntax as

    export default class Alert extends Component {
render() {
 return (
   <Sound
   url={soundfile}
   playStatus={Sound.status.PLAYING}
   onLoading={this.handleSongLoading}
   onPlaying={this.handleSongPlaying}
   onFinishedPlaying={this.handleSongFinishedPlaying}
   />
  );
 }
}

here this sample is using react-sound module you can also use the defualt html5 mp3 player and customize it according to your requirement.

Now coming up to the image you have uploaded and assuming the code is in NeureCountNumberEquivalence.tsx and mp3 file as test.mp3 your import syntax would look like.

import soundfile from ‘../neure-resources/test.mp3’

<audio controls>
  <source src={soundfile} type="audio/ogg">
  <source src={soundfile} type="audio/mpeg">
Your browser does not support the audio element.
</audio>

That's it :p hope this one works out for you.

For further reference you can use

mp3 in react

html5 audio component

4
  • I can just use the local file link on a web browser to play the mp3 if that's what you meant. I will add a picture of the file path to the original question. EDIT: Added pictures for better reference.
    – KsK
    Jul 24, 2019 at 13:30
  • Thanks for the response. When I follow your instructions and try to import the soundfile from "neure-resources" folder where it's located I get an error on the import line saying: "Cannot find module "../neure-resources/test.mp3"". I have no idea why this is happening though as you can see from my picture of the file path the folder is there and the mp3 is inside it. Do I need to somehow make the "neure-resources" file exportable first or something?
    – KsK
    Jul 26, 2019 at 8:58
  • no you don't need to make the mp3 file exportable in any way. That error occurs when the path is wrong. can you upload the code some where github/ or other hosting site
    – Rahul
    Jul 27, 2019 at 9:39
  • Unfortunately as this is not my own project but a company owned one (ant not open source), I am not able to share the code in it's entirety. I'll have one of my seniors check the problem out as they will be returning soon from their summer holidays. Was trying to be efficient and see if I could get it fixed before then. Thanks for all the help though!
    – KsK
    Jul 29, 2019 at 12:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.