源码

<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="img/icon/logo-short.webp">
    <title>小枫公益API播放器</title>

    <style>
        /* 全局盒子模型设置 */
        * {
            box-sizing: border-box;
        }

        /* 基础字体大小设置 */
        input[type="text"],
        button,
        select,
        input[type="range"] {
            font-size: 14px;
        }

        /* 播放器容器 */
        .player-container {
            width: 95%;
            max-width: 800px;
            padding: 20px;
            display: flex;
            flex-direction: column;
            border-radius: 20px;
            background: rgba(255, 255, 255, 0.03);
            color: white;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: auto;
            position: relative;

            /* 新增:防止被 header 挡住,稍微比 header 高一点,留点空隙 */
            margin-top: 64px;
        }

        /* 背景图片设置 */
        body {
            background-image: url('img/bg/绿色树枝.webp');
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
            margin: 0;
            padding: 0;
            height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            position: relative;
        }

        /* 左上角logo */
        .header-top {
            position: fixed;
            z-index: 1000;
            /* 设置较高的z-index值,确保它在最上层 */
            top: 0;
            left: 0;
            right: 0;
            height: 56px;
            background: rgba(255, 255, 255, 0.0);
            /* 调整透明度或颜色,使其更明显 */
            display: flex;
            justify-content: flex-start;
            /* 默认从左侧开始 */
            align-items: center;
            /* 垂直居中 */
        }

        .header-top .logo {
            transition: background 0.3s;
        }

        .header-top .logo:hover {
            background: rgba(255, 255, 255, 0.15);
        }

        .header-top>div {
            display: inline-block;
        }

        .header-top .logo img {
            height: 56px;
            width: auto;
            padding: 8px 16px;
        }

        /* 在小屏幕设备(如手机)上应用的样式 */
        @media (max-width: 600px) {
            .header-top {
                justify-content: center;
                /* 居中对齐 */
            }

            .header-top .logo {
                margin: 0 auto;
                /* 自动边距使.logo水平居中 */
            }

            h2 {
                margin-top: 70px;
                /* 确保标题不与.header-top重叠 */
                font-size: 20px;
                /* 可选:调整字体大小适应小屏幕 */
            }
        }

        /* 对于较大屏幕设备,保证足够的顶部间距 */
        @media (min-width: 601px) {
            h2 {
                margin-top: 70px;
                /* 根据.header-top的高度+padding调整 */
            }
        }

        /* 输入框布局 */
        .input-container {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
        }

        /* 输入框基础样式 */
        input[type="text"] {
            padding: 10px;
            background: transparent;
            color: inherit;
            border: 2px solid;
            border-color: inherit;
            border-radius: 8px;
            transition: all 0.3s ease;
            font-size: 14px;
            flex: 6;
            height: 40px;
            /* 设置高度与按钮一致 */
        }

        /* 输入框获得焦点时的样式 */
        input[type="text"]:focus {
            outline: none;
            border-color: #ff5722;
            background: rgba(255, 87, 34, 0.05);
        }

        /* 输入框鼠标悬停样式 */
        input[type="text"]:hover {
            background: rgba(255, 87, 34, 0.05);
        }

        /* 控制按钮基础样式 */
        @media (max-width: 768px) {
            .control-bar .control-btn {
                font-size: 20px;
                padding: 8px 12px;
                gap: 4px;
            }

            /* 可选:仅显示图标(假设 .icon 是图标元素,.text 是文字) */
            .control-bar .control-btn .text {
                display: none;
            }
        }

        @media (max-width: 480px) {
            .control-bar .control-btn {
                font-size: 16px;
                padding: 6px 8px;
                gap: 2px;
            }
        }

        .control-btn {
            flex: 1;
            padding: 10px;
            background: transparent;
            color: inherit;
            border: 2px solid;
            border-color: inherit;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-weight: 500;
            font-size: 14px;
            height: 40px;
            /* 设置高度与输入框一致 */
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .control-btn:hover {
            background: rgba(255, 87, 34, 0.1);
            color: #ff5722;
            border-color: #ff5722;
        }

        /* 歌曲总数显示控件的基础样式 */
        #playlistStats {
            margin-top: 10px;
            text-align: center;
            font-size: 14px;
            opacity: 0.7;
        }

        /* 播放列表容器样式 */
        .song-list {
            max-height: 420px;
            overflow-y: auto;
            padding: 10px;
            border-radius: 8px;
            margin-top: 10px;
        }

        /* 进度条的基础样式 */
        .seek-bar input[type="range"] {
            width: 100%;
            height: 8px;
            background: rgba(255, 87, 34, 0.2);
            border-radius: 5px;
            outline: none;
            transition: background 0.3s ease;
        }

        /* 进度条滑块的基础样式 */
        .seek-bar input[type="range"]::-webkit-slider-thumb {
            -webkit-appearance: none;
            appearance: none;
            width: 20px;
            height: 20px;
            background: #ff5722;
            cursor: pointer;
            border-radius: 50%;
            box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.5);
        }

        /* 基础样式 */
        .control-bar {
            display: flex;
            align-items: center;
            justify-content: start;
            margin-top: auto;
            background: transparent;
            padding: 10px;
            border-radius: 8px;
            gap: 20px;
            flex-wrap: nowrap;
            overflow-x: auto;
            scrollbar-width: none;
            -ms-overflow-style: none;
        }

        .control-bar::-webkit-scrollbar {
            display: none;
        }

        .control-bar .control-btn {
            font-size: 24px;
            padding: 10px 16px;
            border: none;
            background-color: rgba(255, 255, 255, 0.1);
            border-radius: 6px;
            cursor: pointer;
            transition: background-color 0.3s ease;
            white-space: nowrap;
            text-align: center;
            min-width: max-content;
            display: flex;
            align-items: center;
            gap: 8px;
            flex-shrink: 0;
        }

        .control-bar .control-btn:hover {
            background-color: rgba(255, 255, 255, 0.2);
        }

        /* 主题切换按钮样式 */
        .theme-toggle-btn {
            width: calc(100% / 6);
            /* 设置宽度为父元素宽度的1/6 */
            max-width: 150px;
            /* 可选:限制最大宽度 */
            min-width: 80px;
            /* 确保按钮有最小宽度以保持可用性 */
            position: absolute;
            /* 使用绝对定位 */
            top: 20px;
            /* 距离顶部的距离 */
            right: 20px;
            /* 靠近右侧 */
            background: transparent;
            color: inherit;
            border: 1px solid;
            border-color: inherit;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 14px;
            padding: 5px 10px;
            z-index: 10;
        }

        /* 根据不同主题调整颜色和边框色 */
        .dark-theme .theme-toggle-btn {
            color: #ffffff;
            border-color: rgb(65, 66, 67);
        }

        .light-theme .theme-toggle-btn {
            color: #000000;
            border-color: rgb(235, 238, 245);
        }

        /* 悬停效果 */
        .theme-toggle-btn:hover {
            background: rgba(255, 87, 34, 0.1);
            color: #ff5722;
            border-color: #ff5722;
        }

        /* 确保下方内容不被覆盖(例如 h2 标签) */
        h2 {
            margin-top: 40px;
            /* 根据需要调整此值,确保有足够的空间避免与按钮重叠 */
            text-align: center;
            font-size: 24px;
            font-weight: 600;
            margin-bottom: 15px;
        }

        /* 暗色模式下的输入框样式 */
        .dark-theme input[type="text"] {
            color: #ffffff;
            border-color: rgb(65, 66, 67);
        }

        .dark-theme input[type="text"]:focus {
            border-color: #ff5722;
            background: rgba(255, 87, 34, 0.1);
        }

        /* 明亮模式下的输入框样式 */
        .light-theme input[type="text"] {
            color: #000000;
            border-color: rgb(235, 238, 245);
        }

        .light-theme input[type="text"]:focus {
            border-color: #ff5722;
            background: rgba(255, 87, 34, 0.05);
        }

        /* 控制按钮在暗色/明亮模式下的样式 */
        .dark-theme .control-btn {
            color: #ffffff;
            border-color: rgb(65, 66, 67);
        }

        .light-theme .control-btn {
            color: #000000;
            border-color: rgb(235, 238, 245);
        }

        /* 歌曲总数显示控件的主题适配 */
        .dark-theme #playlistStats {
            color: rgba(255, 255, 255, 0.7);
        }

        .light-theme #playlistStats {
            color: rgba(0, 0, 0, 0.7);
        }

        /* 播放列表滚动条主题适配 */
        .song-list::-webkit-scrollbar {
            width: 8px;
        }

        .song-list::-webkit-scrollbar-thumb {
            background-color: rgba(255, 87, 34, 0.5);
            border-radius: 10px;
        }

        .song-list::-webkit-scrollbar-thumb:hover {
            background-color: rgba(255, 87, 34, 0.7);
        }

        .song-list::-webkit-scrollbar-track {
            background-color: transparent;
        }

        .dark-theme .song-list::-webkit-scrollbar-thumb {
            background-color: rgba(255, 255, 255, 0.5);
        }

        .dark-theme .song-list::-webkit-scrollbar-thumb:hover {
            background-color: rgba(255, 255, 255, 0.7);
        }

        .light-theme .song-list::-webkit-scrollbar-thumb {
            background-color: rgba(0, 0, 0, 0.5);
        }

        .light-theme .song-list::-webkit-scrollbar-thumb:hover {
            background-color: rgba(0, 0, 0, 0.7);
        }

        /* 进度条主题适配 */
        .dark-theme .seek-bar input[type="range"] {
            background: rgba(255, 255, 255, 0.1);
        }

        .dark-theme .seek-bar input[type="range"]::-webkit-slider-thumb {
            background: #ff5722;
        }

        .light-theme .seek-bar input[type="range"] {
            background: rgba(0, 0, 0, 0.1);
        }

        .light-theme .seek-bar input[type="range"]::-webkit-slider-thumb {
            background: #ff5722;
        }

        /* 歌曲项基础样式 */
        .song-item {
            display: flex;
            align-items: center;
            padding: 12px;
            cursor: pointer;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            transition: background 0.3s ease;
        }

        .song-item:hover {
            background-color: rgba(255, 87, 34, 0.1);
        }

        /* 暗色模式下歌曲项样式 */
        .dark-theme .song-item {
            border-color: rgba(255, 255, 255, 0.1);
            color: #e0e0e0;
        }

        .dark-theme .song-item:hover {
            background-color: rgba(255, 87, 34, 0.1);
        }

        /* 明亮模式下歌曲项样式 */
        .light-theme .song-item {
            border-color: rgba(0, 0, 0, 0.1);
            color: #333333;
        }

        .light-theme .song-item:hover {
            background-color: rgba(255, 87, 34, 0.05);
        }

        /* 当前播放歌曲高亮样式 */
        .song-item.playing-song {
            background-color: rgba(255, 87, 34, 0.2);
            font-weight: bold;
            border-left: 3px solid #ff5722;
            padding-left: calc(12px - 3px);
            /* 调整内边距以保持对齐 */
        }

        .dark-theme .song-item.playing-song {
            background-color: rgba(255, 87, 34, 0.25);
            border-left: 3px solid #ff5722;
        }

        .light-theme .song-item.playing-song {
            background-color: rgba(255, 87, 34, 0.15);
            border-left: 3px solid #d84315;
        }

        /* 全局主题容器样式 */
        .dark-theme {
            background: rgba(0, 0, 0, 0.7);
            color: #ffffff;
        }

        .light-theme {
            background: rgba(255, 255, 255, 0.7);
            color: #000000;
        }
    </style>
</head>

<body>
    <div class="player-container dark-theme">

        <!-- logo栏 -->
        <div class="header-top">
            <div class="logo">
                <a href="https://xzysee.online">
                    <!--左上角图标LOGO-->
                    <img src="img/icon/logo-big.webp" alt="Logo Brand" loading="lazy">
                </a>
            </div>
            <!-- 其他顶部导航菜单等可以放在这里 -->
        </div>

        <!-- 播放器标题 -->
        <h2 style="font-size: 24px; font-weight: 600; margin-bottom: 15px; text-align: center;">小枫公益API播放器</h2>

        <!-- 主题切换按钮 -->
        <button class="theme-toggle-btn" onclick="toggleTheme()">切换主题</button>

        <!-- 输入容器 -->
        <div class="input-container">
            <input type="text" id="playlistId" value="https://music.163.com/#/my/m/music/playlist?id=7478460778"
                placeholder="在这里输入你的网易云歌单id或网址">
            <button class="control-btn" onclick="loadPlaylist()">加载歌单</button>
        </div>
        <!-- 歌曲总数显示 -->
        <div id="playlistStats" style="margin-top: 10px; text-align: center; font-size: 14px; opacity: 0.7;">
            歌曲总数:<span id="songCount">0</span> 首</div>
        <!-- 歌单列表 -->
        <div class="song-list" id="songList"></div>
        <!-- 播放进度条 -->
        <div class="seek-bar"><input type="range" id="seekBar" value="0" min="0" max="100" step="0.1"
                oninput="setAudioTime(this.value)" onchange="updateSeekBar()"></div>
        <!-- 控制栏 -->
        <div class="control-bar">
            <button class="control-btn" onclick="skipToPrevious()">⏮️</button>
            <button id="playPauseBtn" class="control-btn" onclick="togglePlayMode()">▶️</button>
            <button class="control-btn" onclick="skipToNext()">⏭️</button>
            <button id="repeatBtn" class="control-btn" title="切换播放模式" onclick="toggleRepeatMode()">🔁</button>
            <button id="downloadBtn" class="control-btn" onclick="downloadSongWithMetadata()">⬇️</button>
        </div>
        <!-- 音频元素 -->
        <audio id="audioPlayer" preload="metadata" style="display: none;"></audio>
    </div>


    <script>
        (function (c, l, a, r, i, t, y) {
            c[a] = c[a] || function () {
                (c[a].q = c[a].q || []).push(arguments)
            };
            t = l.createElement(r);
            t.async = 1;
            t.src = "https://www.clarity.ms/tag/" + i;
            y = l.getElementsByTagName(r)[0];
            y.parentNode.insertBefore(t, y);
        })(window, document, "clarity", "script", "rmvms2s3x5");

        //初始化主题适配
        (function initThemeAdaptation() {
            const playerContainer = document.querySelector('.player-container');
            const htmlElement = document.documentElement;

            function updatePlayerTheme() {
                if (htmlElement.classList.contains('color-scheme-dark')) {
                    playerContainer.classList.remove('light-theme');
                    playerContainer.classList.add('dark-theme');
                } else {
                    playerContainer.classList.remove('dark-theme');
                    playerContainer.classList.add('light-theme');
                }
            }

            updatePlayerTheme();
            const observer = new MutationObserver(mutations => {
                for (let mutation of mutations) {
                    if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
                        updatePlayerTheme();
                    }
                }
            });
            observer.observe(htmlElement, {
                attributes: true
            });
        })();

        // 全局变量定义
        let currentPlaylist = [];
        let currentIndex = -1;
        const songListDiv = document.getElementById('songList'); // 提前获取歌单列表元素
        const audioPlayer = document.getElementById('audioPlayer');
        const playPauseBtn = document.getElementById('playPauseBtn');

        // 添加播放模式控制的全局变量
        let shuffleMode = false; // 是否开启随机播放
        let repeatMode = 'normal'; // 可选值: normal(顺序), shuffle(随机), repeat(单曲循环)
        let isJSZipLoading = false; // 标志位防止重复加载 JSZip
        let hasUserInteracted = false; // 标记用户是否已与页面发生交互

        // 默认歌单ID(可替换为你自己的常用歌单ID)
        const defaultPlaylistId = '7478460778'; // 示例:网易云热门歌单

        function setupAudioEventListeners() {
            if (!audioPlayer) return;

            audioPlayer.addEventListener('play', () => {
                playPauseBtn.textContent = '⏸️';
                savePlayerState();
            });
            audioPlayer.addEventListener('pause', () => {
                playPauseBtn.textContent = '▶️';
                savePlayerState();
            });
            audioPlayer.addEventListener('timeupdate', () => {
                if (audioPlayer.duration) {
                    updateSeekBar(); // 假设这是你用来更新进度条的函数
                }

                // 每隔 5 秒保存一次播放进度
                if (Math.floor(audioPlayer.currentTime) % 5 === 0) {
                    savePlayerState();
                }
            });

            // 可以在这里添加更多事件监听器
            audioPlayer.addEventListener('ended', handleSongEnd); // 播放结束处理
        }

        function extractPlaylistId(input) {
            const urlPattern = /^https:\/\/music\.163\.com\/#\//;
            if (urlPattern.test(input)) {
                const hashPart = input.split('#')[1];
                const match = hashPart.match(/playlist\?id=(\d+)/);
                if (match && match[1]) {
                    return match[1];
                } else {
                    showTemporaryMessage('请输入有效的网易云歌单地址');
                    return null;
                }
            }
            if (/^\d+$/.test(input)) {
                return input;
            }
            showTemporaryMessage('请输入有效的网易云歌单地址或直接输入歌单ID');
            return null;
        }

        async function loadPlaylist(uid = null) {
            resetPlayer(); // 清空当前列表和状态

            if (!uid) {
                const input = document.getElementById('playlistId').value.trim();
                uid = extractPlaylistId(input); // 假设你有一个方法可以从输入中提取出UID
                if (!uid) {
                    showTemporaryMessage("请输入有效的歌单ID");
                    return;
                }
            }

            try {
                const response = await fetch(`https://node.api.xfabe.com/api/wangyi/userSongs?uid=${uid}&limit=100`);
                if (!response.ok) throw new Error("Network response was not ok");

                const data = await response.json();

                if (data.code !== 200 || !data.data.songs) {
                    showTemporaryMessage('歌单ID无效,请检查并重试');
                    return;
                }

                currentPlaylist = data.data.songs; // 更新全局变量
                currentIndex = 0;

                cachePlaylist(currentPlaylist); // 缓存歌单数据

                updateSongList(data.data.songs); // 更新歌单列表显示
                document.getElementById('songCount').textContent = data.data.songs.length; // 更新歌曲总数显示

                // 如果你想在加载歌单后自动播放第一首歌曲,可以在这里调用 playIndex(0);
                if (currentPlaylist.length > 0) {
                    playIndex(0); // 自动播放第一首歌曲
                }

            } catch (error) {
                console.error('加载歌单失败:', error);
                showTemporaryMessage('加载歌单失败,请检查网络连接或稍后再试');
            }
        }

        async function loadDefaultPlaylist() {
            await loadPlaylist(defaultPlaylistId);
        }

        async function playIndex(index, retry = 3) {
            if (!currentPlaylist || index < 0 || index >= currentPlaylist.length) {
                console.warn("无效的播放索引", index);
                if (currentPlaylist.length > 0) playIndex(0);
                return;
            }

            currentIndex = index;
            const song = currentPlaylist[index];

            // 获取所有歌曲项并移除高亮
            const allSongs = document.querySelectorAll('#songList .song-item');
            allSongs.forEach(item => item.classList.remove('playing-song'));

            try {
                const res = await fetch(`https://node.api.xfabe.com/api/wangyi/music?type=json&id=${song.id}`);
                const data = await res.json();

                if (data.code !== 200) {
                    if (retry > 0) {
                        console.log(`加载失败,第 ${4 - retry} 次重试...`);
                        await new Promise(resolve => setTimeout(resolve, 200));
                        return playIndex(index, retry - 1);
                    } else {
                        throw new Error('多次尝试后仍无法加载该歌曲');
                    }
                }

                const songData = data.data;

                // 设置音频源
                audioPlayer.src = songData.url;

                // 尝试播放
                try {
                    await audioPlayer.play();
                    updateMediaSession(songData);
                    playPauseBtn.textContent = '⏸️'; // 显示暂停图标

                    // 再次获取当前项以确保是最新的 DOM
                    const currentItem = document.querySelector(`#songList .song-item:nth-child(${index + 1})`);
                    if (currentItem) {
                        currentItem.classList.add('playing-song');
                    } else {
                        console.warn("找不到对应索引的歌曲项,可能歌单未正确渲染");
                    }

                    // 如果已经有过用户交互,那么设置结束后播放下一首
                    if (hasUserInteracted) {
                        audioPlayer.onended = () => {
                            playIndex((currentIndex + 1) % currentPlaylist.length);
                        };
                    }
                } catch (err) {
                    console.error("播放受限:", err);
                    if (!hasUserInteracted) {
                        showTemporaryMessage("请先与页面交互后再播放");
                    }
                }

            } catch (e) {
                console.error("播放失败:", e);
                showTemporaryMessage('加载歌曲信息失败');
            }
        }

        function highlightCurrentSong() {
            const playingItems = document.querySelectorAll('.playing-song');
            playingItems.forEach(item => item.classList.remove('playing-song'));

            const currentItem = document.querySelector(`[data-index="${currentIndex}"]`);
            if (currentItem) {
                currentItem.classList.add('playing-song');
            }
        }

        async function togglePlayMode() {
            if (!playPauseBtn || !audioPlayer) return;

            if (audioPlayer.paused) {
                // 如果还没有歌曲资源
                if (!audioPlayer.src) {
                    try {
                        await loadDefaultPlaylist(); // 加载默认歌单
                        if (currentPlaylist.length === 0) {
                            showTemporaryMessage("默认歌单为空");
                            return;
                        }
                        await playIndex(0); // 播放第一首
                        playPauseBtn.textContent = '⏸️';
                        showTemporaryMessage("开始播放");
                    } catch (err) {
                        console.error('加载默认歌单失败:', err);
                        showTemporaryMessage("加载歌单失败");
                    }
                } else {
                    // 已有音频资源,尝试播放
                    try {
                        await audioPlayer.play();
                        playPauseBtn.textContent = '⏸️';
                        showTemporaryMessage("继续播放");
                    } catch (err) {
                        showTemporaryMessage("播放受限,请点击页面授权播放");
                        audioPlayer.pause();
                    }
                }
            } else {
                // 当前正在播放,暂停
                audioPlayer.pause();
                playPauseBtn.textContent = '▶️';
                showTemporaryMessage("已暂停");
            }
        }

        function updateSeekBar() {
            if (audioPlayer.duration) {
                const progress = (audioPlayer.currentTime / audioPlayer.duration) * 100;
                document.getElementById('seekBar').value = progress; // 确保使用正确的ID
            }
        }

        function setAudioTime(value) {
            const time = (value / 100) * audioPlayer.duration;
            audioPlayer.currentTime = time;
        }

        async function handleSongEnd() {
            console.log("歌曲结束,准备播放下一首...");
            skipToNext();
        }

        function updateTimeDisplay() {
            const duration = audioPlayer.duration;
            const currentTime = audioPlayer.currentTime;

            // 假设你有这两个元素显示时间
            document.getElementById('currentTime').textContent = formatTime(currentTime);
            document.getElementById('totalDuration').textContent = formatTime(duration);
        }

        function formatTime(timeInSeconds) {
            const minutes = Math.floor(timeInSeconds / 60);
            const seconds = Math.floor(timeInSeconds % 60).toString().padStart(2, '0');
            return `${minutes}:${seconds}`;
        }

        function toggleRepeatMode() {
            const repeatBtn = document.getElementById('repeatBtn');
            if (repeatMode === 'normal') {
                repeatMode = 'shuffle';
                shuffleMode = true;
                repeatBtn.textContent = '🔀'; // 随机播放图标
                showTemporaryMessage("已切换为随机播放");
            } else if (repeatMode === 'shuffle') {
                repeatMode = 'repeat';
                repeatBtn.textContent = '🔂'; // 单曲循环图标
                showTemporaryMessage("已切换为单曲循环");
            } else {
                repeatMode = 'normal';
                shuffleMode = false;
                repeatBtn.textContent = '🔁'; // 顺序播放图标
                showTemporaryMessage("已切换为顺序播放");
            }
        }

        function skipToNext() {
            if (!currentPlaylist || currentPlaylist.length <= 1) return;

            let nextIndex;
            if (repeatMode === 'repeat') {
                nextIndex = currentIndex;
            } else if (repeatMode === 'shuffle') {
                do {
                    nextIndex = Math.floor(Math.random() * currentPlaylist.length);
                } while (nextIndex === currentIndex && currentPlaylist.length > 1);
            } else {
                nextIndex = (currentIndex + 1) % currentPlaylist.length;
            }

            console.log("播放下一首索引:", nextIndex);
            playIndex(nextIndex);
        }

        function skipToPrevious() {
            const newIndex = (currentIndex - 1 + currentPlaylist.length) % currentPlaylist.length;
            playIndex(newIndex);
        }

        function updateMediaSession(songData) {
            if ('mediaSession' in navigator) {
                navigator.mediaSession.metadata = new MediaMetadata({
                    title: songData.name,
                    artist: songData.artistsname,
                    album: songData.album,
                    artwork: [{
                        src: songData.picurl,
                        sizes: '96x96',
                        type: 'image/jpeg'
                    },
                    {
                        src: songData.picurl,
                        sizes: '128x128',
                        type: 'image/jpeg'
                    },
                    {
                        src: songData.picurl,
                        sizes: '192x192',
                        type: 'image/jpeg'
                    },
                    {
                        src: songData.picurl,
                        sizes: '256x256',
                        type: 'image/jpeg'
                    },
                    {
                        src: songData.picurl,
                        sizes: '384x384',
                        type: 'image/jpeg'
                    },
                    {
                        src: songData.picurl,
                        sizes: '512x512',
                        type: 'image/jpeg'
                    }
                    ]
                });

                // 设置动作监听器
                navigator.mediaSession.setActionHandler('play', () => {
                    if (audioPlayer.paused) audioPlayer.play();
                });

                navigator.mediaSession.setActionHandler('pause', () => {
                    if (!audioPlayer.paused) audioPlayer.pause();
                });

                navigator.mediaSession.setActionHandler('nexttrack', skipToNext);
                navigator.mediaSession.setActionHandler('previoustrack', skipToPrevious);

                // 可选:支持跳转时间
                navigator.mediaSession.setActionHandler('seekbackward', () => {
                    audioPlayer.currentTime = Math.max(0, audioPlayer.currentTime - 10);
                });

                navigator.mediaSession.setActionHandler('seekforward', () => {
                    audioPlayer.currentTime = Math.min(audioPlayer.duration, audioPlayer.currentTime + 10);
                });

                navigator.mediaSession.setActionHandler('seekto', (details) => {
                    if (details.fastSeek || details.seekTime !== undefined) {
                        audioPlayer.currentTime = details.seekTime;
                    }
                });
            }
        }

        function downloadSongWithMetadata() {
            const url = audioPlayer.src;
            if (!url) return showTemporaryMessage("当前无可下载的歌曲");

            if (typeof JSZip === 'undefined' && !isJSZipLoading) {
                isJSZipLoading = true;
                showTemporaryMessage('正在加载 ZIP 支持...');
                const script = document.createElement('script');
                script.src = 'js/jszip.min.js';
                script.onload = () => {
                    isJSZipLoading = false;
                    downloadSongWithMetadata(); // 重试
                };
                script.onerror = () => {
                    isJSZipLoading = false;
                    showTemporaryMessage('加载ZIP支持失败');
                };
                document.head.appendChild(script);
                return;
            } else if (isJSZipLoading) {
                return showTemporaryMessage('ZIP支持正在加载中,请稍候...');
            }

            const title = currentPlaylist[currentIndex]?.name || "music";
            const artist = currentPlaylist[currentIndex]?.artistsname || "";
            const coverUrl = currentPlaylist[currentIndex]?.picurl;

            // 开始下载和打包
            Promise.all([
                fetch(url).then(res => res.blob()),
                fetch(coverUrl).then(res => res.blob())
            ])
                .then(([audioBlob, coverBlob]) => {
                    const zip = new JSZip();
                    zip.file(`${artist} - ${title}.mp3`, audioBlob);
                    zip.file(`${artist} - ${title}.jpg`, coverBlob);

                    return zip.generateAsync({
                        type: 'blob'
                    });
                })
                .then(content => {
                    const link = document.createElement("a");
                    link.href = URL.createObjectURL(content);
                    link.download = `${artist} - ${title}.zip`;
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                })
                .catch(err => {
                    console.error('下载失败:', err);
                    showTemporaryMessage('下载失败,请检查网络连接或重试');
                });
        }

        function showTemporaryMessage(message) {
            const toast = document.createElement('div');
            toast.style.position = 'fixed';
            toast.style.bottom = '60px'; /* 调整临时消息的位置,避免与主题切换按钮重叠 */
            toast.style.right = '20px';
            toast.style.backgroundColor = 'rgba(0,0,0,0.7)';
            toast.style.color = '#fff';
            toast.style.padding = '10px 15px';
            toast.style.borderRadius = '6px';
            toast.style.fontFamily = 'sans-serif';
            toast.style.fontSize = '14px';
            toast.style.zIndex = '1000'; /* 降低临时消息的层级 */
            toast.style.opacity = '0';
            toast.style.transition = 'opacity 0.3s ease';
            toast.textContent = message;
            document.body.appendChild(toast);

            setTimeout(() => {
                toast.style.opacity = '1';
            }, 100);

            setTimeout(() => {
                toast.style.opacity = '0';
                setTimeout(() => {
                    document.body.removeChild(toast);
                }, 300);
            }, 2000);
        }

        function resetPlayer() {
            if (songListDiv) {
                songListDiv.innerHTML = '';
            }

            if (audioPlayer) {
                audioPlayer.pause();
                audioPlayer.src = ''; // 设置为空字符串以停止播放
                audioPlayer.currentTime = 0;
            }

            if (playPauseBtn) {
                playPauseBtn.textContent = '▶️';
            }

            currentPlaylist = [];
            currentIndex = -1;

            if ('mediaSession' in navigator) {
                navigator.mediaSession.metadata = null;
            }

            if (document.getElementById('songCount')) {
                document.getElementById('songCount').textContent = '0';
            }

            const playingItems = document.querySelectorAll('.song-item.playing-song');
            playingItems.forEach(item => item.classList.remove('playing-song'));
        }

        function updateSongList(songs) {
            if (!songListDiv) {
                console.error("找不到歌单列表容器");
                return;
            }
            songListDiv.innerHTML = ''; // 清空旧内容

            songs.forEach((song, index) => {
                const item = document.createElement('div');
                item.className = 'song-item';
                item.setAttribute('data-index', index); // 可选:方便调试或选择元素
                item.innerHTML = `
                    <img src="${song.picurl}" alt="封面" style="width: 40px; height: 40px; border-radius: 8px; margin-right: 10px;">
                    <div><strong>${song.name}</strong><br><small>${song.artistsname}</small></div>`;
                item.onclick = () => playIndex(index);

                // 如果这首歌是当前正在播放的,添加 playing-song 类
                if (index === currentIndex) {
                    item.classList.add('playing-song');
                }

                songListDiv.appendChild(item);
            });
        }

        // 保存播放器状态到 localStorage
        function savePlayerState() {
            const state = {
                playlist: currentPlaylist,
                currentIndex: currentIndex,
                currentTime: audioPlayer ? audioPlayer.currentTime : 0,
                isPlaying: !audioPlayer.paused,
                shuffleMode: shuffleMode,
                repeatMode: repeatMode
            };
            try {
                localStorage.setItem('musicPlayerState', JSON.stringify(state));
            } catch (e) {
                console.error("保存播放器状态失败", e);
            }
        }

        // 从 localStorage 恢复播放器状态
        function restorePlayerState() {
            const savedState = localStorage.getItem('musicPlayerState');
            if (savedState) {
                try {
                    const state = JSON.parse(savedState);
                    currentPlaylist = state.playlist || [];
                    currentIndex = state.currentIndex;
                    shuffleMode = state.shuffleMode;
                    repeatMode = state.repeatMode;

                    // 更新 UI
                    updateSongList(currentPlaylist); // 刷新歌单列表显示
                    if (currentPlaylist.length > 0 && currentIndex >= 0) {
                        const song = currentPlaylist[currentIndex];
                        audioPlayer.src = song.url; // 假设歌曲 URL 存在 url 字段中
                        audioPlayer.currentTime = state.currentTime || 0;
                        if (state.isPlaying) {
                            audioPlayer.play().then(() => {
                                playPauseBtn.textContent = '⏸️';
                            }).catch(() => {
                                playPauseBtn.textContent = '▶️';
                            });
                        } else {
                            playPauseBtn.textContent = '▶️';
                        }
                        highlightCurrentSong(); // 高亮当前播放歌曲
                    }
                } catch (e) {
                    console.error("恢复播放器状态失败", e);
                }
            }
        }

        // 缓存歌单数据到 localStorage
        function cachePlaylist(playlist) {
            try {
                localStorage.setItem('cachedPlaylist', JSON.stringify(playlist));
            } catch (e) {
                console.error("缓存歌单数据失败", e);
            }
        }

        // 从 localStorage 加载缓存的歌单数据
        function loadCachedPlaylist() {
            const cachedData = localStorage.getItem('cachedPlaylist');
            if (cachedData) {
                try {
                    const playlist = JSON.parse(cachedData);
                    currentPlaylist = playlist;
                    currentIndex = 0;
                    updateSongList(playlist);
                    document.getElementById('songCount').textContent = playlist.length;
                    if (playlist.length > 0) {
                        playIndex(0); // 自动播放第一首歌曲
                    }
                } catch (e) {
                    console.error("加载缓存歌单失败", e);
                }
            } else {
                console.log("没有找到缓存的歌单数据");
            }
        }

        // 初始化时设置事件监听器
        function initializePlayer() {
            resetPlayer(); // 清空播放器状态和列表
            loadCachedPlaylist(); // 尝试加载缓存的歌单数据
            setupAudioEventListeners(); // 设置事件监听器
        }

        // 切换主题函数
        function toggleTheme() {
            const playerContainer = document.querySelector('.player-container');
            if (playerContainer.classList.contains('dark-theme')) {
                playerContainer.classList.remove('dark-theme');
                playerContainer.classList.add('light-theme');
            } else {
                playerContainer.classList.remove('light-theme');
                playerContainer.classList.add('dark-theme');
            }
        }

        document.addEventListener('DOMContentLoaded', function () {
            initializePlayer(); // 初始化播放器
        });

        // 用户交互触发函数,比如点击播放按钮或歌曲项
        document.getElementById("playButton").addEventListener("click", () => {
            if (!hasUserInteracted) { // 如果用户还没有交互过,则标记为已交互
                hasUserInteracted = true;
            }
            playIndex(currentIndex); // 播放当前索引的歌曲
        });
    </script>
</body>

</html>