MediaRecorder IOException: prepare failed
Asked Answered
B

7

8

I want to use MediaRecorder to record voice, my code is:

 public void record(View v) {
       Log.d(TAG, "record");

    this.mediaRecorder.setAudioChannels(1);
    this.mediaRecorder.setAudioSamplingRate(44100);
    this.mediaRecorder.setAudioEncodingBitRate(64000);
    this.mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    this.mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
    this.mediaRecorder.setOutputFile(this.file.getAbsolutePath());
    this.mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
    try {
        this.mediaRecorder.prepare();
        this.mediaRecorder.start();

        // update the buttons
        this.setButtonsEnabled(false, true, false);
    } catch (IOException e) {
        Log.e(TAG, "Failed to record()", e);
    }
}

Or

   public void record(View v) {
    Log.d(TAG, "record");
    this.mediaRecorder = new MediaRecorder();
    this.mediaRecorder.setAudioChannels(1);
    this.mediaRecorder.setAudioSamplingRate(8000);

    this.mediaRecorder.setAudioEncodingBitRate(16);
    this.mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    this.mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
    this.mediaRecorder.setOutputFile(this.file.getAbsolutePath());

    this.mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

    try {
        this.mediaRecorder.prepare();
        this.mediaRecorder.start();

        // update the buttons
        this.setButtonsEnabled(false, true, false);
    } catch (IOException e) {
        Log.e(TAG, "Failed to record()", e);
    }
}

On a Samsung all is OK, but on a Dell two methods do not succeed

Here is logcat:

 02-01 13:56:51.094: E/AudioRecorderDemoActivity(1397): Failed to record()
 02-01 13:56:51.094: E/AudioRecorderDemoActivity(1397): java.io.IOException: prepare failed.
 02-01 13:56:51.094: E/AudioRecorderDemoActivity(1397):     at android.media.MediaRecorder._prepare(Native Method)
 02-01 13:56:51.094: E/AudioRecorderDemoActivity(1397):     at android.media.MediaRecorder.prepare(MediaRecorder.java:524)
 02-01 13:56:51.094: E/AudioRecorderDemoActivity(1397):     at com.marakana.android.audiorecorderdemo.AudioRecorderDemoActivity.record(AudioRecorderDemoActivity.java:69)
 02-01 14:05:20.074: E/AndroidRuntime(1790): FATAL EXCEPTION: main
 02-01 14:05:20.074: E/AndroidRuntime(1790): java.lang.IllegalStateException: Could not execute method of the activity
Bolen answered 1/2, 2013 at 6:8 Comment(0)
I
2

First at all you code looks fine. Have you added the required permissions to your manifest file?

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />

If yes, then try replacing:

this.mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);

by

this.mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);

Don't forget to check if the path of your video file is correct.

Integrated answered 1/2, 2013 at 6:45 Comment(0)
B
1

I deleted

this.mediaRecorder.setAudioEncodingBitRate(16);

at method 2 and now it's working.

Bolen answered 1/2, 2013 at 11:35 Comment(0)
W
1

This is a big problem but has a very small solution

In most cases, the filename that we get from this.file.getAbsolutePath() contains file:/// as a prefix

    ////////////////////////////////////////////////* INCORRECT CODE */
    this.mediaRecorder.setOutputFile(this.file.getAbsolutePath());
    /*the above line sets a file url beginning with a "file:///"
    //however, since this setOutputFile requires us to send a
    //string referring to the uri, we will have to get rid of the
    //"file:///" and simply write the uri */
    ////////////////////////////////////////////////* CORRECTED CODE BELOW */
    this.mediaRecorder.setOutputFile(this.file.getAbsolutePath().substring(8));
    /*the above line of code extracts the string uri eliminating
    // file:/// */

Hope you find this answer helpful

Wording answered 17/3, 2014 at 7:18 Comment(0)
D
1

This Exception will be raised . if any of the following things failed:

file not found: Ensure that output file location that yu have specified is existing, otherwise it will throw you filenotfoundexception

Write Permission: You must specify Write permission in your manifest file.

Record permission : specify Record permission in your manifest file.

you can use this..

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>

Still you get error.. try display the error. Like this

try{
        mRecorder.prepare();

    } catch (IOException e) {
        Log.e(LOG_TAG, "prepare() failed");
       System.out.println(""+e);    //to display the error
    }

mRecorder.start();

Doubletongued answered 27/10, 2016 at 4:31 Comment(0)
V
0

For devices targeting version >= 10+ , you need to use MediaStore api, in my case file could not be found because the file is out of my app's scoped storage.

Vincenza answered 14/4, 2020 at 22:53 Comment(3)
Hi @Mehmet Did you have a example, in my case i am receiving always E/MediaRecorder: prepare failed: -2147483648 in some phones with Android 10Ahoufe
Due to scoped storage , you need to either do as how google suggests or for now you can choose to define android:requestLegacyExternalStorage=”true” in your manifest file. However this won't survive Android 11 they say. So I havent used MediaStore api yet, but I'll need to move using it soon.Vincenza
Any real examples ????????? Cuz this answer says literally nothing.Uneventful
E
0

Actually iam also faced the same problem in my application building time, and i got a perfect solution is that we should set all permissions like RECORD_AUDIO,READ_EXTERNAL_STORAGE,WRITE_EXTERNAL_STORAGE, we should set these permissions AndroidManifest.xml and runtime also.i just pasting my code below, its kotlin code and running success

    //Here when the app opening time 
    <!--MainActivity-->

    class MainActivity: AppCompatActivity() {

        companion object{
            var permissionAccepted = false
            var permissions = arrayOf(android.Manifest.permission.RECORD_AUDIO,
                android.Manifest.permission.READ_EXTERNAL_STORAGE,
                android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
        }


        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)

            ActivityCompat.requestPermissions(this, permissions,CODE_PERMISSIONS)

            setContentView(R.layout.activity_main)
        }

        @RequiresApi(Build.VERSION_CODES.M)
        override fun onRequestPermissionsResult(
            requestCode: Int,
            permissions: Array<out String>,
            grantResults: IntArray
        ) {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults)
            when (requestCode) {
                REQUEST_CODE_PERMISSIONS -> {
                    permissionAccepted = grantResults[0]
                                                == PackageManager.PERMISSION_GRANTED                                     
                            && grantResults [1] == PackageManager.PERMISSION_GRANTED
                            && grantResults[2] == PackageManager.PERMISSION_GRANTED
                }
            }
            if (!permissionAccepted){
                requestPermissions(permissions, REQUEST_CODE_PERMISSIONS)
            }
        }


    }

    <!--VoiceRecordActivity-->

    class VoiceRecordActivity: AppCompatActivity() {

        private var mediaRecorder: MediaRecorder? = null

        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_voice_record)

            //i used touch listner
            audio_message_send.setOnTouchListener{ v, event ->
                    if (permissionAccepted)
                    {
                        //Log.e("TAG","permission accepted:$permissionAccepted")
                        if (event.action == MotionEvent.ACTION_DOWN) {
                            startRecording()

                        }
                        if (event.action == MotionEvent.ACTION_UP) {
                            stopRecording()
                        }
                    }else{
                        //Log.e("TAG","permission accepted:$permissionAccepted")
                        requestPermissions(permissions, REQUEST_CODE_PERMISSIONS)
                    }
                    false
                }
        }

            private fun startRecording() {
                       mFile = Environment.getExternalStorageDirectory().absolutePath                       
                    +"/$formattedDate-FC00$random.aac"
                if (mediaRecorder == null){
                this.mediaRecorder = MediaRecorder().apply {
                    setOutputFile(mFile)
                    setAudioSource(MediaRecorder.AudioSource.MIC)
                    setAudioChannels(1)
                    setOutputFormat(MediaRecorder.OutputFormat.AAC_ADTS)
                    setAudioEncoder(MediaRecorder.AudioEncoder.AAC)

                    //Log.e("TAG", "mFIle: $mFile")

                    try {
                        this.prepare()
                        this.start()

                    } catch (e: IOException) {
                        e.printStackTrace()
                        Log.e("TAG", "error: Prepare() failed")
                    } catch (e: InterruptedException) {
                        e.printStackTrace()
                    } catch (e: InterruptedException) {
                        e.printStackTrace()
                    }
                }
            }else{
                this.mediaRecorder!!.prepare()
                this.mediaRecorder!!.start()
            }
        }

    private fun stopRecording() {
        mediaRecorder!!.apply {
            try {
                stop()
                release()
            }catch (e: IOException){
                Log.e("TAG","error: stop${e.printStackTrace()}")
            }
            mediaRecorder = null
        }
    }

    override fun onStop() {
            super.onStop()
            if(mediaRecorder != null) {
                mediaRecorder!!.release()
                mediaRecorder = null
            }
        }
}
Elsaelsbeth answered 12/6, 2020 at 8:46 Comment(0)
M
0

try replace that line

this.mediaRecorder.setOutputFile(this.file.getAbsolutePath());

to

private static String mFileName = null;
mFileName = getExternalCacheDir().getAbsolutePath();
mFileName += "/audiorecordtest.3gp";
this.mediaRecorder.setOutputFile(fileName);
Mosenthal answered 24/6, 2022 at 22:26 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.