5

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.

Tony
  • 10,088
  • 20
  • 85
  • 139
  • You want to play a video but it's an mp3 and you're using an audio tag? I'm confused. – Michael Berry Jan 02 '12 at 18:18
  • Are you saying you are seeing the wrong controls? What does you audio tag look like? Can you post some code examples? – Seth Jan 02 '12 at 18:20
  • Does Your browser has mp3 support? – Michas Jan 02 '12 at 18:35
  • @berry120 It was a mistake, it is fixed. No video tag. I just want to play audio. – Tony Jan 02 '12 at 19:42
  • @Seth I removed the audio tag and I am trying to do everything from javascript – Tony Jan 02 '12 at 19:42
  • @Michas I am using the latest versions of Chrome and Firefox – Tony Jan 02 '12 at 19:42
  • The Firefox doesn't support mp3 due to US patent issues. The support in Chrome is (was?) experimental and may be (have been?) dropped. It is possible to write the whole decoder in pure JavaScript, tough. Well, a lot of code. https://github.com/nddrylliog/jsmad If You want to play sound in Firefox or Chrome, You may use Ogg Vrobis. This audio format is supported. – Michas Jan 03 '12 at 00:46

1 Answers1

4

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.

Xavi
  • 20,111
  • 14
  • 72
  • 63