我有一个通过* ngFor显示的音频文件列表。每个文件都包含一个标题,一个播放/停止按钮和一个进度栏(稍后添加)。对于单个文件,我可以使用一个按钮进行播放和暂停。但是,任何时候都只能播放一个文件。例如,如果正在播放歌曲1,同时用户按下歌曲2的播放按钮,则应该停止歌曲1并仅播放歌曲2。由于我对Angular相当陌生,因此尽管付出了很多努力,但我仍无法实现这一目标。任何帮助表示赞赏!
player-group-component.html:
<div *ngIf="songGroupInfo" class="song-group-wrapper">
<div *ngFor="let song of songGroupInfo; let i = index">
<app-player [songInfo]="song" [songIdx]="i"
(playingStatusToEmit)="getStatus($event)">
</app-player>
</div>
</div>
player-group-component.ts:
// imports and @component...
export class PlayerGroupComponent implements OnInit {
songGroupInfo: any = SONGS;
statusArray: Object[] = new Array();
constructor() {}
ngOnInit() {}
// get playing status from child component
getStatus(status: Object) {
console.log(status);
}
}
player-component.html:
<div *ngIf="songInfo" class="player-wrapper">
<p>{{ songInfo.name }}</p>
<button *ngIf="!isPlaying" mat-button color="primary" (click)="toggleMusic()">Play</button>
<button *ngIf="isPlaying" mat-button color="primary" (click)="toggleMusic()">Pause</button>
</div>
player-component.ts:
// imports and @component...
export class PlayerComponent implements OnInit {
@Input() songInfo: any;
@Input() songIdx: number;
@Output() playingStatusToEmit = new EventEmitter<Object>();
sound: any;
isPlaying: boolean = false;
constructor() { }
ngOnInit() {
this.sound = new Howl({
src: this.songInfo.link
});
this.sound.load();
}
playSong() {
this.sound.play();
this.isPlaying = true;
//console.log('Duration: ' + this.sound.duration());
}
pauseSong() {
this.sound.pause();
this.isPlaying = false;
}
stopSong() {
this.sound.stop();
this.isPlaying = false;
}
toggleMusic() {
this.isPlaying ? this.pauseSong() : this.playSong();
this.sendPlayingStatus();
console.log("Played: " + this.sound.seek()); // show how much is played in seconds
}
sendPlayingStatus() {
this.playingStatusToEmit.emit({
'idx': this.songIdx,
'status': this.isPlaying
});
}
}