Android中用MediaRecorder实现录音

java代码

public class RecordSound extends Activity
implements OnClickListener
{
Button record , stop;
File soundFile ;
MediaRecorder mRecorder;
public void onCreate(Bundle savedInstanceState)
{
	super.onCreate(savedInstanceState);
	setContentView(R.layout.recordsound);
	record = (Button) findViewById(R.id.record);
	stop = (Button) findViewById(R.id.stop);
	stop.setEnabled(false);
	record.setOnClickListener(this);
	stop.setOnClickListener(this);
}

public void onClick(View source)
{
	switch (source.getId())
	{
		case R.id.record:
			if (!Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED))
			{
				Toast.makeText(RecordSound.this
					, "SD卡不存在,请插入SD卡!"
					, 5000)
					.show();
				return;
			}
			try
			{
				Date date=null;
	            SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
	            date =new Date();
	            String str=format.format(date);
	            String fileName =SceneRecord.tempfilestr+"/"+str+".mp3";
				soundFile = new File(fileName);
				mRecorder = new MediaRecorder();
				mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
				mRecorder.setOutputFormat(MediaRecorder
					.OutputFormat.THREE_GPP);
				mRecorder.setAudioEncoder(MediaRecorder
					.AudioEncoder.AMR_NB);
				mRecorder.setOutputFile(soundFile.getAbsolutePath());
				mRecorder.prepare();
				mRecorder.start();
				record.setEnabled(false);
				stop.setEnabled(true);
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
			break;
		case R.id.stop:
			if (soundFile != null && soundFile.exists())
			{
				mRecorder.stop();
				mRecorder.release();
				mRecorder = null;
				record.setEnabled(true);
				stop.setEnabled(false);	
				RecordSound.this.finish();
				Intent intent = new Intent(RecordSound.this,AddAccidentRecord.class);
				startActivity(intent);	
			}
			break;
	}
}
}
布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
	xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center_horizontal"
    >
<Button
	android:id="@+id/record"
	android:layout_width="wrap_content" 
	android:layout_height="wrap_content" 
	android:text="录制"
    />
<Button
    android:id="@+id/stop"
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
   android:text="保存"
    />
</LinearLayout>
权限

<uses-permission android:name="android.permission.RECORD_AUDIO"/>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值