1

MediaStore当我调用内置录音机应用程序时,我想指定一个目标文件夹,例如 sdcard 文件夹。根据Android 文档,不支持EXTRA_OUTPUT调用RECORD_SOUND_ACTION.

我怎样才能做到这一点?

4

1 回答 1

3

您必须允许使用使用的任何默认文件名和位置记录文件,然后移动文件。移动文件绝非易事。这是一个完整的例子。

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));
   }
}

注意:com.google.common.io.Files.copy()来自 Guava 的文件副本;随意使用替代实现或编写自己的 Java 文件复制器。

于 2012-09-06T17:33:58.583 回答