DreamLife_HomePage/javascape/music_player.js

92 lines
3.0 KiB
JavaScript

// 音乐播放器功能
class MusicPlayer {
constructor() {
this.currentSongIndex = 0;
this.songs = [];
this.isPlaying = false;
this.audio = new Audio();
this.init();
}
init() {
this.bindEvents();
this.bindAudioEvents();
this.loadSongs();
}
bindAudioEvents() {
this.audio.addEventListener('loadeddata', () => {
if (this.isPlaying) {
this.audio.play();
}
});
}
bindEvents() {
document.getElementById('playPauseBtn').addEventListener('click', () => this.togglePlayPause());
document.getElementById('prevBtn').addEventListener('click', () => this.playPrevious());
document.getElementById('nextBtn').addEventListener('click', () => this.playNext());
}
async loadSongs() {
try {
// 使用新的音乐API
const response = await fetch('https://www.cunyuapi.top/rwyymusic');
const data = await response.json();
this.songs = [data];
this.loadSong(0);
} catch (error) {
console.error('加载歌曲失败:', error);
document.getElementById('musicTitle').textContent = '加载失败';
}
}
async loadSong(index) {
this.currentSongIndex = index;
const song = this.songs[index];
document.getElementById('musicTitle').textContent = song.name;
document.getElementById('musicArtist').textContent = song.artists;
// 设置音频源
this.audio.src = song.song_url;
}
togglePlayPause() {
if (this.isPlaying) {
this.audio.pause();
document.getElementById('playPauseBtn').innerHTML = '<img src="icon/play.png" alt="播放" width="18" height="18">';
} else {
this.audio.play();
document.getElementById('playPauseBtn').innerHTML = '<img src="icon/pause.png" alt="暂停" width="18" height="18">';
}
this.isPlaying = !this.isPlaying;
}
playPrevious() {
if (this.currentSongIndex > 0) {
this.loadSong(this.currentSongIndex - 1);
this.isPlaying = true;
document.getElementById('playPauseBtn').innerHTML = '<img src="icon/pause.png" alt="暂停" width="18" height="18">';
}
}
playNext() {
if (this.currentSongIndex < this.songs.length - 1) {
this.loadSong(this.currentSongIndex + 1);
this.isPlaying = true;
document.getElementById('playPauseBtn').innerHTML = '<img src="icon/pause.png" alt="暂停" width="18" height="18">';
} else {
this.loadSongs();
this.isPlaying = true;
document.getElementById('playPauseBtn').innerHTML = '<img src="icon/pause.png" alt="暂停" width="18" height="18">';
}
}
}
// 页面加载完成后初始化音乐播放器
window.addEventListener('DOMContentLoaded', () =>{
new MusicPlayer();
});