android mediaRecorder.setAudioSource failed

2019-01-07 17:15发布

I have android G1 firmware 1.6, I am trying to record voice from the app with the follow code.

MediaRecorder recorder = new MediaRecorder();
 recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
 recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
 recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
 recorder.setOutputFile(PATH_NAME);
 recorder.prepare();
 recorder.start();  

my manifest.xml has:

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

I got:

09-23 14:41:05.531: ERROR/AndroidRuntime(1718): Uncaught handler: thread main exiting due to uncaught exception
09-23 14:41:05.551: ERROR/AndroidRuntime(1718): java.lang.RuntimeException: setAudioSource failed.
09-23 14:41:05.551: ERROR/AndroidRuntime(1718):     at android.media.MediaRecorder.setAudioSource(Native Method)

how do I record voice properly?

15条回答
Ridiculous、
2楼-- · 2019-01-07 18:19

This code worked for me

 mRecorder = new MediaRecorder();
 mRecorder.reset();
 mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
查看更多
小情绪 Triste *
3楼-- · 2019-01-07 18:19

I moved it to another thread. Everything works.

Here's a code:

new Thread(() -> {
    mediaRecorder.reset();
    mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
    mediaRecorder.setOutputFile("/audiorecordtest.3gp");
    mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        try {
            mediaRecorder.prepare();
            mediaRecorder.start();
            //do something here
            mediaRecorder.stop();
        } catch (IOException e) {
            e.printStackTrace();
            Log.d("Audio","unable to prepare");
        }

}).start();
查看更多
Melony?
4楼-- · 2019-01-07 18:20

For API 23+, check audio record permission in both Manifest.xml <uses-permission android:name="android.permission.RECORD_AUDIO" /> and in Java Code

if (ActivityCompat.checkSelfPermission(cnt, Manifest.permission.RECORD_AUDIO)
            != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(cnt, arrayOf(
                Manifest.permission.RECORD_AUDIO
        ),0)
        return
    }
查看更多
登录 后发表回答