<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>简易音乐播放器</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: "微软雅黑", sans-serif;
background-color: #f0f2f5;
padding: 20px;
}
.music-player {
max-width: 600px;
margin: 0 auto;
background: white;
border-radius: 12px;
padding: 25px;
box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}
.player-title {
text-align: center;
color: #333;
margin-bottom: 20px;
font-size: 24px;
}
.audio-container {
width: 100%;
margin: 20px 0;
}
audio {
width: 100%;
outline: none;
}
.song-list-title {
color: #444;
margin: 15px 0;
font-size: 18px;
}
.songs {
list-style: none;
}
.song-item {
padding: 12px 15px;
margin-bottom: 8px;
background-color: #f8f9fa;
border-radius: 6px;
cursor: pointer;
transition: all 0.2s;
display: flex;
align-items: center;
}
.song-item:hover {
background-color: #e9ecef;
}
.song-item.active {
background-color: #007bff;
color: white;
}
.song-index {
display: inline-block;
width: 24px;
height: 24px;
background-color: #ddd;
border-radius: 50%;
text-align: center;
line-height: 24px;
margin-right: 12px;
font-size: 14px;
}
.song-item.active .song-index {
background-color: white;
color: #007bff;
}
</style>
</head>
<body>
<div class="music-player">
<h1 class="player-title">音乐播放器</h1>
<div class="audio-container">
<audio id="musicPlayer" controls>
您的浏览器不支持音频播放功能
</audio>
</div>
<h3 class="song-list-title">歌曲列表</h3>
<ul class="songs" id="songList">
<!-- 歌曲列表将在这里动态生成 -->
</ul>
</div>
<script>
// 歌曲数据 - 这里使用示例音频链接,实际使用时替换为自己的音频路径
const songListData = [
{ name: "陈晓乐 - 刘三姐-等郎归低调门", url: "陈晓乐 - 刘三姐-等郎归低调门.mp3" },
{ name: "示例音乐2", url: "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3" },
{ name: "示例音乐3", url: "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-3.mp3" }
];
// 获取DOM元素
const musicPlayer = document.getElementById('musicPlayer');
const songList = document.getElementById('songList');
let activeSongItem = null;
// 初始化歌曲列表
function initSongList() {
// 清空列表
songList.innerHTML = '';
// 循环添加歌曲
songListData.forEach((song, index) => {
const li = document.createElement('li');
li.className = 'song-item';
li.innerHTML = `
<span class="song-index">${index + 1}</span>
<span class="song-name">${song.name}</span>
`;
// 存储歌曲URL
li.setAttribute('data-song-url', song.url);
// 绑定点击事件
li.addEventListener('click', function() {
playSelectedSong(this);
});
songList.appendChild(li);
});
}
// 播放选中的歌曲
function playSelectedSong(songItem) {
// 移除之前选中歌曲的激活状态
if (activeSongItem) {
activeSongItem.classList.remove('active');
}
// 设置当前选中歌曲
activeSongItem = songItem;
activeSongItem.classList.add('active');
// 获取歌曲URL并播放
const songUrl = songItem.getAttribute('data-song-url');
musicPlayer.src = songUrl;
musicPlayer.play().catch(error => {
console.log('播放失败:', error);
alert('播放失败,请检查音频文件是否存在或路径是否正确');
});
}
// 页面加载完成后初始化
window.onload = function() {
initSongList();
};
</script>
</body>
</html>
|
|