我尝试使用下面的代码播放声音,但它没有播放声音,所以我感到很难过,最后觉得可以在这里寻求帮助。
脚本
$(function() {
$('#btn_start').on('click', function(event){
event.preventDefault();
play_sound('mp3');
return false;
});
//------------------------
function play_sound(sound)
{
// This next line will get the audio element
// that is adjacent to the link that was clicked.
var song = $(this).next('audio').get(0);
if (song.paused)
song.play();
else
song.pause();
}
});
答案 0 :(得分:1)
我建议你创建一个像这样的小班:
持续时间无法通过Javascript获取(实际上并未在每个浏览器上实现,您必须为每个“歌曲”设置此值)
小提琴:http://jsfiddle.net/XYevE/4/
(nota:这只是一个例子,发展得非常快......:))
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();
});