Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Using Ionic - Cordova Native Audio in Phonegap application

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 770
    Comment on it

    native audio plugin is used for playing audio in your ionic application.

    To use this plugin you need to install it first in your application directory by following command:
     

    cordova plugin add cordova-plugin-nativeaudio

    you first need audio file which is saved inside your js folder or anywhere you want to place it.
    Next you have to preload audio file in your project so that it can be used. For this two options available: preloadSimple and preloadComplex.

    preloadSimple : It is used for sounds that are played once.

    preloadComplex : It is used for sounds that are in looping or like background audio.

    This is the code to add in your controller:

    $ionicPlatform.ready(function() {
       $cordovaNativeAudio
       .preloadSimple('click', 'js/click.mp3')
        
       .then(function (msg) {
          console.log(msg);
       }, function (error) {
          console.log(error);
       });
    
       $cordovaNativeAudio.preloadComplex('click', 'js/click.mp3', 1, 1)
        
       .then(function (msg) {
          console.log(msg);
       }, function (error) {
          console.error(error);
       });
        
    });

    To play sound, you have to add below code in the same controller:

    $scope.playAudio = function () {
       $cordovaNativeAudio.play('click');
    };
    
    $scope.loopAudio = function () {
       $cordovaNativeAudio.loop('click');
    
       $timeout(function () {
          $cordovaNativeAudio.stop('click');
          $cordovaNativeAudio.unload('click');
       }, 5000);
    }

    here timeout will stop and unload looping sound after 5 seconds.

    Now, you have to create buttons in html file, by clicking which sound plays:

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

    When you click on PLAY button, the sound will be played once, and on clicking LOOP button sound will be played in loop for five seconds.

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: