在android中存储音频文件名时出现IllegalStateException

时间:2013-12-03 10:16:48

标签: android audio-recording

我正在开发一个项目,用户通过点击记录按钮录制音频并通过点击停止按钮停止音频,当用户按下停止按钮,弹出打开要求输入名称时,通过此名称音频将存储在SD卡中。

现在我的问题是当用户按下停止按钮时发生错误,说java.lang.IllegalStateException。

以下是我的活动代码。

public class Record_Audio extends Activity {

private static final String AUDIO_RECORDER_FILE_EXT_3GP = ".3gp";
private static final String AUDIO_RECORDER_FILE_EXT_MP4 = ".mp4";
private static final String AUDIO_RECORDER_FOLDER = "AudioRecorder";

private MediaRecorder recorder = null;
private int currentFormat = 0;
private int output_formats[] = { MediaRecorder.OutputFormat.MPEG_4,
        MediaRecorder.OutputFormat.THREE_GPP };
private String file_exts[] = { AUDIO_RECORDER_FILE_EXT_MP4,
        AUDIO_RECORDER_FILE_EXT_3GP };
Chronometer myChronometer;
Handler seekHandler = new Handler();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.record_audio);

    myChronometer = (Chronometer) findViewById(R.id.chronometer);
    Button buttonStart = (Button) findViewById(R.id.btnStart);

    buttonStart.setOnLongClickListener(new OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            Toast.makeText(Record_Audio.this,
                    "Start Recording With LongClick", Toast.LENGTH_SHORT)
                    .show();
            enableButtons(true);
            startRecording();
            return true;
        }
    });

    setButtonHandlers();
    enableButtons(false);
    setFormatButtonCaption();
}

private void setButtonHandlers() {
    ((Button) findViewById(R.id.btnStart)).setOnClickListener(btnClick);
    ((Button) findViewById(R.id.btnStop)).setOnClickListener(btnClick);
    ((Button) findViewById(R.id.btnFormat)).setOnClickListener(btnClick);
    ((Button) findViewById(R.id.allrecording)).setOnClickListener(btnClick);
}

private void enableButton(int id, boolean isEnable) {
    ((Button) findViewById(id)).setEnabled(isEnable);
}

private void enableButtons(boolean isRecording) {
    enableButton(R.id.btnStart, !isRecording);
    enableButton(R.id.btnFormat, !isRecording);
    enableButton(R.id.btnStop, isRecording);
}

private void setFormatButtonCaption() {
    ((Button) findViewById(R.id.btnFormat))
            .setText(getString(R.string.audio_format) + " ("
                    + file_exts[currentFormat] + ")");
}

private String getFilename() {
    String filepath = Environment.getExternalStorageDirectory().getPath();
    File file = new File(filepath, AUDIO_RECORDER_FOLDER);

    if (!file.exists()) {
        file.mkdirs();
    }
    return (file.getAbsolutePath() + "/" + Code.audioName + file_exts[currentFormat]);
}

private void startRecording() {
    recorder = new MediaRecorder();

    try {
        recorder.prepare();
        recorder.start();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    myChronometer.setBase(SystemClock.elapsedRealtime());
    myChronometer.start();
}

private void stopRecording() {
    if (null != recorder) {
        recorder.stop();
        recorder.reset();
        recorder.release();

    recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    recorder.setOutputFormat(output_formats[currentFormat]);
    recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    recorder.setOutputFile(getFilename());
    recorder.setOnErrorListener(errorListener);
    recorder.setOnInfoListener(infoListener);

        displayAlertDialog();

        recorder = null;
        myChronometer.stop();
    }
}

private void displayFormatDialog() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    String formats[] = { "MPEG 4", "3GPP" };

    builder.setTitle(getString(R.string.choose_format_title))
            .setSingleChoiceItems(formats, currentFormat,
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog,
                                int which) {
                            currentFormat = which;
                            setFormatButtonCaption();

                            dialog.dismiss();
                        }
                    }).show();
}

private void displayAlertDialog() {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(
            Record_Audio.this);

    // Setting Dialog Title
    alertDialog.setTitle("Would you Like to save your Recording");

    // Setting Dialog Message
    alertDialog.setMessage("Enter Audio Name");

    final EditText editTextAudioName = new EditText(Record_Audio.this);
    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT,
            RelativeLayout.LayoutParams.MATCH_PARENT);
    editTextAudioName.setLayoutParams(lp);
    alertDialog.setView(editTextAudioName);

    // Setting Icon to Dialog
    alertDialog.setIcon(R.drawable.save_icon);

    // Setting Positive "Yes" Button
    alertDialog.setPositiveButton("Save",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    // Write your code here to execute after dialog
                    Code.audioName = editTextAudioName.getText().toString().trim();
                }
            });

    // Setting Negative "NO" Button
    alertDialog.setNegativeButton("Cancel",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    // Write your code here to execute after dialog
                    dialog.cancel();
                }
            });
    alertDialog.show();
}

private MediaRecorder.OnErrorListener errorListener = new MediaRecorder.OnErrorListener() {
    @Override
    public void onError(MediaRecorder mr, int what, int extra) {
        Toast.makeText(Record_Audio.this, "Error: " + what + ", " + extra,
                Toast.LENGTH_SHORT).show();
    }
};

private MediaRecorder.OnInfoListener infoListener = new MediaRecorder.OnInfoListener() {
    @Override
    public void onInfo(MediaRecorder mr, int what, int extra) {
        Toast.makeText(Record_Audio.this,
                "Warning: " + what + ", " + extra, Toast.LENGTH_SHORT)
                .show();
    }
};

private View.OnClickListener btnClick = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.btnStart: {
            Toast.makeText(Record_Audio.this, "Start Recording",
                    Toast.LENGTH_SHORT).show();
            enableButtons(true);
            startRecording();
            break;
        }
        case R.id.btnStop: {
            Toast.makeText(Record_Audio.this, "Stop Recording",
                    Toast.LENGTH_SHORT).show();
            enableButtons(false);
            stopRecording();
            // displayFormatDialog();
            break;
        }
        case R.id.btnFormat: {
            displayFormatDialog();
            break;
        }

        case R.id.allrecording: {
            Intent intent = new Intent(Record_Audio.this, PlayAudio.class);
            startActivity(intent);
            break;
        }
        }
    }
};
}

以下是我的logcat

E/AndroidRuntime(14328): FATAL EXCEPTION: main
E/AndroidRuntime(14328): java.lang.IllegalStateException
E/AndroidRuntime(14328):    at android.media.MediaRecorder.stop(Native Method)
E/AndroidRuntime(14328):    at iqualtech.skirr.Record_Audio.stopRecording(Record_Audio.java:113)
E/AndroidRuntime(14328):    at iqualtech.skirr.Record_Audio.access$2(Record_Audio.java:111)
E/AndroidRuntime(14328):    at iqualtech.skirr.Record_Audio$3.onClick(Record_Audio.java:221)
E/AndroidRuntime(14328):    at android.view.View.performClick(View.java:3517)
E/AndroidRuntime(14328):    at android.view.View$PerformClick.run(View.java:14155)
E/AndroidRuntime(14328):    at android.os.Handler.handleCallback(Handler.java:605)
E/AndroidRuntime(14328):    at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime(14328):    at android.os.Looper.loop(Looper.java:154)
E/AndroidRuntime(14328):    at android.app.ActivityThread.main(ActivityThread.java:4624)
E/AndroidRuntime(14328):    at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(14328):    at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(14328):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:809)
E/AndroidRuntime(14328):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
E/AndroidRuntime(14328):    at dalvik.system.NativeStart.main(Native Method)

3 个答案:

答案 0 :(得分:2)

在开始录制之前取文件名,因为它来NULL ...
所以打开你的弹出窗口,点击弹出按钮,开始录制:

recorder = new MediaRecorder(); 
recorder.setAudioSource(MediaRecorder.AudioSource.MIC); 
recorder.setOutputFormat(output_formats[currentFormat]); 
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); 
recorder.setOutputFile(getFilename()); 
recorder.setOnErrorListener(errorListener); 
recorder.setOnInfoListener(infoListener);

答案 1 :(得分:1)

这样做,

private void startRecording() {
    displayAlertDialog();
}

和displayAlertDialog()

private void displayAlertDialog() {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(
            Record_Audio.this);

    alertDialog.setTitle("Would you Like to save your Recording");
    alertDialog.setMessage("Enter Audio Name");
    alertDialog.setIcon(R.drawable.save_icon);

    final EditText editTextAudioName = new EditText(Record_Audio.this);
    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT,
            RelativeLayout.LayoutParams.MATCH_PARENT);

    editTextAudioName.setLayoutParams(lp);
    alertDialog.setView(editTextAudioName);

    alertDialog.setPositiveButton("Save",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                    Code.audioName = editTextAudioName.getText().toString()
                            .trim();

                    recorder = new MediaRecorder();
                    recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                    recorder.setOutputFormat(output_formats[currentFormat]);
                    recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
                    recorder.setOutputFile(getFilename());
                    recorder.setOnErrorListener(errorListener);
                    recorder.setOnInfoListener(infoListener);
                    try {
                        recorder.prepare();
                        recorder.start();
                    } catch (IllegalStateException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    myChronometer.setBase(SystemClock.elapsedRealtime());
                    myChronometer.start();
                }
            });

    alertDialog.setNegativeButton("Cancel",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    // Write your code here to execute after dialog
                    dialog.cancel();
                }
            });
    alertDialog.show();
}

答案 2 :(得分:0)

抛出IllegalStateException,因为当您调用stop()时,recorder不处于启动状态。参考Documentation

  

抛出
   IllegalStateException 如果在start()

之前调用它

将启动播放器所需的所有行从stopRecording方法移至startRecording方法:

private void startRecording() {
    recorder = new MediaRecorder();

//below lines have been added here from stopRecording
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(output_formats[currentFormat]);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(getFilename());
recorder.setOnErrorListener(errorListener);
recorder.setOnInfoListener(infoListener);

异常即将发生,因为未正确跟踪steps mentioned in Documentation

  

- 创建android.media.MediaRecorder的新实例    - 使用MediaRecorder.setAudioSource()设置音频源    - 使用MediaRecorder.setOutputFormat()设置输出文件格式    - 使用MediaRecorder.setOutputFile()设置输出文件名    - 使用MediaRecorder.setAudioEncoder()设置音频编码器    - 在MediaRecorder实例上调用MediaRecorder.prepare()    - 要开始音频捕获,请调用MediaRecorder.start()。