How to create a dynamic playlist with cordova-media-plugin in an Ionic4 application

I am trying to achieve a playlist feature using cordova media plugin (https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-media/) in an Ionic4 application. The plugin does not originally have a playlist feature and I am to play a list of audio files sequentially and dynamically

single instance looks like this

const file: MediaObject = this.media.create('file.mp3');
file.play()

what is the best way to handle this.

This is my approach to attempt to achieve a playlist feature and play with a logic I learnt from @rapropos

First I created a model for the audio track like this


export class AudioFile {

    constructor(trackUrl?: string, trackId?: string) {

        this.trackUrl = trackUrl;
        this.trackId = trackId;
    }

    public trackUrl: string;
    public trackId: string;
    
}

Then I created the playlist

 public myaudioFile :  AudioFile = new AudioFile();

async CreatePlayList(chap, author, from, to) {

  
    let PlayList = new Array()
    
    for (let ti =from; ti <= to; ti++) {
       
      let uniqueId = 'v_' + ti
      let audioUrl =  this.file.externalRootDirectory+`${chap}/${author}/${ti}.mp3`
    
      PlayList.push({ trackId: tafItem, trackUrl: audioUrl})
   
    }
   
    return PlayList;
 

  }

Then the playOne and playAll implementation

playOne(track: AudioFile): Promise<void> {
 
   return  new Promise(resolve =>{ 
    setTimeout(() => {
      this.goToVerse(parseInt(track.trackId.split("_")[1]));

     this.LoadAndPlayMediaFile(track.trackUrl)
     resolve()
    },1000)
    });
  }


playAll(tracks: AudioFile[]): void {
    let player = (acc, track:AudioFile) => acc.then(() =>    this.playOne(track)
    
    );
    tracks.reduce(player, Promise.resolve());
  }
  LoadAndPlayMediaFile(track){
    console.log('playing'+track )
    
   this.Audiofile =  this.media.create(this.file.externalDataDirectory+track);
   this.Audiofile.play()
   this.Audiofile.onError.subscribe(error => console.log('Error! for '+this.file.externalDataDirectory+track, error));  
  this.Audiofile.onSuccess.subscribe(() => console.log('Action is successful for '+ this.file.externalDataDirectory+ track));
  }

It’s working but they are all playing at the same time with the exception of 1sec delay set with the timeout.

Any suggestion will be appreciated.

Any help on this please, IONIC community!

I eventually got it to work with a recursive function. This works as expected.

PlayAllList(i,tracks: AudioFile[]){
    var self = this;
   
 this.Audiofile = this.media.create(this.file.externalDataDirectory+tracks[i].trackUrl);
  
 this.Audiofile.play()
   this.Audiofile.onSuccess.subscribe(() => {
    if ((i + 1) == tracks.length) {
      // do nothing
     } else {
       self.PlayAllList(i + 1, tracks)
     }
   


  })
}

Then

this.PlayAllList(0,tracks)

If there is any improvement on this, I will appreciate.