android 录制短音频
有个语音聊天需求,于是写了个工具类用来录制短音频。
该类为单例模式,通过getInstance()获取到实例后调用startRecord开始录制,调用stopRecord停止录制,没有暂停功能.
getAMRFilePath获取文件路径,只会保留最后一次的录音文件,每次开始录制时都会删除上一次的录音文件。
public class AudioRecorderr { private boolean isRecord = false; private int maxDuration = 60 * 1000;//最长录制时间 private int maxSize = 5 * 1024 * 1024;//最大录音大小限制为5M private MediaRecorder mMediaRecorder; private Context mContext; private final String AUDIO_AMR_FILENAME = "temp.amr"; private AudioRecorderr(Context context) { mContext = context; } private static AudioRecorderr mInstance; /** * 获取实例 * @param context * @return */ public synchronized static AudioRecorderr getInstance(Context context) { if (mInstance == null) mInstance = new AudioRecorderr(context); return mInstance; } /** * 开始录制 */ public void startRecord() { if (!isRecord) { isRecord = true; if (mMediaRecorder == null) createMediaRecord(); try { mMediaRecorder.prepare(); mMediaRecorder.start(); } catch (IOException ex) { ex.printStackTrace(); } } } /** * 结束录制 */ public void stopRecord() { close(); } /** * 获取录音文件的大小,单位为KB */ public double getRecordSize() { File mFile = new File(getAMRFilePath()); if (!mFile.exists()) return -1; return mFile.length() / 1024; } private void createMediaRecord() { mMediaRecorder = new MediaRecorder(); /* * 设置音频来源为麦克风 */ mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); /* * 设置最长录制时间 */ mMediaRecorder.setMaxDuration(maxDuration); /* * 设置最大录音文件大小 */ mMediaRecorder.setMaxFileSize(maxSize); /* 设置输出文件的格式:THREE_GPP/MPEG-4/RAW_AMR/Default * THREE_GPP(3gp格式,H263视频/ARM音频编码)、MPEG-4、RAW_AMR(只支持音频且音频编码要求为AMR_NB) */ mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT); /* 设置音频文件的编码:AAC/AMR_NB/AMR_MB/Default */ mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT); /* 设置输出文件的路径 */ File file = new File(getAMRFilePath()); if (file.exists()) { file.delete(); } mMediaRecorder.setOutputFile(getAMRFilePath()); } private void close() { if (mMediaRecorder != null) { isRecord = false; mMediaRecorder.stop(); mMediaRecorder.release(); mMediaRecorder = null; } } /** * 获取AMR格式音频文件地址 * @return */ public String getAMRFilePath() { return mContext.getExternalCacheDir().getAbsolutePath() + "/" + AUDIO_AMR_FILENAME; } }