您的位置:首页 > 移动开发 > Android开发

Android 录音组件MediaRecorder的使用 提供完整源码

2012-07-31 21:34 513 查看


Android 录音组件MediaRecorder的使用 提供完整源码

MediaRecorder可以很方便的拍照、录像、录音,本文只介绍录音的使用方法。虽然录音时声源可以选择通话,但是在真机上运行不行,不知如何解决,我机上(i897 lidroid 2.2 Rom)的录音通话软件很好用,所以说理论上还有有方法实现的,毕竟已经有人实现了。下面上代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button android:id="@+id/start"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="开始录音"
/>
<Button android:id="@+id/stop"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="停止"
/>
</LinearLayout>

两个按钮,一个开始,一个停止。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
1718
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59

package com.pocketdigi;

import android.app.Activity;
import android.media.MediaRecorder;
import android.media.MediaRecorder.AudioSource;
import android.media.MediaRecorder.OutputFormat;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MediaRecorderActivity extends Activity {
Button start,stop;
MediaRecorder mr;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
start=(Button)findViewById(R.id.start);
stop=(Button)findViewById(R.id.stop);

start.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mr=new MediaRecorder();
mr.setAudioSource(AudioSource.MIC);
//设置音源,这里是来自麦克风,虽然有VOICE_CALL,但经真机测试,不行
mr.setOutputFormat(OutputFormat.RAW_AMR);
//输出格式
mr.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
//编码
mr.setOutputFile("/sdcard/1.amr");
//输出文件路径,貌似文件必须是不存在的,不会自己清空
try{
mr.prepare();
//做些准备工作
mr.start();
//开始
}catch(Exception e){
e.printStackTrace();
}
}});
stop.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mr.stop();
//停止
mr.release();
//释放
}});

}
}

注意添加权限:

1
2

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

不加权限会出现类似unsupported parameter: x-pvmf/media-input-node/cap-config-interface;valtype=key_specific_value之类的错误

源码打包:

MediaRecorder (330)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: