MediaPlugin does not save audio recording into file [ionic-native]

Hello :smiley:

I am not using createFile, i am usign directly the media.create method and i dont have a external storage like an sd card, but externalDataDirectory is accessible (iโ€™ve changed to external after i saw a guy saying that only external was working to him).

If you look on the media plugin android native code, you will see that, when you execute the startRecord, creates a .3gp file (the file you can see on the file tool), when you call the stopRecord method, it will try to save to destination file (specified on media.create), the problem is, the code check if the file destination start with a โ€œ/โ€, if not, then the file name is prepended with the cache directory, so if you try to save to file://xxxx.3gp (all directories from native File starts with file://) the code will try to save on /data/data/com.package.your/cache/file://xxxx.3gp.

So your file still with size 0, simply because the media plugin is trying to save in another destination, this is why you have to remove the initial โ€œfile://โ€. (the .replace(/file:///g, โ€˜โ€™) will do it)

this is the android code where the filename is prepended

    ...
    public void moveFile(String file) {
       if (!file.startsWith("/")) {
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                file = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + file;
            } else {
                file = "/data/data/" + handler.cordova.getActivity().getPackageName() + "/cache/" + file;
            }
        }
       ...
    }
    ...

so i would recommend you to change your code to:

  private fileName: string;

  constructor(public navCtrl: NavController, private media: MediaPlugin, private file: File, private platform: Platform) {
    this.platform.ready().then(() => {
      if (!this.platform.is('cordova')) {
        return false;
      }

      if (this.platform.is('ios')) {
        this.fileName = file.documentsDirectory.replace(/file:\/\//g, '') + 'record.m4a';
      }
      else if (this.platform.is('android')) {
        this.fileName = file.externalDataDirectory.replace(/file:\/\//g, '') + 'record.3gp';
      }
      else {
        // future usage for more platform support
        return false;
      }
    });
  }

  record() {
    let audioObject: MediaObject = this.media.create(this.fileName);

    audioObject.startRecord();
    console.log('cache dir: ' + this.file.cacheDirectory);
    console.log('start recording' + this.fileName);
    setTimeout(() => {
      audioObject.stopRecord();
      console.log('duration: ' + audioObject.getDuration());
      audioObject.release();
      console.log('done recording' + this.fileName);
      /** Do something with the record file and then delete */
      // this.file.removeFile(this.file.tempDirectory, 'record.m4a');
    }, 5000);
  }
3 Likes