Layout布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:text="录音"
android:textSize="20sp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<LinearLayout
android:layout_width="fill_parent" android:layout_height="wrap_content">
<Button
android:id="@+id/startBtn1"
android:text="开始"
android:layout_weight="1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/stopBtn1"
android:text="停止"
android:enabled="false"
android:layout_weight="1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
<SurfaceView
android:id="@+id/view"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
main文件:
package com.example.coremv;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.app.Activity;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
MediaRecorder recorder1;//录音的
Button startBtn1;
Button stopBtn1;
MediaRecorder recorder2; //录像的
Button startBtn2;
Button stopBtn2;
SurfaceView view;//录像时的预览视图
SurfaceHolder holder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initAudio();
}
void initAudio(){
recorder1 = new MediaRecorder();
startBtn1 =(Button)findViewById(R.id.startBtn1);
stopBtn1 =(Button)findViewById(R.id.stopBtn1);
//音频源是麦克风
recorder1.setAudioSource(MediaRecorder.AudioSource.MIC);//输出格式THREE_GPP
recorder1.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);//编码格式AMR_NB
recorder1.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);//输出文件路径
recorder1.setOutputFile("/sdcard/"
+ new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+".3gp");
startBtn1.setOnClickListener(new OnClickListener(){
@Override
public void onClick (View v){
try {
recorder1.prepare();
recorder1.start();
startBtn1.setEnabled(false);
stopBtn1.setEnabled(true);
}catch (Exception e){
e.printStackTrace();
}
}
});
stopBtn1.setOnClickListener (new OnClickListener() {
@Override
public void onClick (View v){
try{
recorder1.stop();
recorder1.release();
startBtn1.setEnabled(true);
stopBtn1.setEnabled(false);
}catch (Exception e){
e.printStackTrace();
}
}
});
}
}
运行时闪退,模拟器报错 unfortunately ,coreMV has stopped。
使用的开发环境是adt-bundle-windows-x86-20131030,LogCat报错如下: