How can I specify the output file's folder when calling RECORD_SOUND_ACTION?

前端 未结 1 1782
误落风尘
误落风尘 2021-01-24 09:21

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, t

相关标签:
1条回答
  • 2021-01-24 09:23

    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.

    0 讨论(0)
提交回复
热议问题