EDIT: How to import MP3 files in React app

18,877

Solution 1

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

Solution 2

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 />

Solution 3

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.

Share:
18,877
KsK
Author by

KsK

Updated on July 18, 2022

Comments

  • KsK
    KsK almost 2 years

    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

  • KsK
    KsK almost 5 years
    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
    KsK almost 5 years
    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?
  • Rahul
    Rahul almost 5 years
    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
  • KsK
    KsK almost 5 years
    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!
  • Ebuka
    Ebuka about 2 years
    thanks for sharing this. Very insightful explanation.
  • Saber Hayati
    Saber Hayati about 2 years
    Avoiding any type with declare module '*.mp3' {const src: string; export default src}