Reputation: 61
I've been trying to play an audio file in Recact.js but it doesn't play. I'm not facing any error the scroll bar shows up but play button doesn't work. I've tried playing the song to check if the file is corrupted. the mp3 file works fine.
import React from 'react'
class AudioPlayer extends React.Component {
render() {
return (
<div>
<audio ref="audio_tag" src="./abc.mp3" controls autoPlay/>
</div>
);
}
}
export default AudioPlayer;
Upvotes: 5
Views: 9176
Reputation: 1107
Since you are using create-react-app I suggest that you move your mp3 file to the public folder and then try the following with what I called pathToPublic whatever path you need to go down to your file:
import abc from '.../pathToPublic/public/abc.mp3'
<audio
ref="audio_tag"
autoPlay={true}
controls={true} >
<source type="audio/mp3" src={abc} />
</audio>
And let us know if it works.
Upvotes: 4
Reputation: 9787
./
is a relative path, so your audio file will need to be served from the same folder as your bundle.
If you want to keep your audio files and the player decoupled, this is fine, but to make it work sure that a) your file is copied to your app's output folder somewhere and b) you reference the path from the root, so something like:
class AudioPlayer extends React.Component {
render() {
return (
<div>
<audio ref="audio_tag" src="/assets/sounds/abc.mp3" controls autoPlay/>
</div>
);
}
}
You can alternatively import your audio file and use it directly:
import abc from './../path/to/file/abc.mp3';
class AudioPlayer extends React.Component {
render() {
return (
<div>
<audio ref="audio_tag" src={abc} controls autoPlay/>
</div>
);
}
}
Here's a working sandbox that demonstrates the importing method: https://codesandbox.io/s/strange-leakey-7lk6f
Upvotes: 2
Reputation: 601
Can you place right src file? or just put external if you want to check
<div>
<audio ref="audio_tag" src="https://file-examples.com/wp-content/uploads/2017/11/file_example_MP3_700KB.mp3" controls autoPlay/>
</div>
Or
<audio
ref="audio_tag"
autoPlay={true}
controls={true}>
<source type="audio/mp3" src="https://file-examples.com/wp-content/uploads/2017/11/file_example_MP3_700KB.mp3" />
</audio>
Upvotes: 0