// ==UserScript==
// @name 音乐播放器
// @namespace http://tampermonkey.net/
// @version 6.0
// @description 在网页右下角添加一个音乐播放器,播放本地或合法在线音乐
// @author You
// @match *://*/*
// @grant none
// ==/UserScript==
(function() {
'use strict';
// ======== 配置你的播放列表(必须是合法可用的音频 URL)========
const playlist = [
"https://www.example.com/audio/sample1.mp3",
"https://www.example.com/audio/sample2.mp3"
// 也可以用本地服务器路径,如 http://localhost/music/song.mp3
];
let currentIndex = 0;
// ======== 创建播放器 UI ========
const container = document.createElement("div");
container.style.position = "fixed";
container.style.bottom = "10px";
container.style.right = "10px";
container.style.background = "rgba(0,0,0,0.7)";
container.style.color = "#fff";
container.style.padding = "10px";
container.style.borderRadius = "8px";
container.style.zIndex = "99999";
container.style.fontSize = "14px";
container.style.width = "250px";
container.innerHTML = `
音量:
`;
document.body.appendChild(container);
// ======== 获取元素 ========
const audio = container.querySelector("#tm-audio");
const playBtn = container.querySelector("#tm-play");
const prevBtn = container.querySelector("#tm-prev");
const nextBtn = container.querySelector("#tm-next");
const progressBar = container.querySelector("#tm-progress");
const volumeBar = container.querySelector("#tm-volume");
// ======== 功能函数 ========
function loadSong(index) {
if (index < 0) index = playlist.length - 1;
if (index >= playlist.length) index = 0;
currentIndex = index;
audio.src = playlist[currentIndex];
audio.load();
}
function togglePlayPause() {
if (audio.paused) {
audio.play();
playBtn.textContent = "⏸";
} else {
audio.pause();
playBtn.textContent = "▶";
}
}
// ======== 事件绑定 ========
playBtn.addEventListener("click", togglePlayPause);
prevBtn.addEventListener("click", () => {
loadSong(currentIndex - 1);
audio.play();
playBtn.textContent = "⏸";
});
nextBtn.addEventListener("click", () => {
loadSong(currentIndex + 1);
audio.play();
playBtn.textContent = "⏸";
});
audio.addEventListener("timeupdate", () => {
if (audio.duration) {
progressBar.value = (audio.currentTime / audio.duration) * 100;
}
});
progressBar.addEventListener("input", () => {
if (audio.duration) {
audio.currentTime = (progressBar.value / 100) * audio.duration;
}
});
volumeBar.addEventListener("input", () => {
audio.volume = volumeBar.value / 100;
});
audio.addEventListener("ended", () => {
loadSong(currentIndex + 1);
audio.play();
});
// ======== 初始化 ========
loadSong(currentIndex);
})();