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
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.