我建議你創建一個小的類是這樣的:
持續時間不能在Javascript(其實不是在每個瀏覽器中實現來搞定,你必須設置這個值每個 「歌」)
小提琴:http://jsfiddle.net/XYevE/4/
(諾塔:這個我只是一個例子,developped非常快... :))
HTML:
<a href="#" id="btn_start">PLAY</a>
<div id="timer"><span>click play</span></div>
<div id="ms">
Before callback:
<span id="mins"></span>:
<span id="secs"></span>
</div>
<audio id="audiosource">
<source src="http://www.cumfortitudine.com/vvdemo/assets/js/actions/vquery.vdemo/scenes/assets/sound/hans-zimmer-injection.mp3" type="audio/mpeg" />
</audio>
的Javascript:
function myApp() {
this.paused = false;
this.paused = true // set pause to true (stop)
this.isactive = false; // countdown is active
this.duration = 0; // set duration to 0 (get via audio DOM)
return this.observer(); // call and return the "observer" method of the "myApp" class
}
myApp.prototype.observer = function() { // observer method
var self = this; // set this to self (this is the current instance of this class)
$('#btn_start').on('click', function(event){ // where an user click on "btn_start"
event.preventDefault();
self.play('mp3'); // call the play method and store the state in a public var
self.countdown(self.onEnd); //parameter is the callback when the audio is finished
self.isactive = true;
});
return this; // return this instance
};
myApp.prototype.play = function() { // play method
var song = document.getElementById('audiosource');
this.duration = song.duration;
if (this.paused === true)
{
$('#btn_start').html('PAUSE');
console.log('set play song');
song.play();
this.paused = false;
}
else
{
$('#btn_start').html('PLAY');
console.log('set pause song');
song.pause();
this.paused = true;
}
return this;
};
myApp.prototype.countdown = function(duration, callback) { // countdown method
var self = this, // class instance
countdown = null, // countdown
ctx = null; // setIntervall clearer
timer = this.duration * 1000; // timer in milliseconds
if (this.isactive === true) // if this method yet called
{
return false;
}
countdown = function() {
if (timer <= 0)
{
self.isactive = false; // reset
clearInterval(ctx);
callback.call(this);
return false;
}
if (self.paused === false) // if not in pause
{
timer -= 250;
var mins = parseInt((timer/1000)/60);
var secs = parseInt((timer/1000) - mins * 60);
$('#mins').html(mins);
$('#secs').html(secs);
$('#timer > span').html(timer.toFixed(2));
}
};
ctx = setInterval(countdown, 250);
};
myApp.prototype.onEnd = function() {
// when the audio is finish..
alert ('end of the song');
};
;$(function() {
new myApp();
});
我會幫忙 –
我將創建一個小提琴評論(我有修復一些錯誤) –
http://jsfiddle.net/XYevE/1/ –