最终效果预览

我们将制作一个类似下面这样的播放器:

jquery 制作网页音乐播放器
(图片来源网络,侵删)
  • 播放/暂停:点击按钮切换播放状态。
  • 上一首/下一首:可以切换播放列表中的歌曲。
  • 进度条
    • 显示当前播放进度。
    • 可以拖动进度条来快进或快退。
  • 音量控制:可以调节音量大小。
  • 当前歌曲信息:显示正在播放的歌曲名和歌手。
  • 播放列表:显示所有歌曲,并可点击切换。
  • 时间显示:显示当前播放时间和总时长。

第一步:准备工作

  1. 引入 jQuery 库: 我们需要一个 CDN 链接来引入 jQuery,这是最简单的方式。

  2. 准备音频文件: 你需要准备几首 .mp3 格式的音频文件,为了演示,我们将使用一些在线的示例音乐。

  3. 创建项目文件: 创建一个文件夹,并在其中创建以下三个文件:

    • index.html (页面结构)
    • style.css (样式)
    • script.js (jQuery 逻辑)

第二步:HTML 结构 (index.html)

这是播放器的骨架,我们将它分为几个主要部分:播放控制按钮、进度条、音量控制、歌曲信息和播放列表。

jquery 制作网页音乐播放器
(图片来源网络,侵删)
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">jQuery 音乐播放器</title>
    <link rel="stylesheet" href="style.css">
    <!-- 引入 jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <div class="music-player">
        <h1>我的音乐播放器</h1>
        <!-- 播放器主体 -->
        <div class="player-container">
            <!-- 歌曲信息 -->
            <div class="song-info">
                <h2 id="song-title">歌曲标题</h2>
                <p id="artist-name">歌手名</p>
            </div>
            <!-- 进度条 -->
            <div class="progress-container">
                <span id="current-time">0:00</span>
                <div class="progress-bar">
                    <div class="progress"></div>
                </div>
                <span id="duration">0:00</span>
            </div>
            <!-- 播放控制 -->
            <div class="controls">
                <button id="prev-btn" class="control-btn">
                    <i class="fas fa-step-backward"></i>
                </button>
                <button id="play-pause-btn" class="control-btn play-pause">
                    <i class="fas fa-play"></i>
                </button>
                <button id="next-btn" class="control-btn">
                    <i class="fas fa-step-forward"></i>
                </button>
            </div>
            <!-- 音量控制 -->
            <div class="volume-container">
                <i class="fas fa-volume-up"></i>
                <input type="range" id="volume-slider" min="0" max="100" value="50">
            </div>
        </div>
        <!-- 播放列表 -->
        <div class="playlist">
            <h3>播放列表</h3>
            <ul id="song-list">
                <!-- 歌曲列表将通过 JavaScript 动态生成 -->
            </ul>
        </div>
    </div>
    <!-- 引入 Font Awesome 图标库 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <!-- 引入我们的 JavaScript 文件 -->
    <script src="script.js"></script>
</body>
</html>

第三步:CSS 样式 (style.css)

为了让播放器看起来美观,我们需要添加一些样式,这里提供了一套现代简约的样式。

/* 基础样式 */
body {
    font-family: 'Arial', sans-serif;
    background-color: #f0f2f5;
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    margin: 0;
    color: #333;
}
.music-player {
    background-color: #fff;
    border-radius: 15px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
    padding: 30px;
    width: 400px;
    text-align: center;
}
h1 {
    margin-top: 0;
    color: #1a73e8;
}
/* 播放器主体 */
.player-container {
    margin-top: 20px;
}
/* 歌曲信息 */
.song-info {
    margin-bottom: 20px;
}
.song-info h2 {
    font-size: 1.5em;
    margin: 0;
}
.song-info p {
    color: #666;
    margin: 5px 0 0;
}
/* 进度条 */
.progress-container {
    display: flex;
    align-items: center;
    margin: 20px 0;
}
.progress-bar {
    flex-grow: 1;
    height: 6px;
    background-color: #e0e0e0;
    border-radius: 3px;
    cursor: pointer;
    position: relative;
}
.progress {
    height: 100%;
    background-color: #1a73e8;
    border-radius: 3px;
    width: 0%;
    transition: width 0.1s linear;
}
.progress-container span {
    font-size: 0.8em;
    color: #666;
    min-width: 40px;
}
/* 控制按钮 */
.controls {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 20px;
}
.control-btn {
    background: none;
    border: none;
    font-size: 1.5em;
    color: #333;
    cursor: pointer;
    transition: color 0.3s;
}
.control-btn:hover {
    color: #1a73e8;
}
.control-btn.play-pause {
    font-size: 2em;
    color: #1a73e8;
}
/* 音量控制 */
.volume-container {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
    margin-top: 20px;
}
.volume-container input[type="range"] {
    width: 100px;
    cursor: pointer;
}
/* 播放列表 */
.playlist {
    margin-top: 30px;
    text-align: left;
}
.playlist h3 {
    text-align: center;
    margin-bottom: 15px;
}
#song-list {
    list-style: none;
    padding: 0;
    max-height: 200px;
    overflow-y: auto;
}
#song-list li {
    padding: 10px;
    border-bottom: 1px solid #eee;
    cursor: pointer;
    transition: background-color 0.3s;
}
#song-list li:hover {
    background-color: #f5f5f5;
}
#song-list li.active {
    background-color: #e8f0fe;
    color: #1a73e8;
    font-weight: bold;
}

第四步:jQuery 逻辑 (script.js)

这是整个播放器的核心,我们将在这里实现所有的交互功能。

$(document).ready(function() {
    // --- 1. 定义播放器数据 ---
    // 使用一个数组来存储歌曲信息
    const songs = [
        { title: "夏日微风", artist: "轻音乐", src: "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3" },
        { title: "雨后彩虹", artist: "自然之声", src: "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3" },
        { title: "城市夜景", artist: "电子乐", src: "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-3.mp3" },
        { title: "森林晨曦", artist: "环境音", src: "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-4.mp3" }
    ];
    let currentSongIndex = 0; // 当前播放的歌曲索引
    let isPlaying = false;   // 播放状态
    // --- 2. 创建音频对象 ---
    const audio = new Audio(songs[currentSongIndex].src);
    // --- 3. DOM 元素 ---
    const playPauseBtn = $('#play-pause-btn');
    const prevBtn = $('#prev-btn');
    const nextBtn = $('#next-btn');
    const progressBar = $('.progress');
    const progressContainer = $('.progress-bar');
    const currentTimeEl = $('#current-time');
    const durationEl = $('#duration');
    const volumeSlider = $('#volume-slider');
    const songTitleEl = $('#song-title');
    const artistNameEl = $('#artist-name');
    const songListEl = $('#song-list');
    // --- 4. 初始化播放列表 ---
    function initPlaylist() {
        songListEl.empty(); // 清空列表
        songs.forEach((song, index) => {
            const li = $('<li></li>').text(`${song.title} - ${song.artist}`);
            if (index === currentSongIndex) {
                li.addClass('active');
            }
            songListEl.append(li);
        });
    }
    // --- 5. 格式化时间 (秒 -> mm:ss) ---
    function formatTime(seconds) {
        const minutes = Math.floor(seconds / 60);
        const remainingSeconds = Math.floor(seconds % 60);
        return `${minutes}:${remainingSeconds < 10 ? '0' : ''}${remainingSeconds}`;
    }
    // --- 6. 更新歌曲信息 ---
    function updateSongInfo() {
        songTitleEl.text(songs[currentSongIndex].title);
        artistNameEl.text(songs[currentSongIndex].artist);
        audio.src = songs[currentSongIndex].src;
        audio.play(); // 切换歌曲后自动播放
        isPlaying = true;
        updatePlayPauseButton();
        updatePlaylistHighlight();
    }
    // --- 7. 更新播放/暂停按钮图标 ---
    function updatePlayPauseButton() {
        const icon = playPauseBtn.find('i');
        if (isPlaying) {
            icon.removeClass('fa-play').addClass('fa-pause');
        } else {
            icon.removeClass('fa-pause').addClass('fa-play');
        }
    }
    // --- 8. 更新播放列表高亮 ---
    function updatePlaylistHighlight() {
        songListEl.find('li').removeClass('active');
        songListEl.find('li').eq(currentSongIndex).addClass('active');
    }
    // --- 9. 事件监听器 ---
    // 播放/暂停按钮点击事件
    playPauseBtn.on('click', function() {
        if (isPlaying) {
            audio.pause();
        } else {
            audio.play();
        }
        isPlaying = !isPlaying;
        updatePlayPauseButton();
    });
    // 上一首按钮点击事件
    prevBtn.on('click', function() {
        currentSongIndex = (currentSongIndex - 1 + songs.length) % songs.length;
        updateSongInfo();
    });
    // 下一首按钮点击事件
    nextBtn.on('click', function() {
        currentSongIndex = (currentSongIndex + 1) % songs.length;
        updateSongInfo();
    });
    // 点击播放列表中的歌曲
    songListEl.on('click', 'li', function() {
        currentSongIndex = $(this).index();
        updateSongInfo();
    });
    // 音频播放时更新进度条和时间
    audio.addEventListener('timeupdate', function() {
        const { currentTime, duration } = audio;
        const progressPercent = (currentTime / duration) * 100;
        progressBar.css('width', `${progressPercent}%`);
        currentTimeEl.text(formatTime(currentTime));
    });
    // 音频加载完成后显示总时长
    audio.addEventListener('loadedmetadata', function() {
        durationEl.text(formatTime(audio.duration));
    });
    // 点击进度条进行快进/快退
    progressContainer.on('click', function(e) {
        const width = $(this).width();
        const clickX = e.offsetX;
        const duration = audio.duration;
        audio.currentTime = (clickX / width) * duration;
    });
    // 音量滑块变化事件
    volumeSlider.on('input', function() {
        audio.volume = $(this).val() / 100;
    });
    // 音频播放结束时自动播放下一首
    audio.addEventListener('ended', function() {
        nextBtn.click();
    });
    // --- 10. 初始化 ---
    initPlaylist();
    updateSongInfo();
    audio.volume = volumeSlider.val() / 100; // 设置初始音量
});

代码逻辑详解

  1. 数据结构

    • 我们使用一个 songs 数组来存储所有歌曲的标题、艺术家和音频源地址,这使得管理播放列表变得非常容易。
  2. 核心对象

    • audio = new Audio(...):这是 JavaScript 原生的 Audio 对象,它提供了所有控制音频播放的方法(如 play(), pause())和属性(如 currentTime, duration, volume),jQuery 在这里主要负责 DOM 操作和事件绑定,而 Audio 对象负责实际的音频处理。
  3. 事件处理

    • .on('click', ...):这是 jQuery 的标准事件绑定方式,我们为播放/暂停、上一首、下一首和播放列表项绑定了点击事件。
    • audio.addEventListener(...):对于 Audio 对象本身触发的事件(如 timeupdate, loadedmetadata, ended),我们使用原生 JavaScript 的 addEventListener,这些事件在音频播放过程中会自动触发。
  4. 功能实现

    • 播放/暂停:通过检查 isPlaying 状态来决定是调用 audio.play() 还是 audio.pause(),并更新按钮图标。
    • 切换歌曲:改变 currentSongIndex,然后调用 updateSongInfo() 函数,这个函数会更新 UI 上的歌曲信息,并加载新的音频源。
    • 进度条
      • timeupdate 事件会持续触发,我们用它来获取当前的 currentTime,并计算百分比来更新进度条的宽度 css('width', ...)
      • 点击进度条时,我们计算点击位置占整个进度条宽度的比例,然后按比例设置 audio.currentTime,实现快进/快退。
    • 音量控制:监听 input 事件,将滑块的值(0-100)转换为 audio.volume(0-1)。
    • 自动播放下一首:监听 ended 事件,当一首歌播放完毕时,自动触发“下一首”按钮的点击事件。

如何运行

  1. 将上面的代码分别复制到 index.html, style.css, 和 script.js 文件中。
  2. 确保这三个文件在同一个文件夹下。
  3. 用浏览器打开 index.html 文件,你就可以看到一个功能完整的音乐播放器了!

这个项目是学习 jQuery DOM 操作、事件处理和与原生 JavaScript API 交互的绝佳范例,你可以基于这个代码继续扩展,比如添加随机播放、循环播放、歌词显示等更高级的功能。