supergiox
supergiox

Reputation: 1596

Play mp3 file using javascript

Which is the best and cross-browser way to play a mp3 (very short) file via javascript? I tried different ways but there's always a problem...

EDIT 1:

I don't need a "full" player, I just need a function than I can call everytime something happens

EDIT 2:

Ok, I've to explain better my problem. The server is a smartphone connected in a LAN, but not always to the internet. I want to use mp3 because the file weighs only 3kb (instead of 60kb of wav), but if the mechanism to play this file is too "heavy" (a player or jquery.js) I think is better to use the wav file. Other suggestions?

Upvotes: 16

Views: 23158

Answers (3)

DenoryDevelopment
DenoryDevelopment

Reputation: 1

try using my own script,

<script src="https://webtinq.nl/ap/script.js></script>

and when that script is linked, the only thing you need to do is

play('example');

Upvotes: 0

Ties
Ties

Reputation: 5846

Use this:

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

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

Upvotes: 28

user240515
user240515

Reputation: 3207

Load the page with just a direct download to the audio file. Detect if the browser supports MP3s. If it does, progressively enhance the direct download into an AUDIO 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 would imagine that most of the zillions of prebuilt MP3 playing plugins work like this.

UPDATE:

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

Upvotes: 5

Related Questions