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.
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 them – Observable