MediaRecorder.prepare()异常 - 没有这样的文件或目录

时间:2014-07-25 08:10:39

标签: android exception audio record

我试图录制音频,当调试到达.prepare()

时会出现一个狂野的异常

这是我的Record()方法。

private void Grabar(View v) {
    mediaRecorder = new MediaRecorder();
    Date today = Calendar.getInstance().getTime(); 
    String nombrefichero =  String.valueOf(today.getDate()) + "-"
            + String.valueOf(today.getMonth() + 1) + "-"
            + String.valueOf(today.getYear() + 1900) + "_"
            + String.valueOf(today.getHours()) + "."
            + String.valueOf(today.getMinutes())+"."+String.valueOf(today.getSeconds()) +".3gp";

    mediaRecorder.setOutputFile(VarGlobales.Ruta+"/"+VarGlobales.Trabajo+"/Audio/"+nombrefichero);
    // VarGlobales.Ruta -> Environment.getExternalStorageDirectory().getAbsolutePath();
    // VarGlobales.Trabajo -> 001
    mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
    mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

    try {
        mediaRecorder.prepare();
        mediaRecorder.start();
        Toast.makeText(contexto, "Grabando...", Toast.LENGTH_SHORT).show();
    } catch (IOException e)
    {
        Toast.makeText(contexto, "Fallo en la grabación", Toast.LENGTH_SHORT).show();
    }       
}

AndroidManifest.xml具有RECORD_AUDIOWRITE_EXTERNAL_STORAGE权限。

例外说:

java.io.FileNotFoundException: /storage/sdcard0/001/Audio/25-7-2014_8.53.6.3gp:
open failed: ENOENT (No such file or directory)

异常表示该文件不存在。不要以为我现在正在创造它吗?

我做错了什么?

1 个答案:

答案 0 :(得分:10)

请阅读文档。它表示应在 mediaRecorder.setOutputFile() 之后和 setOutputFormat() 之前调用 prepare()

//在sdcard中创建目录:

String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyFolder/";
File dir = new File(path);
if(!dir.exists())
dir.mkdirs();
String myfile = path + "filename" + ".mp4";

然后将其指定为输出文件。

setOutputFile(myfile);