angular - 将 HTML5 <audio> 标签的控件绑定(bind)到 Angular 中的自定义按钮

标签 angular typescript html5-audio

我的模板中有一个音频播放器,使用 <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/

相关文章:

android - <audio> 无法使用 Android 浏览器在 https 上播放

javascript - webRTC:如何检测流中的音频/视频存在?

javascript - 在 iOS chrome 中从 javascript 播放 html5 <audio> 标签

javascript - Angular 2 - 在不使用 HTML 输入/文本区域的情况下获取条形码扫描器数据

typescript - 没有字符串的提供者

angular - 如何在我的 Angular 2 CLI 构建中添加更少的内容?

javascript - 优化 if else 条件 javaScript

angular - 为什么我需要调用 detectChanges/whenStable 两次?

typescript - 如何将值限制为对象的键?

angular - 如何在 Angular 5 中动态使用这个管道?