How can I import all (mp3) files from a particular folder into an array in react.js?
Asked Answered
S

3

3

I'm building an mp3 player with react.js and the HTML5 web audio API. I'm new to react (circa 2 weeks) but have 3 years experience with JavaScript.

It seems that in order for the mp3 files to play/load into the audio tag (within a react environment using the cmd line and localhost) I need to import them to the application(rather than just pointing to their URL in the src of the audio tag). See my question here

So at the moment I am importing the sounds in a hard-coded fashion as follows:

import React, { Component } from 'react';
import './music-player.css';

import mp3_file0 from './sounds/0010_beat_egyptian.mp3';
import mp3_file1 from './sounds/0011_beat_euphoric.mp3';
import mp3_file2 from './sounds/0014_beat_latin.mp3';
import mp3_file3 from './sounds/0015_beat_pop.mp3';
import mp3_file4 from './sounds/0027_falling_cute.mp3';
import mp3_file5 from './sounds/0028_feather.mp3';
import mp3_file6 from './sounds/0036_lose_cute.mp3';
import mp3_file7 from './sounds/0039_pium.mp3';

var mp3s = [];

mp3s[0] = mp3_file0;
mp3s[1] = mp3_file1;
mp3s[2] = mp3_file2;
mp3s[3] = mp3_file3;
mp3s[4] = mp3_file4;
mp3s[5] = mp3_file5;
mp3s[6] = mp3_file6;
mp3s[7] = mp3_file7;


const AudioPlayer = function(props) {
    var mp3Src = mp3s[props.currentSoundIndex];
    console.log(mp3Src);
        return (<audio id="audio_player">
        <source id="src_mp3" type="audio/mp3" src={mp3Src}/>
        <source id="src_ogg" type="audio/ogg" src=""/>
        <object id="audio_object" type="audio/x-mpeg" width="200px" height="45px" data={mp3Src}>
            <param id="param_src" name="src" value={mp3Src} />
            <param id="param_src" name="src" value={mp3Src} />
            <param name="autoplay" value="false" />
            <param name="autostart" value="false" />
        </object>
        </audio>    
        );
}

export default AudioPlayer;

That works perfect, however ideally I would like to either:

1 import the mp3 files straight into an array (instead of creating the array afterwards). I tried the following, however I am receiving an error of "unexpected token" at the [ bracket (when importing)

var mp3s = [];

import mp3s[0] from './sounds/0010_beat_egyptian.mp3';
import mp3s[1] from './sounds/0011_beat_euphoric.mp3';

2 Or even better import all files from the sounds folder without knowing their names into a zero indexed array.

Any help greatly appreciated. thanks.

Smelt answered 24/5, 2017 at 10:34 Comment(3)
Did you try this? with a for loop. for (let i=0; i<7; i++) { let mp3s[i] = mp3file + i } I know it's not a full solution but hope it helps. But you could also try to rename your mp3 files to do that with another loop, and use index to call themObservable
@AdolfoOnrubia Thanks. well I had tried this for(x=0; x < 8; x++){mp3s[x] = 'mp3_file' + x;} however that only stored a string e.g 'mp3_file0' 'mp3_file1' etc into the array rather than the mp3 file object that i imported.Smelt
Are you importing file itself rather than just the path to it?Observable
S
2

I discovered that If you have multiple files (e.g images or mp3 files etc) that you want to include dynamically to your app then it is better to store them in the public folder (see the docs https://create-react-app.dev/docs/using-the-public-folder/).

Note: When storing your files in the public folder you don't need to "import" them but you must use the public environment variable (process.env.PUBLIC_URL) so that the correct path (to your public folder) will be referenced.

So my solution to this was:

  1. I created a folder in the public folder called sounds (where I stored all of my mp3s for this project).
  2. I then changed my the Audio component (in the original post) to the following:

.

import React, { Component } from 'react';
import './music-player.css';

const AudioPlayer = function(props) {
    let mp3Src = process.env.PUBLIC_URL + props.sounds[props.currentSoundIndex].mp3;
        return (<audio id="audio_player">
        <source id="src_mp3" type="audio/mp3" src={mp3Src}/>
        <source id="src_ogg" type="audio/ogg" src=""/>
        <object id="audio_object" type="audio/x-mpeg" width="200px" height="45px" data={mp3Src}>
            <param id="param_src" name="src" value={mp3Src} />
            <param id="param_src" name="src" value={mp3Src} />
            <param name="autoplay" value="false" />
            <param name="autostart" value="false" />
        </object>
        </audio>    
        );
}

export default AudioPlayer;

Note: props.sounds in the above code refers to the following JavaScript array which I have in my src folder:

let sounds = [{"title" : "Egyptian Beat", "artist" : "Sarah Monks", "length": 16, "mp3" : "sounds/0010_beat_egyptian.mp3"}, 
        {"title" : "Euphoric Beat", "artist" : "Sarah Monks", "length": 31, "mp3" : "sounds/0011_beat_euphoric.mp3"},
        {"title" : "Latin Beat", "artist" : "Sarah Monks", "length": 59, "mp3" : "sounds/0014_beat_latin.mp3"}, 
        {"title" : "Pop Beat", "artist" : "Sarah Monks", "length": 24, "mp3" : "sounds/0015_beat_pop.mp3"},
        {"title" : "Falling Cute", "artist" : "Sarah Monks", "length": 3, "mp3" : "sounds/0027_falling_cute.mp3"}, 
        {"title" : "Feather", "artist" : "Sarah Monks", "length": 6, "mp3" : "sounds/0028_feather.mp3"},
        {"title" : "Lose Cute", "artist" : "Sarah Monks", "length": 3, "mp3" : "sounds/0036_lose_cute.mp3"}, 
        {"title" : "Pium", "artist" : "Sarah Monks", "length": 3, "mp3" : "sounds/0039_pium.mp3"}];
Smelt answered 7/7, 2022 at 13:46 Comment(0)
O
0

Check this copeden here

var mp3_file = []
    mp3_file[0] = 'file1',
    mp3_file[1] = 'file2',
    mp3_file[2] = 'file3',
    mp3_file[3] = 'file4',
    mp3_file[4] = 'file5',
    mp3_file[5] = 'file6',
    mp3_file[6] = 'file7',    
    mp3s = [];

for (let i=0; i<6; i++) {   
  mp3s[i] = mp3_file[i]
  console.log(mp3s[i])
}
RESULT > 
"file1"
"file2" and so on.

And also this could be interesting

var mp3_file = [];
var mp3s = [];

for (let i=0; i<6; i++) {
  mp3_file[i = 'file' + i,
}           

for (let i=0; i<mp3_file.length; i++) {   
  mp3s[i] = mp3_file[i]
  console.log(mp3s[i])
}

Have "pros" and "contras" but I think you'll get the point.

Observable answered 24/5, 2017 at 13:59 Comment(3)
Thanks but was looking to do something like this. import mp3_files_array from './sounds'; In other words where I can import all the files together into an array.Smelt
Since you should only play 1 song at time, why to increase your .js file size with multiple files?. As far as I know, if you "import" an external file it will be included in bundle so have no sense for me. I suggest a better way just create an array of mp3 files urls.Observable
Thanks for all your help. Well you see what happened was because I had the sounds stored locally they wouldn't play on localhost without importing them to the application. However I have now decided to upload the sounds to a real domain and (like you said) point to the file URL instead. The sounds DO play in localhost this way so I've no need to import the files anymore thankfully. Thanks for the helpSmelt
P
0

If music in file are like ( songName_01.mp3 songName_02.mp3 songName_03.mp3 ...) you can import all of them in your react project

Instead of using

var songCollection = [];
import song01 from '../some file/songName01.mp3'
import song02 from '../some file/songName02.mp3'
import song03 from '../some file/songName0.mp3'
import song04 from '../some file/songName04.mp3'

   and then add them in array

Use this code transformation

var songCollection = []

    function _interopRequireDefault(obj) {
     return obj && obj.__esModule ? obj : { default: obj };
     }
    
    
    for(let i = 0; i< fileSize; i++ ) {
          songCollection[i] = _interopRequireDefault(require(`../some file/songName_0${i+1}.mp3`));
        
    }

And src value would be <audio src = {songName[2].default} ></audio>

Los-Track ( you can look at my repo how it works ) - https://github.com/sosumit001/los-track

Pyre answered 31/7, 2022 at 10:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.