Привязать элементы управления тегом HTML5 <audio>к пользовательским кнопкам в Angular - PullRequest
1 голос
/ 03 июля 2019

В моем шаблоне есть аудиопроигрыватель, использующий тег <audio>, но я бы хотел использовать свой собственный стиль для проигрывателя, поэтому у меня есть настоящий встроенный аудиоплеер, для которого этот тег установлен со скрытым 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();
}

Возможно ли то, что я пытаюсь сделать? Как я могу привязать элементы управления тега <audio> к своим пользовательским кнопкам?

1 Ответ

1 голос
/ 04 июля 2019

Можно обернуть собственный аудиоплеер в угловой компонент.

Шаблон

<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;
    }
  }
}
...