将HTML5 <audio>标记的控件绑定到Angular中的自定义按钮

时间:2019-07-03 20:13:23

标签: angular typescript html5-audio

我的模板中有一个使用<audio>标签的音频播放器,但是我想对播放器使用自己的样式,因此我将带有该标签的实际本机音频播放器设置为隐藏{{ 1}}。然后,我想将隐藏播放器的控件绑定到我自己的自定义样式的播放器。例如:

display: none;

在我的组件中:

<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(); } 标记的控件绑定到自定义按钮?

1 个答案:

答案 0 :(得分:1)

可以将本机音频播放器包装在Angular组件中。

模板

<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>

组件

@Component({
  moduleId: module.id,
  selector: 'audio-player'
})
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;
    }
  }
}