Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML 5 - Play tiny mp3 "inline"

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.

like image 663
Tony Avatar asked Oct 10 '22 02:10

Tony


1 Answers

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.

like image 195
Xavi Avatar answered Oct 23 '22 11:10

Xavi