使用MediaRecorder保存录音

使用MediaRecorder保存录音

点击button弹出一个button按钮,点击开始录音,松开保存。

//这样创建alertdialog.可以在任何地方alertdialog.dismiss
	AlertDialog alertdialog;
	public void onclock(View view){
		switch (view.getId()) {
		case R.id.button1:
			alertdialog=new AlertDialog.Builder(this).create();
			View audiolayout=View.inflate(MainActivity.this, R.layout.recodeaudio, null);
			alertdialog.setView(audiolayout);
			final Button recodebutoon=(Button) audiolayout.findViewById(R.id.button1);
			final TextView recodetext=(TextView) audiolayout.findViewById(R.id.textView1);
			recodebutoon.setOnTouchListener(new OnTouchListener() {
				
				@Override
				public boolean onTouch(View arg0, MotionEvent event) {
					switch (event.getAction()) {
					case MotionEvent.ACTION_DOWN:
						try {
							recodebutoon.setText("松开保存");
							recodetext.setVisibility(View.VISIBLE);
							recodetext.setText("正在录音");
							if(mediarecorder==null){
								try {
									mediarecorder=new MediaRecorder();
									//设置录音来源
									mediarecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
									//设置录音输出的格式
									mediarecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
									//设置录音的编码
									mediarecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
									//设置录音输出的位置
									mediarecorder.setOutputFile(Environment.getExternalStorageDirectory().getAbsolutePath()+"/1.mp3");
									
									mediarecorder.prepare();
									mediarecorder.start();
								} catch (Exception e) {
									e.printStackTrace();
								}
								
								
							}
						} catch (IllegalStateException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						break;
					case MotionEvent.ACTION_MOVE:
						
						break;
						
					case MotionEvent.ACTION_UP:
						if(mediarecorder!=null){
						mediarecorder.stop();
						//mediarecorder释放
						mediarecorder.release();
						//保证mediarecorder是单例的
						mediarecorder=null;
						alertdialog.dismiss();
						}
						break;
					}
					return false;
				}
			});
			alertdialog.show();
	
		}
	}
上边给MediaRecorder设置时,一定不能把顺序弄反,不然会报错的。

下边就要给我们的应用设置权限了。主要有以下两条权限!

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
一个是用来将我们录好的音保存在sdcard中,另一个用来获取录音的权限!


下载Demo地址:

点击打开链接

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值