您的位置:首页 > 其它

2016—04—07 北京

2016-04-07 12:40 316 查看
最近在做OA项目,其中有个功能是想微信语音的功能,这里对以后app的开发中可能会会用到。这里和大家分享,共同进步。

/**

* 录音工具类

*

* @author rendongwei

*

*/

public class RecordUtil {

private static final int SAMPLE_RATE_IN_HZ = 8000;

private MediaRecorder recorder = new MediaRecorder();

// 录音的路径

private String mPath;

public RecordUtil(ImageView view, String path) {

this.view = view;

mPath = path;

}

/**

* 开始录音

*

* @throws IOException

*/

public void start() throws IOException {

if (recorder == null) {

recorder = new MediaRecorder();

}

String state = android.os.Environment.getExternalStorageState();

if (!state.equals(android.os.Environment.MEDIA_MOUNTED)) {

throw new IOException("SD Card is not mounted,It is " + state + ".");

}

File directory = new File(mPath).getParentFile();

if (!directory.exists() && !directory.mkdirs()) {

throw new IOException("Path to file could not be created");

}

recorder.setAudioSource(MediaRecorder.AudioSource.MIC);

recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);

recorder.setOutputFile(mPath);

recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);

// recorder.setAudioSamplingRate(SAMPLE_RATE_IN_HZ);

recorder.prepare();

recorder.start();

updateMicStatus();

}

/**

* 结束录音

*

* @throws IOException

*/

public void stop() throws IOException {

if (recorder == null)

return;

recorder.stop();

recorder.reset();

recorder.release();

recorder = null;

}

/**

* 获取录音时间

*

* @return

*/

public double getAmplitude() {

if (recorder != null) {

return (recorder.getMaxAmplitude());

}

return 0;

}

private int BASE = 600;

private int SPACE = 200;// 间隔取样时间

private ImageView view;

private void updateMicStatus() {

if (recorder != null && view != null && ChatActivity.sendVoice) {

int ratio = recorder.getMaxAmplitude();

int db = 0;// 分贝

if (ratio > 1)

db = (int) (Math.log10(ratio));

LogerUtil.i("guo", "分贝值:" + db + " " + ratio);

switch (db) {

case 1:

view.setImageResource(R.drawable.voice_mic1);

break;

case 2:

view.setImageResource(R.drawable.voice_mic1);

break;

case 3:

view.setImageResource(R.drawable.voice_mic4);

break;

case 4:

view.setImageResource(R.drawable.voice_mic7);

break;

default:

view.setImageResource(R.drawable.voice_mic1);

break;

}

}

mHandler.postDelayed(mUpdateMicStatusTimer, SPACE);

/*

* if (db > 1) { vuSize = (int) (20 * Math.log10(db)); Log.i("mic_",

* "麦克风的音量的大小:" + vuSize); } else Log.i("mic_", "麦克风的音量的大小:" + 0);

*/

}

private final Handler mHandler = new Handler();

private Runnable mUpdateMicStatusTimer = new Runnable() {

public void run() {

updateMicStatus();

}

};

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: