How can I specify the output file's folder whe

2019-03-02 03:09发布

I'd like to specify a destination folder when I call the MediaStore built-in sound recorder app, e.g. the sdcard folder. According to the Android documentation, there is no support for EXTRA_OUTPUT when calling the RECORD_SOUND_ACTION.

How can I do this?

1条回答
对你真心纯属浪费
2楼-- · 2019-03-02 03:26

You will have to allow the file to be recorded using whatever default filename and location are used and then move the file. Moving the file is far from trivial. Here's a complete example.

import java.io.File;
import java.io.IOException;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;

import com.google.common.io.Files;

public class SoundRecorder extends Activity {
   private static final int RECORD_QUESTION_SOUND_REQUEST_CODE = 1;

   @Override protected void onResume() {
      super.onResume();
      Intent recordIntent = new Intent(
            MediaStore.Audio.Media.RECORD_SOUND_ACTION);
      // NOTE: Sound recorder does not support EXTRA_OUTPUT
      startActivityForResult(recordIntent, RECORD_QUESTION_SOUND_REQUEST_CODE);
   }

   @Override protected void onActivityResult(
         int requestCode, int resultCode, Intent data) {
      switch (requestCode) {
      case RECORD_QUESTION_SOUND_REQUEST_CODE:
         if (resultCode == Activity.RESULT_OK) {
            // Sound recorder does not support EXTRA_OUTPUT
            Uri uri = data.getData();
            try {
               String filePath = getAudioFilePathFromUri(uri);
               copyFile(filePath);
               getContentResolver().delete(uri, null, null);  
               (new File(filePath)).delete();
            } catch (IOException e) {
               throw new RuntimeException(e);
            }
         }
      }
   }

   private String getAudioFilePathFromUri(Uri uri) {
      Cursor cursor = getContentResolver()
            .query(uri, null, null, null, null);
      cursor.moveToFirst();
      int index = cursor.getColumnIndex(MediaStore.Audio.AudioColumns.DATA);
      return cursor.getString(index);
   }

   private void copyFile(String fileName) throws IOException {
      Files.copy(new File(fileName), 
         new File(Environment.getExternalStorageDirectory(), fileName));
   }
}

NOTE: com.google.common.io.Files.copy() is from Guava's file copy; feel free to use an alternate implementation or write your own Java file copier.

查看更多
登录 后发表回答