import { Component } from '@angular/core'; import { HttpClient } from '@angular/common/http'; interface Music { name: string; url: string; picurl: string; artistsname: string; } @Component({ selector: 'app-music-player', templateUrl: './music-player.component.html', styleUrls: ['./music-player.component.scss'] }) export class MusicPlayerComponent { currentSong!: string; musicList: Music[] = []; currentIndex!: number; constructor(private http: HttpClient) { this.getMusicList(); } play() { const audioElement: HTMLAudioElement = document.getElementById('audio') as HTMLAudioElement; audioElement.play(); } pause() { const audioElement: HTMLAudioElement = document.getElementById('audio') as HTMLAudioElement; audioElement.pause(); } next() { this.currentIndex++; if (this.currentIndex >= this.musicList.length) { this.currentIndex = 0; } this.currentSong = this.musicList[this.currentIndex].url; const audioElement: HTMLAudioElement = document.getElementById('audio') as HTMLAudioElement; audioElement.src = this.currentSong; audioElement.play(); } getMusicList() { this.http.get<any>('https://api.uomg.com/api/rand.music?sort=热歌榜&format=json&mid=2642575625').subscribe( res => { const musicName = res.data.name; // 获取音乐名称 this.musicList = [{ name: musicName, // 将音乐名称赋值给name url: res.data.url, picurl: res.data.picurl, artistsname: res.data.artistsname }]; this.currentIndex = 0; this.currentSong = this.musicList[this.currentIndex].url; const audioElement: HTMLAudioElement = document.getElementById('audio') as HTMLAudioElement; audioElement.src = this.currentSong; }, error => { console.log('获取音乐列表失败', error); } ); } }
时间: 2024-04-10 17:31:22 浏览: 92
这是一个 Angular 组件,名为 MusicPlayerComponent。它通过 HttpClient 从一个 API 中获取音乐列表,并将其展示在页面上。这个组件包含了一些方法用于控制音乐播放,比如 play()、pause() 和 next()。在构造函数中调用了 getMusicList() 方法来获取音乐列表,并初始化了一些变量。
阅读全文