我试图实现的效果是,悬停在某些图标上会播放某些音频文件。当您切换图标时,新音频将从最后一个音频关闭的确切时间开始播放 - 这应该就像您正在更改收音机上的频道一样。
下面的代码有效,但只在两个音频文件之间,并且它们被绑定到同一个按钮。
我如何复制这种效果,但是使用10"电台,"每个人都有自己的偶像?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title></title>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<script src="//code.jquery.com/jquery-2.1.3.js"></script>
<script>
var events=["abort","canplay","canplaythrough","durationchange","emptied","ended",
"error","loadeddata","loadedmetadata","loadstart","pause","play","playing",
"progress","ratechange","readystatechange","seeked","seeking","stalled",
"suspend","timeupdate","volumechange","waiting"]
$(function(){
var current={},
audio=$("audio")
audio.on("play",function(){
current = this // remember
})
$(".icon").hover(function(){
var last=$(this).text()
switch ( last ) {
case "start":
audio.first().trigger("play")
$(this).text("switch")
break;
case "switch":
var next=audio.not(current).prop("currentTime", current.currentTime).trigger("play")
audio.not(next).trigger("pause")
break
}
})
})
</script>
</head>
<body>
<div class="icon">start</div>
<audio class="radio1" controls>
<source src="assets/radio1.mp3" type="audio/mpeg">
</audio>
<audio class="radio2" controls>
<source src="assets/radio2.mp3" type="audio/mpeg">
</audio>
</body>
</html>
答案 0 :(得分:0)
无需添加多个图标。您可以通过创建变量current
和next
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>perfect</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<script src="//code.jquery.com/jquery-2.1.3.js"></script>
<script>
var events=["abort","canplay","canplaythrough","durationchange","emptied","ended",
"error","loadeddata","loadedmetadata","loadstart","pause","play","playing",
"progress","ratechange","readystatechange","seeked","seeking","stalled",
"suspend","timeupdate","volumechange","waiting"]
$(function(){
var current = -1;
var next = 0;
var aAudio = $('audio');
var audioLen = aAudio.length;
$(".icon").click(function(){
if(audioLen <= 0){
return false;
}else if(audioLen == 1){
aAudio.eq(next).trigger('play');
}else{
if(current == -1){
$(this).text("switch");
}else{
aAudio.eq(current).trigger('pause');
}
aAudio.eq(next).trigger('play');
current = next;
next = next == audioLen - 1?0:next+1;
}
console.log(current +'~~~~~'+ next);
})
})
</script>
</head>
<body>
<div class="icon">start</div>
<div class="m-audio-wrap">
<audio class="radio1" controls>
<source src="assets/radio1.mp3" type="audio/mpeg">
</audio>
<audio class="radio2" controls>
<source src="assets/radio2.mp3" type="audio/mpeg">
</audio>
<audio class="radio1" controls>
<source src="assets/radio1.mp3" type="audio/mpeg">
</audio>
<audio class="radio2" controls>
<source src="assets/radio2.mp3" type="audio/mpeg">
</audio>
</div>
</body>
</html>