调用RECORD_SOUND_ACTION时,如何指定输出文件的文件夹?

时间:2012-09-06 17:33:59

标签: android audio uri audio-recording mediastore

我想在调用MediaStore内置录音机应用程序时指定目标文件夹,例如sdcard文件夹。根据{{​​3}},调用RECORD_SOUND_ACTION时不支持Android documentation

我该怎么做?

1 个答案:

答案 0 :(得分: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文件复制程序。