TL;DR: In this article, you will learn how to develop an audio player app using Angular and RxJS. You will handle audio operations and application state using RxJS. To secure your application, you will use Auth0. If needed, you can find the final code in this GitHub repository.
Introduction
Creating an audio player is always an intimidating task, especially if you think about managing the media’s state, reacting to media events, and reflecting these changes correctly on the UI (User Interface). So, in this article, you will use Angular and Angular Material (with some other libraries) to easily tackle these challenges.
To handle media playback in a reactive way, you will wrap JavaScript’s Audio
object with an RxJS Observable and you will also use RxJS to manage the state of your audio player.
To provide a secure user experience through your application, you’ll add user authentication through Auth0.
Prerequisites
Since you are going to use Angular, you will need to install Node.js in your development machine. So, if you haven’t done so yet, go to the download page of Node.js and follow the instructions there.
After Installing it, you will need to install Angular CLI via npm
:
If you are using npm v5.2+, you can use
npx
to use@angular/cli
without installing it by runningnpx @angular/cli [options that follow the ng global command]
Scaffolding the app
After installing all the environment dependencies, you can focus on scaffolding your Angular app. To do this, issue the following command on a terminal:
You can use also use npx
to scaffold the app:
This command will ask you three questions:
- Would you like to add Angular routing? (y/N): You can input
y
(yes) as you are going to use Angular Routing in the app. - Which stylesheet format would you like to use? (Use arrow keys): Select
SCSS
from the options given. - Would you like to share anonymous usage data with the Angular Team at Google under Google’s Privacy Policy at https://policies.google.com/privacy For more details and how to change this setting, see http://angular.io/analytics. (y/N): If you want to share data with Google press
y
else pressN
.
Running the application
Before continuing, make sure you can start your application in the browser. Make angular-audio
your current working directly:
Once there, you can simply run:
In your browser, visit http://localhost:4200/
to open the app.
Installing project dependencies
Having confirmed that you can run the basic app in the browser, you can start building this app by installing the dependencies. To build your audio player, you will use the Angular Material Library. You can install it using the ng add
command:
This command will ask you three questions:
- Choose a pre-built theme name, or “custom” for a custom theme: Choose
Indigo/Pink
- Set up HammerJS for gesture recognition?: You can input
y
(yes) since you need gesture recognition. - Set up browser animations for Angular Material? (Y/n): you can input
y
(yes) again because you will need animation.
You are also going to use moment.js
to manipulate dates and times. Install it via npm
:
Note: RxJS comes bundled with Angular
Developing the Audio Player UI Using Angular Material
In this section, you will design the UI of the application. In the end, your application will look like this:
Since your app will use Angular Material Components, you’ll need to import them inside your root NgModule
.
To do so, create a material
module using the ng generate
command:
The
ng generate module
command creates the module with the given name; in your case, the name ismaterial
. The--module=app
option allows you to specify in which module to import the new one, and--flat
creates the module into the root directory without creating an extra folder.
The previous command will generate material.module
in the /src/app
directory. Replace the content of that file with the following code:
Then, you are going to create the app-player
component using the @angular/cli
:
It will generate a player.component.ts
file and other required files within the src/app/pages/player/
directory.
Audio player HTML
Inside the ./src/pages/player
directory, you will find the player.component.html
file. In this file, you will add some HTML to define your player structure. As you will see, the top-level element is a div
with the container
class. On the top, you will have a navigation bar which contains the name of the application inside <mat-toolbar>
.
Below the header, you will have a div
element with class content
which will have your app’s logo and a <mat-list>
with the list of media files.
Finally, the footer div
element with class .media-footer
will have two <mat-toolbar>
elements.
In the first <mat-toolbar>
, you will have a <mat-slider>
. This will allow the user to change the current time of the audio track.
In the second <mat-toolbar>
, you will have rest of the playback controls.
Replace the content of src/app/pages/player/player.component.html
with the following code:
Styling the audio player
Just to improve the look and feel of your app, you will do some minor styling in the player.component.scss
file (you can find it under ./src/pages/player/
), as shown below:
To ensure that your application compiles, open player.component.ts
and update it with the following content which includes mock data:
Updating the router
In order to see the UI, you need to configure the router inside the app-routing.module.ts
file to use PlayerComponent
as a route like so:
You also have to replace the content of app.component.html
with <router-outlet></router-outlet>
as following:
At this point, you can actually see how the app looks like. Go ahead and spin up the development server with npm start
and open the browser at localhost:4200
. You should see this:
However, you will observe that none of our buttons are working. Let’s start adding functionality to our application.
Creating a Service to Manage the Audio Playback
After creating the audio player UI, you can start working on the playback feature.
Creating playback Observable
The Observable that you are going to create is the central piece of your application. RxJS comes with an Observable
constructor to help you create custom observables. It takes a subscribe
function as an input and returns an Observable
.
This subscribe
function takes an observer
object and returns an unsubscribe
function. Observer objects provide three methods: next
, error
, and complete
.
- To emit a value, you can call the
observer.next
method with the desired value. - In case of an error, you can use the
observer.error
function to throw the error and make the observable stop. - If you no longer need the observer and there are no more values to emit, you can call the
observer.complete
method.
Don’t be confused with
new Observable(subscribe)
andObservable.subscribe()
. Thesubscribe
method that you pass into theObservable
constructor is like a blueprint of an Observable and you can execute it by invokingObservable.subscribe()
method.To know more about Observables, take a look at Reverse Engineering Observable.
In your audio player app, you are going to create an observable to get notifications about media events like playing
, pause
, timeupdate
, and so on. So, basically, you will listen to the media events of Audio
inside the observable and then notify the rest of the app via the observer.next
method.
Now that you understand why you need an observable, you can start by creating a service using it in your Angular app:
This will generate service in a file called audio.service.ts
under ./src/services/audio/
. Replace the contents of the audio.service.ts
file with:
Now, whenever you want to play a new audio file, you will create this observable and listen to all these media events. You will do this via a new method called playStream()
that you are going to add to the AudioService
class:
Adding the playback methods
Now that you have the basis of the AudioService
, you can develop the rest of its methods: play
, pause
, stop
, seekTo
, and formatTime
. As their implementation is self-explanatory, you can simply add these five methods to the AudioService
service as shown below:
Managing Playback State Using RxJS
In a typical Angular application, you might use some state management library like NgRx
. But in this application, you are going to use BehaviorSubject
to manage the state of the application.
You are going to update AudioService
to manage the state since the state is dependent on audio playback.
Creating StreamState interface
In order to take more advantage of TypeScript’s type checking; first, you are going to create an interface
for state management.
This will generate an interface in a file called stream-state.ts
under ./src/interfaces/
. Replace the content of the file with the following:
This list explains what these values mean:
playing
: a boolean which indicates if there is any audio playingreadableCurrentTime
: a string which gives you the current time of playing audio in a human-readable formreadableDuration
: the human-readable duration of the current audioduration
: the duration of current audio in millisecondscurrentTime
: the current time of audio in millisecondscanplay
: boolean to indicate if you can play the selected audio or noterror
: a boolean to indicate if an error occurred while playing audio or not
Creating a default state
Now you are going to import the StreamState
interface and create a state
object with the initial state as following:
Emitting the state changes
You will also need a way to emit state changes. So you are going to use BehaviorSubject
named stateChange
. You will also provide and emit the default value of state as shown below. Also, the state is dependent on Audio Events like playing
, pause
and so on. You are going to update state by reacting to those events using the updateStateEvents
method. The updateStateEvent
method takes an audio event and set this.state
. In the end, you are going to emit the latest state via stateChange
subject as shown:
Resetting the state
When you need to reset the state. You can do it using resetState
method as following:
Reading the state
You are going to need a method to share the stateChange
BehaviorSubject to the rest of the application. However, providing access to Subject outside the service can be dangerous. So you will use asObservable
method of BehaviorSubject
to only return Observable
part as follows:
Updating streamObservable
Finally, you need to adapt the streamObservable
method by firing updateStateEvent
method inside it and also resetting the state during unsubscription. The updated streamObservable looks like this:
You can check the final version of AudioService
here.
Reading the Music Files
After managing the state of the application, you will need to create a service to get a list of files. To do so, you can create a cloud service using Angular:
This command will generate service in a file called cloud.service.ts
under ./src/services
. Now, replace the contents of this file with:
The getFiles
method above basically mocks an HTTP request by returning an Observable
with a hardcoded files
object.
Stitching All Together
So far you have written code for services and created the UI of the application. Now you will stitch both of them together by implementing PlayerComponent
.
The audio player UI controller
To help you control your audio player user interface, you will implement a controller responsible for the following things:
- fetching all the media files
- adding the playback feature in the app
You will implement the following methods:
constructor
: creates an instance of Player Component, then it will grab all the media files from the cloud service and finally it will start listening to state updates fromAudioService
viagetState
methodplayStream
: it will subscribe to AudioService.playStream to start playing an audio file for the first timeplay
: it will restart the audio playbackpause
: it will pause the audio playbackstop
: it will stop the audio playbackopenFile
: it will grab the audio file, set it as the current file and then play it using theplayStream
methodnext
: it will play the next track from the audio playlistprevious
: it will play the previous track from the audio playlistisFirstPlaying
: it will check if the first track is playing or notisLastPlaying
: it will check if the last track is playing or notonSliderChangeEnd
: it will fire when the user uses the slider andseekTo
that part of the music
First, you will need to import required files and create files
, state
, and currentFile
properties as shown:
constructor
The constructor will create an instance of PlayerComponent
and fetch the media files and then assign them to this.files
property. It will also subscribe to state changes and assign it to this.state
property.
playStream
Method
Then, the playstream
method can fire the playStream
method of your AudioService
. This method on the service returns an observable that you will use to subscribe and start listening to media events like canplay
, playing
, etc. However, you don’t really need those values or events because you can read them using the stateChange
subject. This method is used to start observable and audio playback.
openFile
Method
Whenever the user clicks on a media file, the openFile
method will be fired. Then, this method will fire the playStream
method with the URL
of the file
chosen.
pause
Method
Once the playStream
method is fired, the media playback is initiated. As such, your users might want to pause the playback. For that, you will implement the pause
method as follows:
play
Method
It’s also true that users might want to start playing the media again. For that, you will add the following:
stop
Method
Then, to stop the media, you will add the following method:
The next
Method
Also, to let your users move to the next music, you will define the following method:
The previous
Method
Similarly, you will need to provide a method to play the previous track:
The isFirstPlaying
and isLastPlaying
Methods
Then, you will need two helper methods to check if the music being played is the first or the last track from the playlist. You use these methods to disable and enable the UI buttons:
The onSliderChangeEnd
Methods
Also, you will want to enable your users to do seek operations. So, when the seek operation ends, Angular will fire the onSliderChangeEnd
method and, in it, you can fetch the time selected by the user and seekTo that time:
Building and running the audio player
After implementing the application, you can run it via @angular/cli:
The above command will spin up a web server at http://localhost:4200/
.
Authentication with Auth0
To develop a secure app, you are going to rely on Auth0 to handle the authentication of your users. As such, you can sign up for a free Auth0 account here. Then, you will need to set up an Auth0 Application to represent your mobile app.
Installing dependencies
To secure your Angular app with Auth0, you will have to install auth0-js
via npm:
Set up an Auth0 application
- Go to your Auth0 Dashboard and click the “create a new application” button.
- Name your new app (e.g. “Angular Audio Player”), select “Single Page Application” as its type, and click the “Create” button.
- In the Settings tab of your new Auth0 app, add
http://localhost:4200
in the Allowed Callback URLs. - Add
http://localhost:4200
to both the Allowed Web Origins and Allowed Logout URLs. - Click the “Save Changes” button.
Configuring Auth0
Now you are going to add Auth0 Configuration to the environment.ts
file under src/environment
directory:
This list explains what these values mean:
clientID
: the Client Id property available in your Auth0 Application.domain
: your Auth0 Domain (e.g.your-domain.auth0.com
redirectUri
: the URL where the user will be redirected after login. You can use the same URL as your callback URL herelogoutUrl
: the URL that you want your user to direct when he/she log out.
Auth service
After creating your Auth0 account and defining the Auth0 config in the environment file, you will need to define an authentication service in your Angular app. To do so, you will use @angular/cli
:
This command will generate service in a file called auth.service.ts
under ./src/services
. Now, replace the contents of this file with:
To better understand how the code above works, take a look into the following explanation:
auth0
: is an instance ofauth0-WebAuth
, which you will use for the authentication_authFlag && _userProfileFlag
: are thelocalStorage
keys for storing authentication and user profile datatoken$
: anObservable
which emits access tokenuserProfile$
: thisBehaviorSubject
creates a stream for the profile dataonAuthSuccessUrl && onAuthFailureUrl
: the URLs which Auth0 will redirect to after success and failure of authentication respectivelylogoutUrl
: the URL where the user is redirected after log outparseHash$
: anObservable
which parse the hash and gives you back the auth resultcheckSession$
: anObservable
use to check the session and then renew the token if it is required
Now, take a look at the methods of the service above:
constructor
: In the constructor, you are going to check if there is any user information stored inlocalStorage
. If yes, then you will emit it viauserProfile$
BehaviorSubjectlogin()
: In the login method, you authorize the userhandleLoginCallback()
: After authentication, this method is going to be fired. It usesparseHash$
Observable to parse the auth result and then it sets the authentication state usingthis._setAuth
method and finally redirect toonAuthSuccessUrl
_setAuth()
: takesauthResult
from parsed Auth data and initializestoken$
. sets the Auth State inlocalStorage
along withuserProfile
dataauthenticated()
: is used to check if the user is authenticated or not usinglocalStorage
flagrenewAuth()
: checks if the user is authenticated or not and then check session if it’s valid or not and set’s auth state respectivelylogout()
: it logs out the user by removing auth state and user data fromlocalStorage
. It also calls theauth0.logout
method which redirects the user to givenlogoutUrl
Auth guard
Now that you have created AuthService. You can create AuthGuard
, which allows you to secure routes of the application. Use Angular Cli to generate the guard as follows:
This command will generate the auth.guard.ts
file under /src/app/guards
directory. Update the content of the file with the following:
It basically checks if the user is logged in or not. If the user is logged in, it allows the user to access the given route otherwise redirect the user to /
route.
Updating the UI
Now that you have created the AuthService
and AuthGuard
, you can use them to add authentication to the player.
Profile page
First, you are going to create an extra page for the player. You are going to add user profile information on that page. You will use @angular/cli
:
Open the profile.component.ts
file in pages/profile
directory and add the following content:
Now open the profile.component.html
add the following content:
Finally, open the profile.component.scss
and add the following content:
User can access this component at /profile
URL.
You have to add this route to router
config in the app-routing.module.ts
file as follows:
Updating player component
You also have to update the player component by adding the Authentication UI and also link to the Profile page. You are going to update player.component.html
by adding the <mat-toolbar>
in the header as follows:
Along with Toolbar, you have to hide the playlist if user is not logged in. You can simply add *ngIf="auth.authenticated"
to the playlist as follows:
Also, you have to inject the AuthService inside PlayerComponent
as follows:
Updating AppComponent
Finally, you have to update the app.component.ts
file to handle authentication as follows:
Running
You can run the application using @angular/cli
:
Conclusion
In this article, you created an audio player app with Angular. You used RxJS to develop audio playback features and handle state management. Beyond that, you also used Auth0 to handle user authentication in your app. With this, you have finished developing the application with static audio content.
I hope you enjoyed this article. Again, you can find the final code in this GitHub repository. See you next time!