播放2声音陆续在Angular2

问题描述:

我有两个声音播放2声音陆续在Angular2

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

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

我该如何修改我的方法,使它能够一个接一个地播放声音?

原因是音频是异步播放的。这意味着这个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(); 
} 

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

你也可以提取这种成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'); 

    } 
}