最简单的 HTML5 音乐播放器

这是最基础的用法,直接使用 <audio> 标签,浏览器会提供默认的播放控件。

html5中网页音乐播放器代码
(图片来源网络,侵删)

代码:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">简单音乐播放器</title>
</head>
<body>
    <h1>简单音乐播放器</h1>
    <!-- 
      src: 音乐文件的路径。
      controls: 显示浏览器自带的播放控件(播放/暂停、进度条、音量等)。
    -->
    <audio src="path/to/your/music.mp3" controls></audio>
</body>
</html>

说明:

  • src: 属性指向你的音乐文件(如 .mp3, .wav, .ogg 格式)。
  • controls: 这是一个核心属性,告诉浏览器显示一套标准的播放控制界面。

功能更丰富的自定义音乐播放器

我们不希望使用浏览器默认的控件,因为它们的样式在不同浏览器中不一致,而且不够美观,下面我们将创建一个完全自定义的播放器,包含播放/暂停、进度条、时间显示、音量控制和播放列表。

这个例子会稍微复杂一些,包含 HTML、CSS 和 JavaScript。

html5中网页音乐播放器代码
(图片来源网络,侵删)

完整代码

你可以直接将以下代码保存为一个 .html 文件,并确保音乐文件路径正确即可运行。

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">自定义音乐播放器</title>
    <style>
        /* --- 基础样式 --- */
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
            background-color: #f0f2f5;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
        }
        /* --- 播放器容器 --- */
        .music-player {
            width: 400px;
            background-color: #fff;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            padding: 25px;
            text-align: center;
        }
        .player-info h2 {
            margin: 0 0 5px 0;
            font-size: 24px;
            color: #333;
        }
        .player-info p {
            margin: 0;
            color: #888;
            font-size: 14px;
        }
        /* --- 进度条 --- */
        .progress-container {
            width: 100%;
            height: 6px;
            background-color: #e0e0e0;
            border-radius: 3px;
            margin: 20px 0;
            cursor: pointer;
            position: relative;
        }
        .progress {
            height: 100%;
            background-color: #007bff;
            border-radius: 3px;
            width: 0%;
            transition: width 0.1s linear;
        }
        .time-info {
            display: flex;
            justify-content: space-between;
            font-size: 12px;
            color: #888;
            margin-bottom: 20px;
        }
        /* --- 控制按钮 --- */
        .controls {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 20px;
        }
        .controls button {
            background: none;
            border: none;
            cursor: pointer;
            font-size: 24px;
            color: #333;
            transition: color 0.2s;
        }
        .controls button:hover {
            color: #007bff;
        }
        .play-pause-btn {
            font-size: 32px;
            background-color: #007bff;
            color: white;
            width: 50px;
            height: 50px;
            border-radius: 50%;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        /* --- 音量控制 --- */
        .volume-container {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            margin-top: 15px;
        }
        .volume-slider {
            width: 100px;
            height: 5px;
            -webkit-appearance: none;
            appearance: none;
            background: #e0e0e0;
            border-radius: 5px;
            outline: none;
        }
        .volume-slider::-webkit-slider-thumb {
            -webkit-appearance: none;
            appearance: none;
            width: 15px;
            height: 15px;
            background: #007bff;
            cursor: pointer;
            border-radius: 50%;
        }
        /* --- 播放列表 --- */
        .playlist {
            margin-top: 20px;
            text-align: left;
        }
        .playlist-item {
            padding: 10px;
            border-radius: 8px;
            cursor: pointer;
            transition: background-color 0.2s;
        }
        .playlist-item:hover {
            background-color: #f0f2f5;
        }
        .playlist-item.active {
            background-color: #e7f1ff;
            color: #007bff;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="music-player">
        <!-- 播放器信息 -->
        <div class="player-info">
            <h2 id="song-title">歌曲标题</h2>
            <p id="artist-name">艺术家</p>
        </div>
        <!-- 进度条 -->
        <div class="progress-container" id="progress-container">
            <div class="progress" id="progress"></div>
        </div>
        <div class="time-info">
            <span id="current-time">0:00</span>
            <span id="duration">0:00</span>
        </div>
        <!-- 控制按钮 -->
        <div class="controls">
            <button id="prev-btn">⏮</button>
            <button id="play-pause-btn" class="play-pause-btn">▶</button>
            <button id="next-btn">⏭</button>
        </div>
        <!-- 音量控制 -->
        <div class="volume-container">
            <span>🔊</span>
            <input type="range" class="volume-slider" id="volume-slider" min="0" max="1" step="0.01" value="1">
        </div>
        <!-- 播放列表 -->
        <div class="playlist" id="playlist">
            <!-- 播放列表项将通过 JavaScript 动态生成 -->
        </div>
    </div>
    <!-- 隐藏的 audio 元素,所有操作都基于它 -->
    <audio id="audio-player"></audio>
    <script>
        // 获取 DOM 元素
        const audioPlayer = document.getElementById('audio-player');
        const playPauseBtn = document.getElementById('play-pause-btn');
        const prevBtn = document.getElementById('prev-btn');
        const nextBtn = document.getElementById('next-btn');
        const progress = document.getElementById('progress');
        const progressContainer = document.getElementById('progress-container');
        const currentTimeEl = document.getElementById('current-time');
        const durationEl = document.getElementById('duration');
        const volumeSlider = document.getElementById('volume-slider');
        const songTitleEl = document.getElementById('song-title');
        const artistNameEl = document.getElementById('artist-name');
        const playlistEl = document.getElementById('playlist');
        // 播放列表数据
        const playlist = [
            { src: 'song1.mp3', title: '夜曲', artist: '周杰伦' },
            { src: 'song2.mp3', title: '晴天', artist: '周杰伦' },
            { src: 'song3.mp3', title: '七里香', artist: '周杰伦' }
        ];
        let currentSongIndex = 0;
        // 初始化播放列表
        function initPlaylist() {
            playlistEl.innerHTML = '';
            playlist.forEach((song, index) => {
                const item = document.createElement('div');
                item.className = 'playlist-item';
                if (index === currentSongIndex) {
                    item.classList.add('active');
                }
                item.innerHTML = `<strong>${song.title}</strong> - ${song.artist}`;
                item.addEventListener('click', () => loadSong(index));
                playlistEl.appendChild(item);
            });
        }
        // 加载歌曲
        function loadSong(index) {
            currentSongIndex = index;
            const song = playlist[currentSongIndex];
            audioPlayer.src = song.src;
            songTitleEl.textContent = song.title;
            artistNameEl.textContent = song.artist;
            // 更新播放列表高亮
            document.querySelectorAll('.playlist-item').forEach((item, i) => {
                if (i === index) {
                    item.classList.add('active');
                } else {
                    item.classList.remove('active');
                }
            });
            audioPlayer.play();
            playPauseBtn.textContent = '⏸';
        }
        // 播放/暂停
        function togglePlayPause() {
            if (audioPlayer.paused) {
                audioPlayer.play();
                playPauseBtn.textContent = '⏸';
            } else {
                audioPlayer.pause();
                playPauseBtn.textContent = '▶';
            }
        }
        // 更新进度条
        function updateProgress() {
            const { duration, currentTime } = audioPlayer;
            const progressPercent = (currentTime / duration) * 100;
            progress.style.width = `${progressPercent}%`;
            // 更新时间显示
            currentTimeEl.textContent = formatTime(currentTime);
            if (!isNaN(duration)) {
                durationEl.textContent = formatTime(duration);
            }
        }
        // 设置进度条
        function setProgress(e) {
            const width = this.clientWidth;
            const clickX = e.offsetX;
            const duration = audioPlayer.duration;
            audioPlayer.currentTime = (clickX / width) * duration;
        }
        // 格式化时间 (秒 -> mm:ss)
        function formatTime(seconds) {
            const minutes = Math.floor(seconds / 60);
            const secs = Math.floor(seconds % 60);
            return `${minutes}:${secs < 10 ? '0' : ''}${secs}`;
        }
        // 上一首
        function prevSong() {
            currentSongIndex--;
            if (currentSongIndex < 0) {
                currentSongIndex = playlist.length - 1;
            }
            loadSong(currentSongIndex);
        }
        // 下一首
        function nextSong() {
            currentSongIndex++;
            if (currentSongIndex >= playlist.length) {
                currentSongIndex = 0;
            }
            loadSong(currentSongIndex);
        }
        // 事件监听器
        playPauseBtn.addEventListener('click', togglePlayPause);
        prevBtn.addEventListener('click', prevSong);
        nextBtn.addEventListener('click', nextSong);
        audioPlayer.addEventListener('timeupdate', updateProgress);
        audioPlayer.addEventListener('ended', nextSong); // 歌曲结束时自动播放下一首
        progressContainer.addEventListener('click', setProgress);
        volumeSlider.addEventListener('input', (e) => {
            audioPlayer.volume = e.target.value;
        });
        // 初始化
        initPlaylist();
        loadSong(0); // 加载第一首歌
        audioPlayer.volume = volumeSlider.value; // 设置初始音量
    </script>
</body>
</html>

代码详解

HTML 结构

  1. <audio>:

    • 我们创建了一个隐藏的 <audio> 元素 (<audio id="audio-player"></audio>),所有对音频的实际操作(如播放、暂停、加载源文件)都通过 JavaScript 控制这个元素来完成,这样做的好处是我们可以完全自定义 UI,而不受浏览器默认控件的限制。
  2. UI 容器:

    • .music-player: 整个播放器的包裹盒。
    • .player-info: 显示歌曲标题和艺术家。
    • .progress-container.progress: 进度条的背景和填充部分,我们通过改变 .progresswidth 来模拟播放进度。
    • .controls: 包含播放/暂停、上一首、下一首按钮。
    • .volume-container: 包含音量滑块。
    • .playlist: 显示歌曲列表。

CSS 样式

  • 使用 Flexbox (display: flex) 来轻松实现元素的居中对齐和均匀分布。
  • 进度条和音量滑块使用了原生滑块样式 (-webkit-appearance: none) 并进行了自定义美化。
  • 使用 transition 属性为按钮和列表项添加了悬停效果,使交互更流畅。
  • 整体设计采用了卡片式布局,并添加了阴影 (box-shadow) 增加层次感。

JavaScript 逻辑

这是播放器的核心,负责处理所有交互。

html5中网页音乐播放器代码
(图片来源网络,侵删)
  1. 获取元素: 首先用 document.getElementById 获取所有需要操作的 HTML 元素。

  2. 播放列表管理:

    • playlist: 一个 JavaScript 对象数组,存储了每首歌的路径、标题和艺术家信息。
    • currentSongIndex: 当前播放歌曲的索引。
    • initPlaylist(): 遍历 playlist 数组,动态生成播放列表的 HTML,并添加点击事件。
  3. 核心功能函数:

    • loadSong(index): 根据 index 从播放列表中加载歌曲,更新 <audio>src 属性,并更新 UI 上的歌曲信息和播放列表高亮。
    • togglePlayPause(): 检查 audioPlayer.paused 状态来决定是播放还是暂停,并更新播放按钮的图标。
    • updateProgress()**: 这是timeupdate` 事件触发的函数,它会不断获取当前播放时间和总时长,计算进度百分比并更新进度条的宽度,同时格式化并显示时间。
    • setProgress(e): 当用户点击进度条时,根据点击的位置计算出新的播放时间,并设置给 audioPlayer.currentTime
    • formatTime(): 一个辅助函数,将秒数转换为 mm:ss 格式。
    • prevSong() / nextSong(): 切换到上一首或下一首,并处理循环播放的逻辑。
  4. 事件监听器:

    • 将 UI 元素(如按钮、滑块、进度条)与 JavaScript 函数连接起来。
    • audioPlayer.addEventListener('ended', nextSong): 这是一个很实用的功能,当一首歌播放完毕时,自动触发 nextSong 函数播放下一首。

如何使用

  1. 创建文件: 将上面的完整代码复制并粘贴到一个新的文本文件中,将其命名为 player.html
  2. 准备音乐: 准备几首 MP3 格式的音乐文件,并将它们与 player.html 放在同一个文件夹下。
  3. 修改路径: 打开 player.html 文件,找到 playlist 数组,将 src 属性的值(如 'song1.mp3')修改为你自己的音乐文件名。
  4. 在浏览器中打开: 用 Chrome、Firefox、Edge 等现代浏览器打开 player.html 文件,你就可以看到一个功能完整的自定义音乐播放器了。

这个例子涵盖了 HTML5 音频播放器的大部分常见功能,你可以基于此进行扩展,比如添加随机播放、歌词显示、专辑封面等功能。