December 26, 2017

Simple Ionic music player with HTML 5


Simple Ionic music player with HTML 5



 

There are several audio plugins available in ionic. Trying with HTML5 audio APIs, this article will explain how to create a very simple and plain ionic music player app with HTML5.

As we proceed to this tutorial, it is assumed that npm, node & cordova are already installed.

If you haven’t install ionic, you can install by using below command

npm install -g cordova ionic

Once you installed ionic, you can start a fresh app with below command

ionic start Ionic Music Player tabs

There are other types of ionic apps you can start with. i.e., blank, tabs, side menu. If you want more clarification on this you can ready Ionic Official documentation.

Now, you completed the initial app setup. To check in the browser with “ionic serve” command. This will open in any of your favorite browsers by using inspect element, you can view as mobile (Chrome and Firefox).

Creating a Player provider:

I have created a provider to set up my basic HTML 5 audio functions like Play, Pause and Stop.

ionic generate provider player

This will create a player folder with a basic class file under providers folder. If you don’t have any providers, don’t worry ionic will create a providers folder also. Along with this, above command will add provider in app.module.ts.

Now you have done setting up the provider. Now, we can add our code in the player provider.

My Player provider code looks like below

Create a new Object for music:

audioObj(song) {

return new Audio(song);

}

Play:

I am expecting a parameter called song (This we can send from ionic page)

play(song) {

if(this.url != undefined && this.url != song){

this.stream.currentTime = 0;

this.currentTime = 0;

this.url = song;

} else {

this.url = song;

}

this.stream.pause();

this.stream = this.audioObj(song);

if(this.currentTime > 0){

this.stream.currentTime = this.currentTime;

}

this.stream.play();

this.promise = new Promise((resolve,reject) => {

this.stream.addEventListener(‘playing’, () => {

console.log(“playing”)

resolve(this.stream.duration);

});

this.stream.addEventListener(‘error’, () => {

reject(false);

});

});

return this.promise;

};

Pause:

pause() {

this.currentTime = this.stream.currentTime;

this.stream.pause();

};

Stop:

stop() {

this.currentTime = 0;

this.stream.currentTime = 0;

this.stream.pause();

};

To find Duration and current time:

duration() {

return this.stream.duration;

};

currenttime() {

return this.stream.currentTime;

}

To get streaming information:

getStream(){

return this.stream;

}

Once your player provider is loaded with basic functionalities, you can start implementing your app.

You can clone my basic project for Music Player here.

Happy coding.

View/Post Comment