7

我想使用 MediaRecorder 录制语音,我的代码是:

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

或者

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

在三星上一切正常,但在戴尔上两种方法都不成功

这是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
4

6 回答 6

2

这是一个大问题,但有一个非常小的解决方案

在大多数情况下,我们从 this.file.getAbsolutePath() 获得的文件名包含 file:/// 作为前缀

    ////////////////////////////////////////////////* 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:/// */

希望你觉得这个答案有帮助

于 2014-03-17T07:18:36.143 回答
2

首先,您的代码看起来不错。您是否在清单文件中添加了所需的权限?

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

如果是,则尝试替换:

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

经过

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

不要忘记检查您的视频文件的路径是否正确。

于 2013-02-01T06:45:42.310 回答
1

我删除了

this.mediaRecorder.setAudioEncodingBitRate(16);

在方法2,现在它正在工作。

于 2013-02-01T11:35:36.540 回答
1

将引发此异常。如果以下任何事情失败:

找不到文件:确保您指定的输出文件位置存在,否则会抛出文件未找到异常

写入权限:您必须在清单文件中指定写入权限。

记录权限:在清单文件中指定记录权限。

你可以用这个..

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

你仍然得到错误..尝试显示错误。像这样

try{
        mRecorder.prepare();

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

mRecorder.start();

于 2016-10-27T04:31:04.577 回答
0

对于定位版本 >= 10+ 的设备,您需要使用MediaStore api,在我的情况下找不到文件,因为该文件超出了我的应用程序的范围存储。

于 2020-04-14T22:53:09.043 回答
0

实际上,iam 在我的应用程序构建时也遇到了同样的问题,我得到了一个完美的解决方案是我们应该设置所有权限,如 RECORD_AUDIO、READ_EXTERNAL_STORAGE、WRITE_EXTERNAL_STORAGE,我们应该设置这些权限 AndroidManifest.xml 和运行时也。我只是粘贴我的代码下面,它的kotlin代码和运行成功

    //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
            }
        }
}
于 2020-06-12T08:46:05.613 回答