MediaRecorder IOException: prepare failed

后端 未结 6 417
北恋
北恋 2021-01-18 08:11

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

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

    this.mediaRecorder.setAudioChannel         


        
相关标签:
6条回答
  • 2021-01-18 08:44

    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.

    0 讨论(0)
  • 2021-01-18 08:44

    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

    0 讨论(0)
  • 2021-01-18 08:54

    I deleted

    this.mediaRecorder.setAudioEncodingBitRate(16);

    at method 2 and now it's working.

    0 讨论(0)
  • 2021-01-18 08:54

    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
                }
            }
    }
    
    0 讨论(0)
  • 2021-01-18 09:00

    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();

    0 讨论(0)
  • 2021-01-18 09:04

    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.

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