Ionic - Cordova Native Audio


This plugin is used for adding native audio sounds to the Ionic app.

Using Native Audio

To be able to use this plugin, we first need to install it. Open the command prompt window and add the Cordova plugin.

C:\Users\Username\Desktop\MyApp>cordova plugin add cordova-plugin-nativeaudio

Before we start using this plugin, we will need audio file. For simplicity, we will save our click.mp3 file inside the js folder, but you can place it wherever you want.

The next step is to preload the audio file. There are two options available, which are −

  • preloadSimple − It is used for simple sounds that will be played once.

  • preloadComplex − It is for sounds that will be played as looping sounds or background audio.

Add the following code to your controller to preload an audio file. We need to be sure that the Ionic platform is loaded before we can preload the audio file.

Controller Code

$ionicPlatform.ready(function() {
   .preloadSimple('click', 'js/click.mp3')
   .then(function (msg) {
   }, function (error) {

   $cordovaNativeAudio.preloadComplex('click', 'js/click.mp3', 1, 1)
   .then(function (msg) {
   }, function (error) {

In the same controller, we will add code for playing audio. Our $timeout function will stop and unload looping audio after five seconds.

$scope.playAudio = function () {

$scope.loopAudio = function () {

   $timeout(function () {
   }, 5000);

The last thing we need is to create buttons for playing and looping audio.


<button class = "button" ng-click = "playAudio()">PLAY</button>

<button class = "button" ng-click = "loopAudio()">LOOP</button>

When we tap on play button, we will hear the sound once and when we tap on the loop button, the sound will loop for five seconds and then stop. This plugin works only on an emulator or a mobile device.