Android设备实现录制音频的简单demo
转载请注明;
http://blog.csdn.net/u013670933/article/details/26089487
代码例如以下:
public class MainActivity extends Activity { File soundFile;//输出文件
MediaRecorder mRecorder;
@Override
protected 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);
}
//EventOfClick
public 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()){ //避免未用到造成空指针
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
break;
default:
break;
}
}
//释放资源
@Override
protected 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