enappd loader




Play Spotify like Music in Ionic 4 apps

This post is all about playing music in your cool new app, be it for a music player or just for a notification. In this post, you will learn 

  • How to play music and sound files in Ionic 4 apps
  • How to stream music using web URLs
  • How to use music controls like next, previous, pause etc. 
Complete source code of this tutorial is available here — Ionic-4-music. This demonstration is supported by Ionic 4 Spotify Starter from Enappd

Where is music required in apps ?

Well ! that’s a stupid question I know. Music is everywhere in today’s apps. Spotify, Youtube Music, Wynk, Gaana, etc. Other than the music streaming apps themselves, there are tonnes of other usages of music/sound in apps. 

  • You definitely need sounds in a game app
  • You can play sounds when user does a specific activity in the app e.g. wins a coupon ! 
  • Sounds can be played for push notifications, the ones which are silently pushed in a foreground app
  • Chat messages can make a sound ! Whatsapp does that 
  • …… and many more such examples

Basically music / sounds make your app more lively, more exciting. Of course you would want to avoid sounds in a professional app like LinkedIn, because people use that at work as well 😄

What is Ionic 4?

You probably already know about Ionic, but put this section in every blog just for the sake of beginners. Ionic is a complete open-source SDK for hybrid mobile app development. Ionic provides tools and services for developing hybrid mobile apps using Web technologies like CSS, HTML5, and Sass. Apps can be built with these Web technologies and then distributed through native app stores to be installed on devices.

In other words — If you create native apps in Android, you code in Java. If you create native apps in iOS, you code in Obj-C or Swift. Both of these are powerful, but complex languages. With Cordova (and Ionic) you can write a single piece of code for your app that can run on both iOS and Android (and windows!), that too with the simplicity of HTML, CSS, and JS. I’m a huge fan of Ionic and been developing Ionic apps for last 4 years.

Structure

We’ll follow a stepped approach to create a Music player app in Ionic 4. We’ll use Ionic native plugin for music playback. Following are the steps

  • Step 1 — Create a basic Ionic 4 app
  • Step 2 — Setup Music plugin
  • Step 3 — Various Music plugin Features
  • Step 4 — Test on Android

So let’s dive right in ! 

Step 1 — Create a basic Ionic 4 app

I have covered this topic in detail in this blog.

In short, the steps you need to take here are

  • Make sure you have node installed in the system (V10.0.0 at the time of this blog post)
  • Install ionic cli using npm (my Ionic version is 4.12.0 currently)
  • Create an Ionic app using ionic start

You can create a blank starter for the sake of this tutorial. On running ionic start ionic-4-music blank , node modules will be installed. Once the installation is done, run your app on browser using

$ ionic serve

Make slight modifications to the home page as you like. My app’s home page looks like this



Home page for ionic-4-music app

I actually borrowed the homepage UI from our Ionic 4 Spotify starter, just to give you a glimpse of the UI and features.

Step 2 — Setup Music plugin

We are going to use an Ionic Native plugin (which is essentially a Cordova plugin) — Cordova Plugin Media. This plugin has basic music playback functionalities, along with recording capabilities. But we’ll not go into recording features for now. 

Once your basic app is ready and running in ionic serve install the plugin using following commands

$ ionic cordova plugin add cordova-plugin-media
$ npm install @ionic-native/media

With this the plugin is installed, no extra settings. Now you have to import the plugin in app.module.ts and your homepage i.e. home.page.ts 



Import music plugin in app.module.ts

Similarly import the plugin in home.page.ts and declare it in constructor as

constructor(public platform: Platform, private media: Media) {}

Step 3 — Various Music plugin Features

Now that he plugin is installed and imported correctly, we move on to integrate its methods. Let’s have a look at different methods the plugin supports 

Complete source code of this tutorial is available here — Ionic-4-music

Create Media

This is the basic routine the plugin needs to perform in order to import the song/audio file into the app. For demo purpose, we will use an external URL to one of the old hits — Hotel California 🎸 . Here’s the URL for the song (Please check if the URL still exists, otherwise use any other mp3 URL)

http://fabienne.sigonney.free.fr/tranquilit/Eagles - Hotel California (Acoustic).mp3

To create a playable media, you need to assign the media file to a variable via the create method of the plugin

this.curr_playing_file = this.media.create(this.play_The_track);

Now, this.curr_playing_file can be used throughout the page to play / pause/ stop the song etc. 

Play / pause

The most basic function of a music player. The plugin allows you to play or pause a “created” media. The method could not have been simpler 😄

this.curr_playing_file.play();

Note — The plugin take a little time to load the media. Make sure you are not calling play() on an uncreated media variable. 

Also, Paused media plays from the same place it was paused.

GetDuration

This method is used to get the total length of the audio file, so you can display the time in your app (as I’ve shown in the screens above). You can get the duration by calling

this.curr_playing_file.getDuration();

But, getting duration in the plugin is a little tricky (or I would say hacky). The plugin doesn’t give away duration directly at the first call. There are two things to note

  1. If getDuration() is called right after media is created, the duration returned will be -1
  2. If getDuration() is called without playing the media file even once, the duration returned will still be -1. To avoid this, the hack we use is :
  • Create the media file as usual 
  • Play the media file, but keep the volume to 0 by calling this.curr_playing_file.setVolume(0.0)
  • Call getDuration() in a loop (sadly, yes) until you find a seemingly valid value of duration for the song. Following is my code to get the duration

Get duration of the song with this Hacky method

Getting duration takes some time. Hence, as a UX feature you can keep the Play button disabled till the duration is obtained. And show a nice little loader somewhere to let the user know what is happening. 

Note — Do not forget to clearInterval once the duration is obtained. Otherwise the loop will continue forever.

GetCurrentPosition

getCurrentPosition is pretty self explanatory. It tells you the current position of song, in seconds. Again, this has a hacky implementation. I hope as the plugin improves, this method would improve to have a non-hacky solution.


Get current position of song and update the variable to update the Seek Bar

Notice the toHHMMSS() function I have used for converting seconds into a mm:ss format. This is what you would like to show to your users, instead of an integer value in seconds, as shown below.



Show the time values in mm:ss format for a good UX

SeekTo

Because a great music player has the ability to jump to a particular time in the song, our plugin also has that capability. The seekTo() method allows users to jump to any moment in the song using the seekbar.

I have implemented the seek bar as an Ionic Range component, where the position of circle is controlled by the ngModel . We can update the position variable using the values from getCurrentPosition() method.

<ion-range min="0" max="{{duration}}" [(ngModel)]="position" color="light"></ion-range>

I have implemented a FastForward and a Rewind button to demonstrate this function. The associated code goes like this. E.g. Rewind button with call controlSeconds('back')


Stop

When the song is over, we need to stop it. That’s why the plugin has this method to stop the audio playback. Notice that stopping the song does not release it from the memory in Android.

this.curr_playing_file.getDuration();

Release

Releases the underlying operating system’s audio resources. This is particularly important for Android since there are a finite amount of OpenCore instances for media playback. Applications should call the release function for any Mediaresource that is no longer needed.

onStatusUpdate

This is subscribe operation. With this, we can subscribe to the status of the song — whether it is playing, paused or stopped. This is useful when we want to change the play button to pause, and vice versa. 


Get status of the song to change Play / Pause icons etc.

Step 4 — Test on Android

Now that everything is ready, we need to build this app for Android. Why ? Because Cordova plugins do not work on browser 😆

If you have carried out the above steps correctly, Android build should be a breeze.

Run the following command to create Android platform

$ ionic cordova platform add android

Once platform is added, run the app on device (Make sure you have a device attached to the system).

$ ionic cordova run android

Once your app is up and running on the device, you can start testing all the functions. I have recorded a video just in case you wanna see it in action!


And here you are, playing music in your own Ionic 4 app 🎉 🎉

Conclusion

In this post, we learned how to implement music player functionalities in an Ionic 4 app. We learned how to use play, pause, seek, etc functionalities. You can now implement music playback in your Ionic 4 apps and create something exciting! 

Complete source code of this tutorial is available here — Ionic-4-music. This demonstration is supported by Ionic 4 Spotify Starter from Enappd

Next Steps

Now that you have learned the implementation of Firebase push notifications in Ionic 4, you can also try

If you need a base to start your next Ionic 4 app, you can make your next awesome app using Ionic 4 Full App



Use Ionic 4 Full app template for your next awesome app




Title
Subtitle
Kicker



SHARE BLOG

PUBLISHED BY

spotify-like-music-in-ionic-4-apps

Abhijeet Rathore

Co-founder, Enappd

ENAPPD