我的模板中有一个音频播放器,使用 <audio>
标签,但我想对播放器使用我自己的样式,因此我将该标签附带的实际 native 音频播放器设置为隐藏 display: none;
。然后我想将隐藏播放器的控件绑定(bind)到我自己的自定义样式的播放器。例如:
<audio src="{{recordingUrl}}" #audio></audio>
<!-- other html -->
<button (click)="startPlayer()">/button> <!-- this is my custom play button -->
在我的组件中:
@ViewChild("audio", { static: true }) audio: any;
player: any = document.getElementById("audio");
startPlayer(){
//neither of these work
this.audio.play();
this.player.play();
}
我想做的事情可能吗?如何绑定(bind)<audio>
的控件标记到我的自定义按钮?
最佳答案
可以将 native 音频播放器包装在 Angular 组件中。
组件
@Component({
moduleId: module.id,
selector: 'audio-player',
template: `
<audio #audioElement src="{{src}}">
<p>Your browser does not support HTML5 audio. Here is a <a href="{{src}}">link</a> instead.</p>
</audio>
<span (click)="paused ? play() : pause()" class="icon-align-middle">
<mat-icon *ngIf="paused" class="icon-size-30">play_circle_outline</mat-icon>
<mat-icon *ngIf="!paused" class="icon-size-30">pause_circle_outline</mat-icon>
</span>
`
})
export class AudioPlayerComponent implements AfterViewInit {
@Input() public src: string;
@Input() public autoplay: boolean = false;
@Input() public showStateLabel: boolean = false;
public audioStateLabel = 'Audio sample';
@Input() public volume: number = 1.0; /* 1.0 is loudest */
@ViewChild('audioElement', { static: false }) public _audioRef: ElementRef;
private audio: HTMLMediaElement;
public constructor() { }
public pause(): void {
if (this.audio) {
this.audio.pause();
this.audioStateLabel = 'Paused';
}
}
public get paused(): boolean {
if (this.audio) {
return this.audio.paused;
} else {
return true;
}
}
public play(): void {
if (this.audio) {
if (this.audio.readyState >= 2) {
this.audio.play();
this.audioStateLabel = 'Playing...'
}
}
}
public ngAfterViewInit() {
this.audio = this._audioRef.nativeElement;
if (this.audio) {
this.audio.volume = this.volume;
this.audio.autoplay = this.autoplay;
}
}
}
关于angular - 将 HTML5 <audio> 标签的控件绑定(bind)到 Angular 中的自定义按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56877319/