将音频文件存储在 SdCard 中

store Audio files in SdCard

这是我的通话录音应用程序代码,将音频文件存储在内部存储器中,但我想将音频文件存储在外部存储器中。我将更改的内容和文件存储在 Sdcard

我正在制作将音频文件存储在存储器中的录音应用程序

 public void recordVoiceCall(String phNumber, String name, String type) {

    File LastingSalesRecordingsDir = new File(Environment.getExternalStorageDirectory(),
            audioFileDirectoryPath);


    if (!LastingSalesRecordingsDir.exists()) {
        LastingSalesRecordingsDir.mkdirs();
    }

    file_name = "call_" + MyDateTimeStamp.getCurrentDate() + "_" +
            MyDateTimeStamp.getCurrentTimeForFile() + "_" + type + "_" + phNumber + "_";
    try {
        audioFile = File.createTempFile(file_name, ".mp3", LastingSalesRecordingsDir);
    } catch (IOException e) {
        Log.d(MyLogTags.recording, "Recording IOException: " + e.getMessage());
        e.printStackTrace();
    }
    String path = Environment.getExternalStorageDirectory().getAbsolutePath();
    try {
        file_name = audioFile.getName();

        if (recorder == null) {
            recorder = new MediaRecorder();
            recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION);

            recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            recorder.setOutputFile(audioFile.getAbsolutePath());

            Log.d(MyLogTags.recording, "Recording output formats set.");
        }
    } catch (Exception e) {
        Log.d(MyLogTags.recording, "Recording Exception: " + e);
    }
    try {

        recorder.prepare();
        Log.d(MyLogTags.recording, "Recording Recorder prepared.");
    } catch (IllegalStateException e) {
        deleteVoiceFile(file_name);
        Log.d(MyLogTags.recording, "Recording prepare IllegalStateException: " + e);
    } catch (IOException e) {
        deleteVoiceFile(file_name);
        Log.d(MyLogTags.recording, "Recording prepare IOException: " + e);
    }

    try {
        String state = Environment.getExternalStorageState();
        if (!state.equals(Environment.MEDIA_MOUNTED)) {
            Log.d(MyLogTags.recording, "SD Card is not mounted.  It is " + state + ".");
            throw new IOException("SD Card is not mounted.  It is " + state + ".");
        }

        recorder.start();
        Log.d(MyLogTags.recording, "Recording Recorder started for: " + phNumber);
        recordStarted = true;
    } catch (Throwable e) {
        deleteVoiceFile(file_name);
        Log.d(MyLogTags.recording, "Recording start Exception: " + e);
    }
}

您可以使用Android的默认外部存储目录来保存您的音频文件。

File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_MUSIC);

您也可以使用文件Class构造函数在SD卡上新建一个文件夹。

File audioFolder = new File(Environment.getExternalStorageDirectory(), 
"newaudiofolder")
  if (!audioFolder.exists()) {
boolean success = audioFolder.mkdir()
if (success) {
    // save the file 
}
}

确保在Manifest.xml

中添加权限
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>