我怎样才能调用RECORD_SOUND_ACTION时指定输出文件的文件夹?(How can I s

2019-07-31 10:04发布

我想指定目标文件夹时,我称之为MediaStore内置录音机应用程序,如SD卡文件夹。 按照Android文档 ,不存在用于支持EXTRA_OUTPUT调用时RECORD_SOUND_ACTION

我怎样才能做到这一点?

Answer 1:

你必须允许使用任何默认的文件名和位置使用,然后将文件中记录的文件。 移动文件是远离琐碎。 这里有一个完整的例子。

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()为番石榴的文件复印件; 随意使用替代实现或写自己的Java文件复印机。



文章来源: How can I specify the output file's folder when calling RECORD_SOUND_ACTION?