Reputation: 81
I want to include an audio player that plays a wav file that is loaded from a URL in a React component. Although this should work straight forward with the HTML5 <audio>
element, I cannot get it to play (I just see the control elements).
I tried to play a .mp3 with the same code, which works. I checked in Chrome and Safari which are supposed to support .wav - it works in neither of them. I tried to replace the <audio>
element with a react-audio-player, a react-player and a react-sound element - none of them works.
When I open the URL, the sound is downloaded as an attachment.
render() {
const wavUrl = config.fileServer+this.props.values.id+".wav";
return (
<audio controls>
<source src={wavUrl} type="audio/wav" />
Your browser does not support the audio element.
</audio>
);
}
I expect to see an audio controller that starts playing the sound when I press play. Instead, I see an audio controller that does nothing when I press play, and that claims that the audio file is 0 seconds long. I checked the URL - it is correct if I past it as URL in my browser directly.
Upvotes: 2
Views: 8402
Reputation: 1295
As mentioned Kitanga, you can use import to load files from public (instead of full URL access), example:
import somefile from '../public/assets/mp3/test1.mp3'
then
Play extends Component {
...
}
render(
<Play file=somefile>
)
But if you found webpack error message at start: "You may need an appropriate loader to handle this file type..." then seems you need to load appropriate extension npm package to read it and configure webpack.config.js, example:
...
module: {
rules: [
{
test: /\.mp3$/,
loader: "file-loader"
},
...
]
...
...
if "file-loader" not installed then use example:
npm install --save file-loader
Upvotes: 0
Reputation: 3565
If you are using create-react-app
you have to import the audio file.
import wavUrl from './path/to/file';
// ... rest of code here
Upvotes: 3