Search code examples
javaandroidioexceptionmediarecorderandroid-mediarecorder

MediaRecorder.prepare() throwing IOException


I have an IOException caused by MediaRecorder.prepare(), and I have found no solution for it, even after searching in multiple places. I have used the code in the official Android Developers guide for this. My code is the following:

private void startRecording(String fileName) {
    mRecorder = new MediaRecorder();
    mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
    mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    mRecorder.setOutputFile(fileName);

    try {
        mRecorder.prepare();
    } catch (IOException e) {
        Log.e("RecordApp", "prepare() failed " + fileName);
    }

    mRecorder.start();
}

I know for a fact that the filename string is not null, as it is controlled by an EditText which I know is working properly for sure.

Just to clarify what the string filename is. Since I plan to have this data on internal storage, I just have the plain name (say I want the file to be "test"), which in this case would be the string "test". I don't know if that would be an issue or not, however.

Any help is appreciated. Thank you.

EDIT 1: A new issue arising (look at the first comment at @Burrough 's post).

private void stopRecording(){
        if(recorder != null){
            recorder.stop();
        }
    }

// stopRecording name of the button.
stopRecording.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                thread.interrupt();
                onorig=false;
                thread = null;
                startRecording.setEnabled(true);
                stopRecording.setEnabled(false);
                try {
                    Log.i("DOG", processCode(originalcode));
                    Log.i("DOG", processCode(code));
                    Log.i("DOG", Arrays.toString(checkNotes(originalcode, code)));
                } catch(NullPointerException npe){}
                code = "";
                stopRecording();
                Calendar calendar = Calendar.getInstance();
            }
        });

I am using TarsosDSP pitch recognition.


Solution

  • Your filename is causing the error. Replace this:

    mRecorder.setOutputFile(fileName);
    

    With something like this:

    final File outputFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC), fileName);
    
    mRecorder.setOutputFile(outputFile.getAbsolutePath());