如何用js控制audio元素连续播放mp3文件
展开全部
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>Document</title>
</head>
<body>
<audio id="myaudio"></audio>
</body>
<script>
// window.onload = function() {
//页面加载完成之后,通过给audio添加autoplay属性,音频下载完成之后自动播放
// var oAudio = document.getElementById('myaudio');
// oAudio.src = 'Le_Papillon.mp3';
// }
//mp3文件名
var mp3List = [
'Girlfriend.mp3',
'Have A Nice Day.mp3',
'Le Papillon.mp3',
'She Is.mp3',
'Tik Tok.mp3'
],
//文件路径
baseUrl = '../music/';
function getMusic(list) {
var len = list.length,
num = parseInt(Math.random()*len, 10),
music = baseUrl + list[num];
if(music) {
return music;
} else {
getMusic(list, baseUrl);
}
}
canPlay(playAudio);
//查看是否支持audio标签,如果支持,预加载当前指向mp3文件
function canPlay(callback) {
var currentFile = getMusic(mp3List);
try {
var audio = new Audio();
audio.oncanplay = function() {
callback(currentFile);
}
audio.src = currentFile;
audio.load();
}catch(e){
callback(false, e);
}
}
//play
function playAudio(currentFile) {
// Check for audio element support.
if (window.HTMLAudioElement && currentFile) {
try {
var oAudio = document.getElementById('myaudio');
oAudio.src = currentFile;
if (oAudio.paused) {
oAudio.play();
}
else {
oAudio.pause();
}
oAudio.onended = function() {
oAudio.src = getMusic(mp3List);
oAudio.play();
}
}
catch (e) {
// Fail silently but show in F12 developer tools console
if(window.console && console.error("Error:" + e));
}
}
}
</script>
</html>
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询