【问题标题】:Play 2 sounds one after another in Angular2在Angular2中依次播放2个声音
【发布时间】:2017-07-26 13:54:58
【问题描述】:

我有两个声音

  say_1() { //music
    this.audio.src = './sound1.wav'; 
    this.audio.load();
    // auto-start
    this.audio.play();
  }
 say_2() { //speech
    this.audio.src = './sound2.wav';
    this.audio.load();
    // auto-start
    this.audio.play();
  }

我想制作一个方法play_all();,它会播放一个接一个的声音

play_all () {
this.say_1();
this.say_2();
}

所以,我想先播放我的音乐,然后是演讲, 但在我的方法中它只播放第二个 wav,我想这是因为我有这个方法

  ngOnDestroy() {
    // destroy audio here
    if (this.audio) {
      this.audio.pause();
      this.audio = null;
    }
  }

我需要这种方法,因为如果我离开页面(通过路由器转到下一页),上一页的音乐仍然会播放。

我怎样才能修改我的方法,让它一个接一个地播放两种声音?

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    原因是音频正在异步播放。这意味着这个play() 方法不会等到播放完成。

    为了一个接一个地播放这些声音,您必须在ended 事件发生时开始播放第二个文件。

    最天真的解决方案可能如下所示:

     say_1() { //music
        this.audio.src = './sound1.wav'; 
    
        // whenever playback ends call the next function
        this.audio.onended = () => {
            this.audio.onended = null;
            this.say_2();
        }
    
        this.audio.load();
        this.audio.play();
     }
    
     say_2() { //speech
        this.audio.src = './sound2.wav';
        this.audio.load();
        this.audio.play();
     }
    

    然后你可以调用say_1() 方法而不是playAll()

    您也可以像这样将其提取到 AudioPlayerService 中:

    @Injectable()
    export class AudioPlayerService {
    
        playbackEndedSource = new Subject<string>();
        playbackEnded$ = this.playbackEndedSource.asObservable();
    
        constructor() {
            // this.audio initialization
            this.audio.addEventListener('ended', () => this.playbackEndedSource.next());
    
        }
    
        play(path: string): void {
            this.audio.src = path;
            this.audio.load();
            this.audio.play();
        }
    
    }
    

    那你就可以这样了

    export class AppComponent {
        constructor(private player: AudioPlayerService) {}
    
        playAll() {
    
            const subscription = player.playbackEnded$
                .subscribe(() => {
                    player.play('audio2.wav');
                    // to prevent it from playing over and over again
                    subscription.unsubscribe();
                });
            player.play('audio1.wav');
    
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多