I have been attempting to create a playlist of multiple audio files using the Ionic media plugin from here. However, I am struggling to achieve this without resorting to using a timeout function.
Here is my current approach:
playOne(track: AudioFile): Promise<any> {
return new Promise(async resolve =>{
const AudFile = await this.media.create(this.file.externalDataDirectory+track.trackUrl);
await resolve(AudFile.play());
});
}
To play all tracks in the playlist, I have implemented the following method:
async playAll(tracks: AudioFile[]): Promise<any>{
let player = (acc, track:AudioFile) => acc.then(() =>
this.playOne(track)
);
tracks.reduce(player, Promise.resolve());
}
Unfortunately, with this setup, all tracks are playing simultaneously. So, I tried wrapping the playOne method in a timeout function to introduce a delay between tracks. This resulted in some tracks waiting an excessively long time before being played:
playOne(track: AudioFile): Promise<any> {
return new Promise(async resolve =>{
setTimeout(async ()=>{
const AudFile = await this.media.create(this.file.externalDataDirectory+track.trackUrl);
await resolve(AudFile.play());
},3000);
});
}
Upon further investigation into the Ionic wrapper for the plugin, I found that the create method is structured as follows:
/**
* Open a media file
* @param src {string} A URI containing the audio content.
* @return {MediaObject}
*/
Media.prototype.create = function (src) {
var instance;
if (checkAvailability(Media.getPluginRef(), null, Media.getPluginName()) ===
true) {
// Creates a new media object
instance = new (Media.getPlugin())(src);
}
return new MediaObject(instance);
};
Media.pluginName = "Media";
Media.repo = "https://github.com/apache/cordova-plugin-media";
Media.plugin = "cordova-plugin-media";
Media.pluginRef = "Media";
Media.platforms = ["Android", "Browser", "iOS", "Windows"];
Media = __decorate([
Injectable()
], Media);
return Media;
}(IonicNativePlugin));
If anyone has suggestions on how to improve this playlist functionality, I would greatly appreciate it.