在前端,有一个选择框和一个音乐播放器。
这是我的 html ,在Salvo Nostrato的帮助下:
<!DOCTYPE html>
<html>
<head>
<title> Test </title>
<script src="jquery-3.2.1.min.js"> </script>
<script src="whatToPlay.js"> </script>
</head>
<body onload="onload();">
<select id="changeselection" name="change-selection">
<option id="change1" value="change1" selected>Song 1</option>
<option id="change2" value="change2">Song 2</option>
<option id="change3" value="change3">Song 3</option>
</select>
<audio id="audio1" tabindex="0" controls="" type="audio/mpeg" controls preload>
<source id="audiochange" type="audio/mp3" src="audio/default.mp3">
Sorry, your browser does not support HTML5 audio.
</audio>
</body>
</html>
和我的 whatToPlay.js 文件,在Salvo Nostrato的帮助下( jQuery ):
$(document).ready(function() {
$("#changeselection").on("change",function(){
audio=$("#audio1");
$("#audio1").attr("src",src);
if($(this).val()=="change2"){
var src = "audio/song2.mp3";
console.log('change2');
}
else if ($(this).val()=="change3"){
var src = "audio/song3.mp3";
console.log('change3');
}
else {
var src = "audio/default.mp3";
console.log('change1');
}
audio=$("#audio1");
$("#audio1").attr("src",src);
audio[0].pause();
audio[0].load();//suspends and restores all audio element
audio[0].play();
});
});
当我选择歌曲2(id =&#34; change2&#34;)时,我想播放audio / song2.mp3,然后当结束时,我想立即播放audio / song2A.mp3。如何将其最小化添加到我的代码中?
答案 0 :(得分:1)
您必须为ended
事件使用事件处理程序。
这是我打字很快的东西......没有测试它。
但评论应该有助于这个想法。
$(document).ready(function() {
// Lookup for the audio element
var audio = $("#audio1");
// Lookup for the select element
var audioChange = $("#changeselection");
// Create an audio source array
var audioSources = [
"audio/default.mp3",
"audio/song2.mp3",
"audio/song3.mp3"
];
// Select change handler
audioChange.on("change",function(){
if($(this).val()=="change2"){
var src = audioSources[1];
console.log('change2');
}
else if ($(this).val()=="change3"){
var src = audioSources[2];
console.log('change3');
}
else {
var src = audioSources[0];
console.log('change1');
}
// Step 1 - Pause the playing audio
audio[0].pause();
// Step 2 - Change the audio source using what the above contitions determined.
audio.attr("src",src);
// Step 3 - Load this new source
audio[0].load();
// Step 4 - Play!
audio[0].play();
});
// Song ended handler
audio.on("ended", function() {
// Find what has just ended
var whichEnded = $(this).attr("src");
// Find its index in the array
var thisSrcIndex = audioSources.indexOf(whichEnded);
// If last index, set it to -1
if(thisSrcIndex==audioSources.length-1){
thisSrcIndex = -1;
}
// increment the index
thisSrcIndex++;
// Same steps as in the other handler here...
// Step 2 - Change the audio source using what the above contitions determined.
audio.attr("src",audioSources[thisSrcIndex]);
// Step 3 - Load this new source
audio[0].load();
// Step 4 - Play!
audio[0].play();
});
});