按钮单击时停止音频文件

时间:2018-01-30 00:47:48

标签: angular typescript

单击组件中的按钮后,我想停止执行当前播放的音频文件,该文件由服务播放。它也应该开始执行不同的音频文件。

但是我在与服务通信时遇到困难,并且在允许播放第二个音频时停止播放第一个音频。

word.component.ts

//This starts the original audio file
ngOnInit() {
   this.playWord(this.startingWord);
}

playWord(word: string) {
    this.sfx.playWordContext(word);
}

audio.service.ts

playWordContext(word: string): Observable<boolean> {
    const w = this.audioFiles[word];
    if (w != null) {
      return this.play(w);
    } else {
      console.error(`Word is null.`);
      return Observable.of(false);
    } 
    return Observable.of(false);
}

play(element: HTMLAudioElement): Observable<boolean> {
    if (element) {
      let result = true;
      const played = Observable.fromEvent(element, 'ended');
      const promise = element.play();

      if (promise) {
        promise.catch(() => {
          console.error('HTMLAudioElement cannot be played.');
          result = false;
        });
      }

      return played.map(() => (result)).take(1);
    } else {
      console.error('HTMLAudioElement is null and cannot be played.');
      return Observable.of(false);
    }
}

key.component.ts

  //When this is fired it needs to stop execution of first audio file while still playing the second
  emitKey(letter: string) {
    if (this.isNotMuted()) {
      this.sfx.play(this.sfx.letters); //this.sfx is the audio service
    }
    this.keyPressed.emit(qke);
  }

有关如何解决此问题的任何建议吗?

0 个答案:

没有答案