package com.example.recorder;
import java.io.File;
import java.io.IOException;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
private Button startB;
private Button stopB;
private boolean isStarted = false;
private boolean isSDCardExist = false;
private File recorderFolder;
private File recorderFile;
private MediaRecorder mr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 初始化按钮
startB = (Button) findViewById(R.id.button1);
stopB = (Button) findViewById(R.id.button2);
stopB.setEnabled(false);
//为了存于SD卡,先判断是否存在SD卡
isSDCardExist = Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED);
class OnStartListener implements OnClickListener {
@Override
public void onClick(View arg0) {
if (isSDCardExist) {
//Q1
//获取目录
recorderFolder = new File(Environment
.getExternalStorageDirectory().getAbsolutePath()
+"/RecorderTest");
if (!recorderFolder.exists()) {
//不存在则创建
recorderFolder.mkdirs();
}
try {
//创建文件
recorderFile = File.createTempFile("tempRecorder01", ".amr", recorderFolder);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
mr = new MediaRecorder();
//Q2
//初始化录音机
//设置录音来源:此处为麦克风
mr.setAudioSource(MediaRecorder.AudioSource.MIC);
//Q3
//设置压缩音频编码
mr.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
//设置音频解码
mr.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
// FileDescriptor
mr.setOutputFile(recorderFile.getAbsolutePath());
try {
mr.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Q4
mr.start();
isStarted = true;
stopB.setEnabled(true);
}
}
}
class OnStopListener implements OnClickListener {
/* (non-Javadoc)
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
@Override
public void onClick(View arg0) {
if (isStarted) {
//MediaRecorder释放,过程参见API
mr.release();
stopB.setEnabled(false);
isStarted = false;
}
}
}
startB.setOnClickListener(new OnStartListener());
stopB.setOnClickListener(new OnStopListener());
}
}
A TO Q
Q1:创建文件时 用File.pathSeparator,结果在文件创建时提示该目录未被创建成功 原因为此处系统分隔符为“:”;
Q2:对系统设备的调用需要加入权限
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
各种权限!
Q3:录音机初始化过程似乎不能变,注释了setOutputFormat后设置在setAudioEncoder会报错(有待商榷)。
Q4:录音过程开始应该是自动创建新线程,所以录音开始时下面两行代码能继续执行