0

我正在尝试实现用于学习的录音,但我遇到了异常,导致应用程序崩溃,而没有明确的线索如何解决这个问题。这是我的代码

private static final File SDCARD_ROOT = Environment.getExternalStorageDirectory();
private static final String APP_DIR = "test_audio";
private static final String AUDIO_SAMPLE_NAME = "myShake";
...............
...............
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    appDir = new File(SDCARD_ROOT, APP_DIR);
    if (!appDir.exists()) {
        appDir.mkdir();
    }

    recordButton = (Button) findViewById(R.id.audio_button);
    textView = (TextView) findViewById(R.id.edit_text);
    recordButton.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(final View view, final MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                record();
                return true;
            } else if (event.getAction() == MotionEvent.ACTION_UP) {

                return true;
            } else {
                return false;
            }

        }
    });

}

private void record() {
    final File audioSampleFile = new File(appDir, AUDIO_SAMPLE_NAME);
    if (audioSampleFile.exists()) {
        audioSampleFile.delete();
    }

    if (mediaRecorder == null) {
        mediaRecorder = new MediaRecorder();
    }
    mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
    mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    mediaRecorder.setOutputFile(audioSampleFile.getPath());
    mediaRecorder.start();
}

以下是应用程序在电话中崩溃后我得到的异常

03-20 07:08:59.272: ERROR/NotificationService(243): Ignoring notification with icon==0: Notification(contentView=null vibrate=null,sound=nullnull,defaults=0x0,flags=0x62)
03-20 07:09:04.007: ERROR/MediaRecorder(7156): start called in an invalid state: 4
03-20 07:09:04.017: ERROR/AndroidRuntime(7156): FATAL EXCEPTION: main
        java.lang.IllegalStateException
        at android.media.MediaRecorder._start(Native Method)
        at android.media.MediaRecorder.start(MediaRecorder.java:712)
        at com.cs.gang.TestAudio.record(TestAudio.java:78)

其中 TestAudio.java:78 是该行

mediaRecorder.start();

我在其他帖子中搜索过这个问题,但它们似乎并不完全相同。我有权限

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

而且我相信我已经正确地创建了文件来访问 sd-card 那么这个问题或错误的原因是什么?谢谢

4

1 回答 1

1

您需要先打电话mediaRecorder.prepare()再打电话start()

于 2013-03-19T23:42:24.157 回答