问题
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?
回答1:
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.
回答2:
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 »</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.
来源:https://stackoverflow.com/questions/9300655/play-mp3-file-using-javascript