Search code examples
androidemailuriattachmentrecording

Sending android audio recorded file as an attachment of an email giving error when trying to read file (URI path not absolute)


I'm saving an audio file using Media recorder and the following code:

 public class AudioRecorder {

 final MediaRecorder recorder = new MediaRecorder();
 final String path;


  /**
   * Creates a new audio recording at the given path
   */
  public AudioRecorder(String path) {
  this.path = sanitizePath(path);
}

public static String sanitizePath(String path) {
   if (!path.startsWith("/")) {
      path = "/" + path;
   }
   if(path.endsWith("/")){
      path = path + "/";
  }
  return path;
 }

 /**
  * Starts a new recording.
  */
  public void start() throws IOException {
  // make sure the directory we plan to store the recording in exists
  File directory = new File(path).getParentFile();
  if (!directory.exists() && !directory.mkdirs()) {
  throw new IOException("Path to file could not be created.");
 }

   recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
   recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
   recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
   recorder.setOutputFile(path);
   recorder.prepare();
   recorder.start();
  }

 /**
  * Stops a recording that has been previously started.
  */
 public void stop() throws IOException {
 recorder.stop();
 recorder.release();
 }
}

I am then calling this class using the following code

 int timeOfRecroding = AppPrefs.getSettingsAdditionalTimeOfRecording() * 60 * 1000;
        ContextWrapper cw = new ContextWrapper(getApplicationContext());
    File directory = cw.getDir("media", Context.MODE_PRIVATE);

    final String pathAndName = AudioRecorder.sanitizePath(directory.getAbsolutePath() + "/LocRec.3gp");
    final AudioRecorder audioRecorder = new AudioRecorder(pathAndName);

    if(Constants.isTest){
        showToast("Starting recording for [" + AppPrefs.getSettingsAdditionalTimeOfRecording() + "] minutes");
        showToast("Recording to path: [" + pathAndName + "]");

    }

and then of course using audioRecorder.start(); and audioRecorder.stop(); do the actual recording

After the recording is done I using the same pathAndName to get the file and send it as attachment in an email using the following code to get the file

new File(new URI(AppPrefs.getInfoToSend(Constants.SERVICE_CODE_SEND_RECORDING, Constants.MESSAGE_TYPE_EMAIL)))

but this is throwing an excpetion

URI is not absolute: /data/data/com.testrecoding.record/app_media/LocRec.3gp

I appreciate any help, Thanks, Wassim


Solution

  • it may sound stupid, but I found a turn-around, not really a turn-around, not sure how I missed it in the first place, getting the file from the path directly without using URI

     new File("PathOfFIle")