Android音频录制错误

时间:2013-03-19 23:30:36

标签: android android-audiorecord

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

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

以下是应用程序在Phone

中崩溃后得到的异常
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卡,那么这个问题或错误的原因是什么?感谢

1 个答案:

答案 0 :(得分:1)

您需要在致电mediaRecorder.prepare()

之前致电start()