布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:gravity="center"
android:orientation="vertical" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/start" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="00:00"
android:textSize="20dp" />
</LinearLayout>
</LinearLayout>
public class MainActivity extends Activity implements OnClickListener {
private ImageView imageView;
private TextView textView;
private boolean flag;
private Timer timer;
private MediaRecorder recorder;
private String timesString = null;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView1);
textView = (TextView) findViewById(R.id.textView1);
imageView.setOnClickListener(MainActivity.this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.imageView1:
if (flag) {// 停止录音
imageView.setImageResource(R.drawable.start);
textView.setText(timesString);
timer.cancel();
if (recorder != null) {
recorder.stop();
recorder.release();
recorder = null;
}
} else {// 开始录音
// 获取一个MediaRecorder对象
recorder = new MediaRecorder();
// 设置音频的来源(来自于麦克风)
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
// 设置音频的格式
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
// 设置音频的编码格式
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
// 设置音频的存放位置
recorder.setOutputFile("sdcard/yunsongvideo.3gp");
// 准备录音
try {
recorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 开始录音
recorder.start();
imageView.setImageResource(R.drawable.stop);
// 文本框的时间显示
final int i = 0;
timer = new Timer();
timer.schedule(new TimerTask() {
int countTime = i;
public void run() {
runOnUiThread(new Runnable() {
public void run() {
countTime++;
//String timesString = null;// 在textview上面显示的时间
int m = countTime / 60;// 分钟
int s = countTime % 60;// 秒
if (m < 10) {
timesString = "0" + m + ":";
} else {
timesString = m + ":";
}
if (s < 10) {
timesString = timesString + "0" + s;
} else {
timesString = timesString + s;
}
textView.setText(timesString);
}
});
}
}, 1, 100);
}
flag = !flag;
break;
}
}
}