[ACCEPTED]-Play mp3 file using javascript-mp3

Accepted answer
Score: 27

Use this:

new Audio('your/url/here').play()

The documentation for the this 2 (HTMLAudioElement) can be found at MDN, note that most of 1 the controls are inherited by HTMLMediaElement.

Score: 5

Load the page with just a direct download 13 to the audio file. Detect if the browser 12 supports MP3s. If it does, progressively 11 enhance the direct download into an AUDIO 10 tag. Here's a sample:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Audio demo</title>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/modernizr/2.0.6/modernizr.min.js"></script>
</head>
<body>
    <p id="audio">
        <a href="BadAppleEnglish.mp3">Listen &raquo;</a>        
    </p>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
    <script src="audio.js"></script>
</body>
</html>

And the Javascript:

$(function () {
var audioElement = $('#audio'),
    href = audioElement.children('a').attr('href');
$.template('audioTemplate', '<audio src="${src}" controls>');
if (Modernizr.audio.mp3) {
    audioElement.empty();
    $.tmpl('audioTemplate', {src: href}).appendTo(audioElement);
}
});

I 9 would imagine that most of the zillions 8 of prebuilt MP3 playing plugins work like 7 this.

UPDATE:

Since you've edited the question 6 to specify that you'd prefer a solution 5 that doesn't use jQuery, I will point out 4 that rewriting this to not use jQuery is 3 trivial. It's just longer and less elegant. Do 2 keep in mind that Javascript libraries loaded 1 from CDNs are usually cached by the browser.

More Related questions