实现录音的代码如下
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.media.MediaRecorder;
import android.util.Log;
public class RecordUtil {
MediaRecorder mediaRecorder = new MediaRecorder();
private String DIRECTORY = "/sdcard/recordfiles";
File dir;
public RecordUtil() {
// 设置声音来源
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
// 设置文件的输出格式
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
// 设置编码方式
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
dir = new File(DIRECTORY);
if(!dir.exists()){
//文件夹如果不存在,新建文件夹
dir.mkdir();
}
}
public void startRecord(int recordTime){
if(dir.exists()&&dir.canWrite()){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
Date curdate = new Date(System.currentTimeMillis());//获取当前时间
String fileName = dir.getAbsolutePath()+"/"+simpleDateFormat.format(curdate)+".amr";
File file = new File(fileName);
try {
file.createNewFile();
if(file.exists()&&file.canWrite()){
mediaRecorder.setOutputFile(fileName);//设置输出文件
mediaRecorder.setMaxDuration(recordTime*1000);//设置录音时间
mediaRecorder.prepare();//准备录音
mediaRecorder.start();//开始录音
}else{
Log.i("zhiyinqing","文件不存在或文件不能被读写");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
Log.i("zhiyinqing","文件夹不存在或不能读写");
}
}
}