Skip to content Skip to sidebar Skip to footer

Phonegap Media Api - Record And Play Audio - Android

I'm hoping to record some audio and then have the ability to play it back. Its important for me to be able to customize the record interface. In the below example after recording

Solution 1:

Here are my steps for getting this to work.

1. Run these commands

ionic start RecordTest blank
ionic platform add ios
cordova plugin add org.apache.cordova.media

2. Create RecordTest/www/myrecording.wav

3. Paste the below code in RecordTest/www/index.html

<!DOCTYPE html><html><head><metacharset="utf-8"><metaname="viewport"content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width"><title></title><linkhref="lib/ionic/css/ionic.css"rel="stylesheet"><linkhref="css/style.css"rel="stylesheet"><!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
    <link href="css/ionic.app.css" rel="stylesheet">
    --><!-- ionic/angularjs js --><scriptsrc="lib/ionic/js/ionic.bundle.js"></script><!-- cordova script (this will be a 404 during development) --><scriptsrc="cordova.js"></script><!-- your app's js --><!-- <script src="js/app.js"></script> --><scripttype="text/javascript"charset="utf-8">// Wait for PhoneGap to load//document.addEventListener("deviceready", onDeviceReady, false);

    // Record audio// functionrecordAudio() {
        var src = "myrecording.wav";
        var mediaRec = newMedia(src, onSuccess, onError);

        // Record audio
        mediaRec.startRecord();

        // Stop recording after 10 secvar recTime = 0;
        var recInterval = setInterval(function() {
            recTime = recTime + 1;
            setAudioPosition(recTime + " sec");
            if (recTime >= 3) {
                clearInterval(recInterval);
                mediaRec.stopRecord();
                mediaRec.play();
            }
        }, 1000);
    }

    // PhoneGap is ready//functiononDeviceReady() {
        recordAudio();
    }

    // onSuccess Callback//functiononSuccess() {
        console.log("recordAudio():Audio Success");
    }

    // onError Callback //functiononError(error) {
        alert('code: '    + error.code    + '\n' + 
              'message: ' + error.message + '\n');
    }

    // Set audio position// functionsetAudioPosition(position) {
        document.getElementById('audio_position').innerHTML = position;
    }
    </script></head><bodyng-app="starter"><ion-pane><ion-header-barclass="bar-stable"><h1class="title">Ionic Blank Starter</h1></ion-header-bar><ion-content><title>Device Properties Example</title><!-- <script type="text/javascript" charset="utf-8" src="phonegap-1.4.1.js"></script> --><pid="media">Recording audio...</p><pid="audio_position"></p></ion-content></ion-pane></body></html>

4. Run ionic emulate ios

The above should work.

Note: the extension changes depending on the platform you're developing for

Solution 2:

I'm working with something similar with ionicframworkf and phonegap plugins.. I build a Record Factory for:

startRecord, stopRecord, playRecord and Save record to the server... This is my factory file:

/**
 * Record service
 * @modulerecord
 * @author Claudio A. Marrero
 * @classfamvoice
 */
 services.factory('$record', [

  '$rootScope',
  '$socket',
  '$account',

  function($rootScope, $socket, $account) {

    var enumerator = 0;
    var recordName = 'record-'+enumerator+'.mp3';
    var mediaRec = null;
    varOnCallback = null;
    varOnAppendData = {};

    /**
    * Start a record
    *
    * @methodstartRecord
    */functionstartRecord(){
      enumerator++;
      recordName = 'record-'+enumerator+'.mp3';
      mediaRec = newMedia(recordName,
          function() {
          },
          function(err) {
          });
      mediaRec.startRecord();
    }

    /**
    * Stop record
    *
    * @methodstopRecord
    */functionstopRecord(){
      mediaRec.stopRecord();
    }

    /**
    * Stop record
    *
    * @methodstopRecord
    */functionplayRecord(){
      mediaRec.play();
    }

    /**
    * Get the name of the record
    *
    * @methodgetRecord
    */functiongetRecord(){
      return recordName;
    }

    /**
    * Save the recorded file to the server
    *
    * @methodsave
    */functionsave(callback,appendData){
      OnCallback = callback;
      OnAppendData = appendData;
      window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, OnFileSystem, fail);
    }

    /**
    * Callback for setting the file system to persistent.
    *
    * @methodOnFileSystem
    */functionOnFileSystem(fileSystem){
      fileSystem.root.getFile(recordName, null, OnGetFile, fail);
    }

    /**
    * Callback for geting the file for disk
    *
    * @methodOnGetFile
    */functionOnGetFile(fileEntry){
      fileEntry.file(OnFileEntry, fail);
    }

    /**
    * Callback for file entry, this get the file.
    *
    * @methodOnFileEntry
    */functionOnFileEntry(file){
      var reader = newFileReader();
      reader.onloadend = function(evt) {

          var image = evt.target.result;
          var base64Data  =   image.replace(/^data:audio\/mpeg;base64,/, "");
          base64Data  +=  base64Data.replace('+', ' ');

          $socket.emit('playlists:file',{file:base64Data,name:recordName, token: $account.token(), info:OnAppendData},OnCallback);
      };
      reader.readAsDataURL(file);
    }

    /**
    * When any process of saving file fail, this console the error.
    *
    * @methodOnFileEntry
    */functionfail(err){
      console.log('Error');
      console.log(err);
    }

    /**
    * Play record
    *
    * @methodplayRecord
    */functionplayRecord(){
      var mediaFile = newMedia(recordName,
          function() {
            console.log("playAudio():Audio Success");
          },
          function(err) {
            console.log("playAudio():Audio Error: "+err);
          }
      );
      // Play audio
      mediaFile.play();
    }

  return {
    start: startRecord,
    stop: stopRecord,
    play:playRecord,
    name:getRecord,
    save:save
  };
}]);

My project is on GitHub if you want to check how I implement this factory:

https://github.com/cmarrero01/famvoice

You will need to checkout the development branch.

I hope that is ussesful for you. :)

PH: I notice this question on codementor request, but I'm not a good english speaker. :)

Post a Comment for "Phonegap Media Api - Record And Play Audio - Android"