html
<audio id="article_audio" class='article_audio' controls src='image/2.mp3'>
</audio>
<div class="audio_box">
<a id="play_btn" class="play_btn"></a>
<div id="pgs" class="pgs">
<div id="progress" class="pgs-play"></div>
<div id="circle" class="circle"></div>
</div>
<div class="time_p clearfix">
<span id="playedTime" class="playedTime" style="display: none">00:00</span>
<span id="totalTime" class="totalTime">00:00</span>
</div>
</div>
js
var audio = $('#article_audio').get(0);
var totalWidth = $("#pgs").width(); //进度条长度
function startAudio(){
audio.play();
$("#play_btn").addClass("on");
}
function endAudio(){
audio.pause();
$("#play_btn").removeClass("on");
}
/**
* 获取音频总时长,并转化为 00:00格式
*/
$('#article_audio').on("loadedmetadata",function () {
$('#totalTime').text(transTime(this.duration));
});
/**
* 开始/暂停按钮点击事件
*/
$("#play_btn").click(function(e){
if(audio.paused){
startAudio();
}else{
endAudio();
}
});
/**
* 播放进度
*/
audio.addEventListener('timeupdate',updateProgress,false);
//更新进度条
function updateProgress() {
var value = Math.round((Math.floor(audio.currentTime) / Math.floor(audio.duration)) * 100, 0);
$('.pgs-play').css('width', value + '%');
$("#circle").css({"left":(audio.currentTime/audio.duration)*totalWidth-1+"px"});
$("#playedTime").html(transTime(audio.currentTime));
}
$("#pgs").click(function(e){
var startX = $(this).offset().left; //进度条开始的x坐标
var endX = e.clientX; //点击事件的x坐标
rate = (endX - startX) / totalWidth;
$("#circle").css({"left":(endX-startX-1)+"px"});
audio.currentTime = rate*audio.duration;
updateProgress();
});
/**
* 播放结束
*/
audio.addEventListener('ended',endAudio,false);
$("#circle").on("touchstart",function(e){
endAudio();
});
$("#circle").on("touchmove",function(e){
e.preventDefault();
var startX = $("#pgs").offset().left; //进度条开始的x坐标
var endX = e.originalEvent.touches[0].clientX; //点击事件的x坐标
if((endX+1) > startX && endX < (startX+totalWidth)){ //触摸范围大于进度条起点,小于进度条终点
$("#circle").css({"left":(endX-startX-1)+"px"});
rate = (endX - startX) / totalWidth;
audio.currentTime = rate*audio.duration;
updateProgress();
}
});
$("#circle").on("touchstart",function(e){
startAudio();
});
//转换音频时长显示
function transTime(time) {
var duration = parseInt(time);
var minute = parseInt(duration/60);
var sec = duration%60+'';
var isM0 = ':';
if(minute == 0){
minute = '00';
}else if(minute < 10 ){
minute = '0'+minute;
}
if(sec.length == 1){
sec = '0'+sec;
}
return minute+isM0+sec
}
网友评论