I want to play a mp3 using HTML 5 audio support. I was trying to use an audio tag but now I am doing it using javascript.
My "Player" will be just a tiny Play image, that when is pressed plays the audio (not all the audio control with progress).
I am trying to play it using javascript .
function playmp3(url){
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', url);
audioElement.load();
audioElement.play();
}
This is my code and it does not work. It executes ok when I click an image that is my Play button.
Url is a string that contains the url of a file.
I am testing in the newest versions of Chrome and FF.
Trying listening for the canplay
event before attempting to play the mp3. Here's an example of how to do that:
function playmp3(url){
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', url);
audioElement.load();
audioElement.addEventListener("canplay", function() {
audioElement.play();
});
}
The canplay
event is fired when the browser can start playing the mp3, but it doesn't guarantee that it can play the mp3 to completion. If that doesn't suite your purposes, there are a couple of other related events that you can listen to such as loadeddata
and canplaythrough
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With