js实现音频轮播
实现音频轮播的基本思路
音频轮播通常指在网页中自动循环播放多个音频文件。可以通过JavaScript动态切换音频源并控制播放。
HTML结构准备
创建一个包含<audio>元素的容器,并设置必要的控制属性:
<audio id="audioPlayer" controls autoplay></audio>
JavaScript核心实现
定义音频列表和当前索引:
const audioList = [
'audio1.mp3',
'audio2.mp3',
'audio3.mp3'
];
let currentIndex = 0;
获取音频元素并加载第一个音频:

const audioPlayer = document.getElementById('audioPlayer');
audioPlayer.src = audioList[currentIndex];
添加事件监听实现自动轮播:
audioPlayer.addEventListener('ended', function() {
currentIndex = (currentIndex + 1) % audioList.length;
audioPlayer.src = audioList[currentIndex];
audioPlayer.play();
});
增强功能实现
添加手动控制按钮:
<button id="prevBtn">上一首</button>
<button id="nextBtn">下一首</button>
实现按钮功能:

document.getElementById('prevBtn').addEventListener('click', function() {
currentIndex = (currentIndex - 1 + audioList.length) % audioList.length;
audioPlayer.src = audioList[currentIndex];
audioPlayer.play();
});
document.getElementById('nextBtn').addEventListener('click', function() {
currentIndex = (currentIndex + 1) % audioList.length;
audioPlayer.src = audioList[currentIndex];
audioPlayer.play();
});
显示当前播放信息
添加显示当前曲目的元素:
<div id="nowPlaying">正在播放: <span id="currentSong"></span></div>
更新显示逻辑:
function updateDisplay() {
document.getElementById('currentSong').textContent =
audioList[currentIndex].split('/').pop();
}
在每次切换音频时调用:
audioPlayer.addEventListener('play', updateDisplay);
完整示例代码
<!DOCTYPE html>
<html>
<head>
<title>音频轮播示例</title>
</head>
<body>
<audio id="audioPlayer" controls autoplay></audio>
<div id="nowPlaying">正在播放: <span id="currentSong"></span></div>
<button id="prevBtn">上一首</button>
<button id="nextBtn">下一首</button>
<script>
const audioList = [
'audio1.mp3',
'audio2.mp3',
'audio3.mp3'
];
let currentIndex = 0;
const audioPlayer = document.getElementById('audioPlayer');
function loadAudio() {
audioPlayer.src = audioList[currentIndex];
audioPlayer.play();
}
function updateDisplay() {
document.getElementById('currentSong').textContent =
audioList[currentIndex].split('/').pop();
}
audioPlayer.addEventListener('ended', function() {
currentIndex = (currentIndex + 1) % audioList.length;
loadAudio();
});
document.getElementById('prevBtn').addEventListener('click', function() {
currentIndex = (currentIndex - 1 + audioList.length) % audioList.length;
loadAudio();
});
document.getElementById('nextBtn').addEventListener('click', function() {
currentIndex = (currentIndex + 1) % audioList.length;
loadAudio();
});
audioPlayer.addEventListener('play', updateDisplay);
loadAudio();
</script>
</body>
</html>






