必須在AndroidManifest中設定相應的許可權:android:name="android.permission.RECORD_AUDIO"
1. 首先判定是否存在SD卡,並得到相應的路徑
/* 檢測是否存在SD卡 */
if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
{
/* 得到SD卡得路徑 */
mRecAudioPath = Environment.getExternalStorageDirectory();
/* 更新所有錄音檔案到List中 */
musicList(); }
2. 錄音開始
/* 建立錄音檔案,第一個參數是檔案名稱首碼,第二個參數是尾碼,第三個參數是SD路徑 */
mRecAudioFile = File.createTempFile(strTempFile, ".amr", mRecAudioPath);
/* 執行個體化MediaRecorder對象 */
mMediaRecorder = new MediaRecorder();
/* 設定麥克風 */
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
/* 設定輸出檔案的格式 */
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
/* 設定音頻檔案的編碼 */
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
/* 設定輸出檔案的路徑 */
mMediaRecorder.setOutputFile(mRecAudioFile.getAbsolutePath());
/* 準備 */
mMediaRecorder.prepare();
/* 開始 */
mMediaRecorder.start();
3. 錄音關閉
mMediaRecorder.stop();
4. 播放錄音檔案
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);intent.setAction(android.content.Intent.ACTION_VIEW);/* 設定檔案類型 */intent.setDataAndType(Uri.fromFile(file), "audio");startActivity(intent);
5. 過濾檔案類型,實現FilenameFilter
class MusicFilter implements FilenameFilter{public boolean accept(File dir, String name){return (name.endsWith(".amr"));}
}
代碼下載:/Files/lee0oo0/Examples_07_05.rar