js控制audio播放的起始时间
2020-5-11 zhulinan JavaScript
<!DOCTYPE html><html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>js控制audio播放的起始时间</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
</head>
<body>
<div>IE11、Firefox下支持不好,苹果4s微信浏览器支持不好,在华为手机微信浏览器支持比较好。</div>
<div>参考资料:
<br />https://blog.csdn.net/huxiaoxiao_zero/article/details/45217591
<br />https://www.w3school.com.cn/tags/av_event_progress.asp
</div>
<audio id='myMp3' src='fly.mp3' controls='controls'></audio>
<div><a href='javascript:void()' onclick='startplay(200, 220)'>从200秒处开始播放到220秒</a></div>
<div id='myTs'></div>
<script type='text/javascript'>
var x = document.getElementById('myMp3');
var cur = 0;
var flag = 0;
var func1 = function(){
if (cur > 0 && x.currentTime >= cur) {
$('#myTs').html($('#myTs').html() + '<br />音频结束播放');
cur = 0;
x.pause();
x.removeEventListener('timeupdate', func1);
x.removeEventListener('progress', func2);
} else {
$('#myTs').html($('#myTs').html() + '<br />音频播放中 ...');
}
}
var fun2 = function(){
$('#myTs').html($('#myTs').html() + '<br />音频加载中 ...');
}
function startplay(starttime, endtime){
if(flag == 0){
flag = 1;
x.autoplay='autoplay';
x.load();
}
//浏览器是否支持fastSeek方法
if ("fastSeek" in x){
x.fastSeek(starttime);
$('#myTs').html($('#myTs').html() + '<br />浏览器支持fastSeek方法');
} else {
x.currentTime=starttime;//改变audio.currentTime的值
$('#myTs').html($('#myTs').html() + '<br />浏览器不支持fastSeek方法');
}
cur = endtime;
x.addEventListener("timeupdate", func1);
x.addEventListener("progress", func2);
x.play();
}
</script>
</body>
</html>