Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recording audio using cordova media plugin results in empty file

I'm using the following code to record audio using Cordova Media plugin on android devices. This results in an empty audio file despite returning successfully on stopRecord(). Can somebody point to what might be wrong with this code?

$cordovaFile.createFile(cordova.file.dataDirectory, 'new-rec.amr'), false)
    .then(function (fileObj) {
      console.log('File created', fileObj);

      var nativePath = fileObj.nativeURL;
      resolveLocalFileSystemURL(nativePath, function (entry) {
        var internalPath = entry.toInternalURL();

        var mediaRec = new Media(internalPath,
          //success callback
          function (success) {
            console.log("record success", success);
          },

          //error callback
          function (err) {
            console.log("record error: " + JSON.stringify(err));
          });

        // Start recording audio
        mediaRec.startRecord();
      });
    }, function (error) {
      console.log('Cannot create a file to initiate a new recording', error);
    });
like image 968
gopalkoduri Avatar asked Jan 05 '16 04:01

gopalkoduri


1 Answers

I was having this exact same problem today. Solved it by releasing the Media object. I'm not sure why this helped, but I have a feeling it may be that the OS is holding onto the Media object instead of saving it and then once it's released it's properly saved?

Not 100% sure though. It works without releasing in other Cordova directories (e.g. cordova.file.externalDataDirectory).

Here's my code:

var fileName = randomFileName();   
fileName = fileName + ".aac";
var store = cordova.file.dataDirectory;

window.resolveLocalFileSystemURL(store, function(dir){

    var directoryToSave = dir.nativeURL + fileName;        

    $scope.audioRecording = new Media(directoryToSave, audioRecordingSuccess, audioRecordingFail, audioStatus);

    $scope.audioRecording.startRecord();

    setTimeout(function(){
        $scope.audioRecording.stopRecord();
        $scope.audioRecording.release();
    }, 5000);

});
like image 79
Shib TPF Avatar answered Oct 28 '22 06:10

Shib TPF