Friday, 22 January 2016

Post 41: Play sound/audio in ionic app

In one of my last post I described how to play sound on ionic app. If you have updated your ionic framework to 1.7.x, then chances are that that tutorial isn't working for you anymore, since the cordova-media plugin is not compatible with newer versions of ionic.

That's why I want to show you another way that also works for newer ionic versions:

First create an ionic project

cordova plugin add cordova-plugin-nativeaudio
Install ng-cordova:
bower install ngCordova --save
Go to www/index.html and add this script tag after bundle.js and cordova.js

<script src="lib/ngCordova/dist/ng-cordova.js"></script>
Go to www/js/app.js and inject the dependency "ngCordova":

angular.module('starter', ['ionic', 'ngCordova'])  
In your www/index.html file replace this with the body:
<body ng-app="starter">  
        <h1 class="title">Native Audio</h1>
      <ion-content ng-controller="SoundController as vm">
        <p><button ng-click="'bass')" class="button icon-left ion-play button-assertive">Play Bass</button></p>
        <p><button ng-click="'hi-hat')" class="button icon-left ion-play button-balanced">Play Hi-Hat</button></p>
        <p><button ng-click="'snare')" class="button icon-left ion-play button-energized">Play Snare</button></p>
        <p><button ng-click="'bongo')" class="button icon-left ion-play button-positive">Play Bongo</button></p>
In your www/js/app.js file add the controller:

.controller('SoundController', ['$ionicPlatform', '$timeout',  '$cordovaNativeAudio', SoundController]);

function SoundController($ionicPlatform, $timeout, $cordovaNativeAudio) {  
    var vm = this;

    $ionicPlatform.ready(function() {

        // all calls to $cordovaNativeAudio return promises

        $cordovaNativeAudio.preloadSimple('snare', 'audio/snare.mp3');
        $cordovaNativeAudio.preloadSimple('hi-hat', 'audio/highhat.mp3');
        $cordovaNativeAudio.preloadSimple('bass', 'audio/bass.mp3');
        $cordovaNativeAudio.preloadSimple('bongo', 'audio/bongo.mp3');
    }); = function(sound) {

    return vm;
Go to your /www-folder and create a new folder called "audio". In this audio-volder put in some mp3 files (and name them snare.mp3, bass.mp3, bongo.mp3, etc.).

Build and run your project. Click here to see how to build and run your ionic project.