/**
* author:${dbf}
* Date:2019/6/6
* Description:
*/
public class MyAudioRecord {
private String TAG = "MyAudioRecord";
private MediaRecorder mr;
private boolean isStart = false;
private Handler handler;
private long startTime;
private String voicePathName;
public MyAudioRecord(Handler handler) {
this.handler = handler;
}
}
public void startRecord() {
if (isStart) {
Log.d(TAG, "正在录制");
return;
}
isStart = true;
Log.d(TAG, "开始录制");
if (mr == null) {
File dir = new File(Environment.getExternalStorageDirectory(), "Avoicassistant");
if (!dir.exists()) {
dir.mkdirs();
}
File soundFile = new File(dir, System.currentTimeMillis() + ".amr");
voicePathName = soundFile.getPath();
Log.d(TAG, voicePathName);
if (!soundFile.exists()) {
try {
soundFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
mr = new MediaRecorder();
mr.setAudioSource(MediaRecorder.AudioSource.MIC); //音频输入源
mr.setOutputFormat(MediaRecorder.OutputFormat.AMR_WB); //设置输出格式
mr.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_WB); //设置编码格式
mr.setAudioSamplingRate(16);
mr.setOutputFile(soundFile.getAbsolutePath());
new Thread() {
@Override
public void run() {
super.run();
try {
mr.prepare();
mr.start(); //开始录制
startTime = System.currentTimeMillis();
updateMicStatus();
} catch (IOException e) {
e.printStackTrace();java
}
}
}.start();
}
}
//停止录制,资源释放
private void stopRecord() {
if (mr != null) {
Log.d(TAG, "录制完成");
mr.stop();
mr.release();
mr = null;
isStart = false;
}
}
private void updateMicStatus() {
long ctime = System.currentTimeMillis();
if (ctime - startTime >= 5000) {
stopRecord();
Message message = Message.obtain(handler);
message.what = 1;
message.obj = voicePathName;
handler.sendMessage(message);
return;
}
if (mr != null) {
int ratio = mr.getMaxAmplitude() / 600;
int db = 0;// 分贝
if (ratio > 1)
db = (int) (20 * Math.log10(ratio));
System.out.println("分贝值:" + db + " " + Math.log10(ratio));
if (handler != null) {
//我对着手机说话声音最大的时候,db达到了35左右,
handler.postDelayed(mUpdateMicStatusTimer, 200);
Message message = Message.obtain(handler);
message.what = 0;
message.arg1 = db / 2;
//所以除了2,为的就是对应14张图片
handler.sendMessage(message);
}
}
}
private Runnable mUpdateMicStatusTimer = new Runnable() {
public void run() {
updateMicStatus();
}
};