如何使用 Ionic4 Native 音频动态播放音频列表

How to play audio lists dynamically with Ionic4 Native audio

我想在 angular/typescript.

的 ionic4 项目中播放其前身后立即播放音频文件列表

我可以像这样手动播放音频

PlayList(){

      this.nativeAudio.play('uniqueId1', () => {

           //the first audio is done playing
              this.nativeAudio.play('uniqueId2', () => {
                 //the second video is done playing 
                         this.nativeAudio.play('uniqueId3', () => {


                                                      }

                                           }

              }

     }

我试着用 async/await 在循环中播放它,但它们都在同时播放。

我假设 nativeAudio.play()promise。使用您的代码,您不会等待结束第一个方法来调用第二个方法,因为承诺未完成。您可以通过 async/await 方式链接承诺或很好地做到这一点。

赞:

async PlayList(){
 await this.nativeAudio.play('uniqueId1);
 await this.nativeAudio.play('uniqueId2);
 await this.nativeAudio.play('uniqueId3);
}

动态地,我会这样做:

async PlayList(){
 const listIds = ['uniqueId1', 'uniqueId2', 'uniqueId3'];
 await Promise.all(listIds.map(async id => await this.nativeAudio.play(id));
}

希望对您有所帮助。

通过帮助解决了。

 playOne(track: string): Promise<void> {
  return new Promise(resolve => this.nativeAudio.play(track, resolve));
}

playAll(tracks: string[]): void {
  let player = (acc, track) => acc.then(() => this.playOne(track));
  tracks.reduce(player, Promise.resolve());
}

Array.reduce 允许我们将一次迭代的结果提供给下一次迭代。每个连续的 运行 等待最后一个和 returns 一个新的 Promise,下一个将等待。

希望对大家有所帮助。