前端 用HTML,CSS, JS 写一个简易的音乐播放器

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Music Player</title>
    <style>
        /* 样式可自行修改 */
        .container {
            width: 600px;
            margin: 0 auto;
        }
        h2 {
            text-align: center;
        }
        .controls {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        .progress {
            width: 400px;
            height: 10px;
            background-color: #ccc;
        }
        .progress-bar {
            height: 10px;
            background-color: #6cb0ff;
        }
        .info {
            display: flex;
            justify-content: center;
            align-items: center;
            margin-bottom: 20px;
        }
        .song-info {
            margin-left: 20px;
            display: flex;
            flex-direction: column;
        }
        .song-info span {
            margin-bottom: 5px;
        }
        .song-list {
            list-style: none;
            padding: 0;
        }
        .song-list li {
            margin-bottom: 5px;
            cursor: pointer;
        }
        .song-list li.active {
            color: #6cb0ff;
        }
        .play-mode {
            display: flex;
            align-items: center;
        }
        .play-mode span {
            margin-right: 5px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h2>Music Player</h2>
        <div class="controls">
            <button id="prev">上一首</button>
            <button id="play">播放</button>
            <button id="next">下一首</button>
            <div class="progress">
                <div class="progress-bar"></div>
            </div>
            <input type="range" id="volume" min="0" max="1" step="0.1" value="0.5">
        </div>
        <div class="info">
            <img src="" alt="" id="cover">
            <div class="song-info">
                <span id="song-name">歌曲名称</span>
                <span id="artist">歌手</span>
            </div>
        </div>
        <ul class="song-list">
            <li data-src="./music/song1.mp3">歌曲1</li>
            <li data-src="./music/song2.mp3">歌曲2</li>
            <li data-src="./music/song3.mp3">歌曲3</li>
        </ul>
        <div class="play-mode">
            <span>播放模式:</span>
            <button id="loop">循环</button>
            <button id="random">随机</button>
            <button id="single">单曲</button>
        </div>
    </div>
    <script>
        const audio = new Audio(); // 创建音乐播放器对象
        const songList = document.querySelectorAll('.song-list li');
        const prevBtn = document.querySelector('#prev');
        const playBtn = document.querySelector('#play');
        const nextBtn = document.querySelector('#next');
        const volumeSlider = document.querySelector('#volume');
        const progressBar = document.querySelector('.progress-bar');
        const coverImg = document.querySelector('#cover');
        const songName = document.querySelector('#song-name');
        const artistName = document.querySelector('#artist');
        const loopBtn = document.querySelector('#loop');
        const randomBtn = document.querySelector('#random');
        const singleBtn = document.querySelector('#single');
        let currentIndex = 0;
        let isPlaying = false;
        let playMode = 'loop'; // 默认播放模式为循环

        function playSong(index) {
            const song = songList[index];
            audio.src = song.dataset.src;
            audio.play();
            isPlaying = true;
            playBtn.textContent = '暂停';
            coverImg.src = `./images/cover${index+1}.jpg`;
            songName.textContent = song.textContent;
            artistName.textContent = '歌手名称';
            songList.forEach((item) => {
                item.classList.remove('active');
            });
            song.classList.add('active');
        }

        function getNextIndex() {
            let nextIndex;
            switch(playMode) {
                case 'loop':
                    nextIndex = currentIndex + 1;
                    if (nextIndex >= songList.length) {
                        nextIndex = 0;
                    }
                    break;
                case 'random':
                    nextIndex = Math.floor(Math.random() * songList.length);
                    break;
                case 'single':
                    nextIndex = currentIndex;
                    break;
            }
            return nextIndex;
        }

        function updateProgress() {
            const progress = audio.currentTime / audio.duration * 100;
            progressBar.style.width = `${progress}%`;
        }

        function init() {
            playSong(currentIndex);
        }

        init();

        prevBtn.addEventListener('click', () => {
            currentIndex--;
            if (currentIndex < 0) {
                currentIndex = songList.length - 1;
            }
            playSong(currentIndex);
        });

        nextBtn.addEventListener('click', () => {
            currentIndex = getNextIndex();
            playSong(currentIndex);
        });

        playBtn.addEventListener('click', () => {
            if (isPlaying) {
                audio.pause();
                isPlaying = false;
                playBtn.textContent = '播放';
            } else {
                audio.play();
                isPlaying = true;
                playBtn.textContent = '暂停';
            }
        });

        volumeSlider.addEventListener('input', () => {
            audio.volume = volumeSlider.value;
        });

        audio.addEventListener('timeupdate', updateProgress);

        progressBar.addEventListener('click', (e) => {
            const width = progressBar.clientWidth;
            const clickX = e.offsetX;
            const duration = audio.duration;
            audio.currentTime = clickX / width * duration;
        });

        songList.forEach((song, index) => {
            song.addEventListener('click', () => {
                currentIndex = index;
                playSong(currentIndex);
            });
        });

        loopBtn.addEventListener('click', () => {
            playMode = 'loop';
        });

        randomBtn.addEventListener('click', () => {
            playMode = 'random';
        });

        singleBtn.addEventListener('click', () => {
            playMode = 'single';
        });

        audio.addEventListener('ended', () => {
            currentIndex = getNextIndex();
            playSong(currentIndex);
        });
    </script>
</body>
</html>
 

这个实现了基本的播放/暂停、歌曲切换、音量控制、进度条控制和显示歌曲信息等功能,同时还支持播放模式切换和歌曲列表操作。不过这只是一个简单的示例,实际上还有很多功能需要进一步完善和优化,例如:

  1. 支持歌词显示和同步
  2. 支持播放列表编辑和保存
  3. 支持拖拽上传歌曲
  4. 支持在线搜索歌曲
  5. 支持分享和评论等社交功能

这些功能的实现需要涉及到不同的技术和工具,如 AJAX、WebSocket、React、Node.js 等。如果你想要深入学习和掌握 Web 开发技术,可以选择相应的学习路径和教程进行学习。

相关推荐
螺丝钉tina1 小时前
[Playwright] [02]常用命令与调试:Debug UI、Mode和 Trace Viewer
开发语言·javascript·测试工具·ui·自动化
PedroQue991 小时前
0.8.2 新增 backFallback 配置,无 tabbar 页返回无忧
前端·uni-app
淡漠的蓝精灵1 小时前
web.py:一个简单到极致的 Python Web 框架
开发语言·前端·python·其他
开开心心就好2 小时前
竖式除法出题工具,整除余数混合模式
运维·服务器·前端·javascript·ocr·perl·1024程序员节
起个名字费劲死了2 小时前
Halcon学习一:骰子识别
前端·python·学习
大江东去浪淘尽千古风流人物2 小时前
【HexVIO】DSP卸载双目惯性VIO:Hexagon向量化前端与单帧融合调度深度解析
前端·状态模式·slam·dsp·vio·hexagon·移动端加速
এ慕ོ冬℘゜2 小时前
JS 事件循环、宏任务微任务:单线程底层原理 + 执行顺序
开发语言·javascript·ecmascript
其实防守也摸鱼2 小时前
Chrome 扩展安全攻防实录:从攻击面到防御实践
开发语言·前端·网络·chrome·安全·web安全·php
web打印社区2 小时前
Lodop排障总纲-常见报错一张表
开发语言·前端·javascript·chrome·websocket
李剑一2 小时前
为什么几乎所有的知名开源项目都是外国人写的?
前端·ai编程·deepseek