最近在項目中實現(xiàn)錄音功能式撼,并在邏輯中還有對錄音文件的特殊要求踢匣,前前后后看了很多資料告匠,學(xué)習了很多,今天在這里分享記錄一下离唬,以便后期回看后专。
Android提供了兩個API用于錄音的實現(xiàn):MediaRecorder 和AudioRecord。
MediaRecorder:錄制的音頻文件是經(jīng)過壓縮后的男娄,需要設(shè)置編碼器行贪。并且錄制的音頻文件可以用系統(tǒng)自帶的Music播放器播放。MediaRecorder已經(jīng)集成了錄音模闲、編碼建瘫、壓縮等,并支持少量的錄音音頻格式尸折,但是這也是他的缺點啰脚,支持的格式過少并且無法實時處理音頻數(shù)據(jù)。
AudioRecord:主要實現(xiàn)對音頻實時處理以及邊錄邊播功能实夹,相對MediaRecorder比較專業(yè)橄浓,輸出是PCM語音數(shù)據(jù),如果保存成音頻文件亮航,是不能夠被播放器播放的荸实,所以必須先寫代碼實現(xiàn)數(shù)據(jù)編碼以及壓縮。
MediaRecorder
MediaRecorder因為已經(jīng)集成了錄音缴淋、編碼准给、壓縮等功能,所以使用起來相對比較簡單重抖。
開始錄音
MediaRecorder 使用起來相對簡單露氮,音頻編碼可以根據(jù)自己實際需要自己設(shè)定,文件名防止重復(fù)钟沛,使用了日期_時分秒的結(jié)構(gòu)畔规,audioSaveDir 是文件存儲目錄,可自行設(shè)定恨统。下面貼出示例代碼:
public void startRecord() {
// 開始錄音
/* ①Initial:實例化MediaRecorder對象 */
if (mMediaRecorder == null)
mMediaRecorder = new MediaRecorder();
try {
/* ②setAudioSource/setVedioSource */
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);// 設(shè)置麥克風
/*
* ②設(shè)置輸出文件的格式:THREE_GPP/MPEG-4/RAW_AMR/Default THREE_GPP(3gp格式
* 叁扫,H263視頻/ARM音頻編碼)、MPEG-4延欠、RAW_AMR(只支持音頻且音頻編碼要求為AMR_NB)
*/
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
/* ②設(shè)置音頻文件的編碼:AAC/AMR_NB/AMR_MB/Default 聲音的(波形)的采樣 */
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
fileName = DateFormat.format("yyyyMMdd_HHmmss", Calendar.getInstance(Locale.CHINA)) + ".m4a";
if (!FileUtils.isFolderExist(FileUtils.getFolderName(audioSaveDir))) {
FileUtils.makeFolders(audioSaveDir);
}
filePath = audioSaveDir + fileName;
/* ③準備 */
mMediaRecorder.setOutputFile(filePath);
mMediaRecorder.prepare();
/* ④開始 */
mMediaRecorder.start();
} catch (IllegalStateException e) {
LogUtil.i("call startAmr(File mRecAudioFile) failed!" + e.getMessage());
} catch (IOException e) {
LogUtil.i("call startAmr(File mRecAudioFile) failed!" + e.getMessage());
}
}
上面代碼只是基本使用方式陌兑,具體使用還需結(jié)合項目具體需求制定具體邏輯,但是MediaRecorder使用時需實例化由捎,所以在不用時一定要記得即時釋放兔综,以免造成內(nèi)存泄漏。
結(jié)束錄音
public void stopRecord() {
try {
mMediaRecorder.stop();
mMediaRecorder.release();
mMediaRecorder = null;
filePath = "";
} catch (RuntimeException e) {
LogUtil.e(e.toString());
mMediaRecorder.reset();
mMediaRecorder.release();
mMediaRecorder = null;
File file = new File(filePath);
if (file.exists())
file.delete();
filePath = "";
}
}
總結(jié):MediaRecorder 實現(xiàn)錄音還是比較簡單的,代碼量相對較少软驰,較為簡明涧窒,但也有不足之處,例如輸出文件格式選擇較少锭亏,錄音過程不能暫停等纠吴。
下一篇文章介紹了使用 AudioRecorder 實現(xiàn)錄音功能 Android錄音實現(xiàn)(AudioRecorder)