標籤:android des style blog http java 使用 os
Android裝置實現錄製音訊簡單demo
轉載請註明;
http://blog.csdn.net/u013670933/article/details/26089487
代碼例如以下:
public class MainActivity extends Activity {File soundFile;//輸出檔案MediaRecorder mRecorder;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main); inintView();//初始化}//初始化private void inintView() {mRecorder = new MediaRecorder();//設定音頻來源mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);//設定聲音輸出格式----一定要在編碼格式之前設定mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);//設定聲音的編碼格式mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);}//EventOfClickpublic void onClick(View view){switch(view.getId()){case R.id.record:try{//設定儲存音樂的檔案soundFile = new File(Environment.getExternalStorageDirectory().getCanonicalFile()+"/sound.amr");mRecorder.setOutputFile(soundFile.getAbsolutePath());mRecorder.prepare();//開始mRecorder.start();}catch(Exception e){e.printStackTrace();}break;case R.id.stop:if(soundFile!=null && soundFile.exists()){ //避免未用到造成null 指標mRecorder.stop();mRecorder.release();mRecorder = null;}break;default:break;}}//釋放資源@Overrideprotected void onDestroy() {if(soundFile!=null && soundFile.exists()){mRecorder.stop();mRecorder.release();mRecorder = null;}super.onDestroy();}}
布局檔案僅有兩個button,在此略過。
使用權限設定:
<uses-permission android:name="android.permission.RECORD_AUDIO"/><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Demo示範範例代碼:
http://download.csdn.net/detail/u013670933/7362171