1.部分变量声明
/**
* 采样频率 通用:44100 此处:8000
*/
private static final int SAMPLE_RATE = 8000;
/**
* 录音需要的一些变量
*/
private short[] mBuffer;
private AudioRecord mRecorder;
/**
* 是否转换ok
*/
private boolean convertOk = false;
private int volume=0;
2.初始化AudioRecorder并开始录制.raw文件
int bufferSize = AudioRecord.getMinBufferSize(SAMPLE_RATE,
AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
mBuffer = new short[bufferSize];
mRecorder = new AudioRecord(MediaRecorder.AudioSource.MIC, SAMPLE_RATE,
AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT,
bufferSize);
File file = new File(dir,rawPath);
mCurrentFilePath = file.getAbsolutePath();//raw文件路径
mRecorder.startRecording();
startBufferedWrite(file);
/**
* 写入到raw文件
*
* @param file
*/
private void startBufferedWrite(final File file) {
new Thread(new Runnable() {
@Override
public void run() {
DataOutputStream output = null;
try {
output = new DataOutputStream(new BufferedOutputStream(
new FileOutputStream(file)));
while (isPrepared) {
int readSize = mRecorder.read(mBuffer, 0,
mBuffer.length);
long v = 0;
for (int i = 0; i < readSize; i++) {
output.writeShort(mBuffer[i]);
v += mBuffer[i]*mBuffer[i];
}
double mean = v/(double)readSize;
volume = (int) (10 * Math.log10(mean));
// Log.e("-----音量AudioManger-----", ""+volume);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (output != null) {
try {
output.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}).start();
}
3.停止录音,转换格式
/**
* 停止录音,并且转换文件,<br/>
* <b>这很可能是个耗时操作,建议在后台中做
*
* @return
*/
public boolean stopRecordingAndConvertFile() {
if (!isPrepared) {
return isPrepared;
}
// 停止
mRecorder.stop();
isPrepared = false;
// 开始转换
FLameUtils lameUtils = new FLameUtils(1, SAMPLE_RATE, 16);
convertOk = lameUtils.raw2mp3(mCurrentFilePath, mp3Path);//.raw文件路径,.mp3文件路径
if (convertOk) {//删除源文件
if(mCurrentFilePath != null) {
File file = new File(mCurrentFilePath);
file.delete();
mCurrentFilePath = null;
}
}
return isPrepared ^ convertOk;// convertOk==true,return true
}
注:以上仅为部分重要代码,格式转换时,需要用的第三方flame.jar包。