展会信息港展会大全

android使用MediaRecorder实现录音
来源:互联网   发布日期:2015-09-29 10:17:43   浏览:2127次  

导读:MediaRecorder可以用来录制音频或视频。它具有以下几个状态:Initial:初始状态,在设定视频源或者音频源之后将转换为Initialized状态。Initialized:已初始化状态,可以通过设置输出格式转换为DataSourceConfig......

MediaRecorder可以用来录制音频或视频。它具有以下几个状态:

Initial:初始状态,在设定视频源或者音频源之后将转换为Initialized状态。

Initialized:已初始化状态,可以通过设置输出格式转换为DataSourceConfigured状态,或者通过重新启动转换成Initial状态。

设置录音来源 :

iMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);

设置输出格式:

iMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);

设置编码方式

iMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);

设置输出文件

iMediaRecorder.setOutputFile(PATH_NAME);

让MediaRecorder对象处于就绪状态

iMediaRecorder.prepare();

开始录音

iMediaRecorder.start();

停止录音,一旦停止则必须从新配置MediaRecorder对象才能再次开始录音。

iMediaRecorder.stop();

从新启动MediaRecorder对象让它处于空闲状态。

iMediaRecorder.reset();

释放和MediaRecorder对向相关的所有资源。

iMediaRecorder.release();

package com.ophone.iRecorder;

//这里为了节省篇幅,忽略了import项

public class ActivityMain extends Activity {

private ImageButton iRecordButton;

private ImageButton iStopButton;

private ImageButton iPlayButton;

private ImageButton iDeleteButton;

private ListView iListView;

private String iTempFileNameString = "iRecorder_";

private File iRecAudioFile;

private File iRecAudioDir;

private File iPlayFile;

private MediaRecorder iMediaRecorder;

private ArrayList iRecordFiles;

private ArrayAdapter iAdapter;

private TextView iTextView;

private boolean isSDCardExit;

private boolean isStopRecord;

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

iRecordButton = (ImageButton) findViewById(R.id.ImageButton01);

iStopButton = (ImageButton) findViewById(R.id.ImageButton02);

iPlayButton = (ImageButton) findViewById(R.id.ImageButton03);

iDeleteButton = (ImageButton) findViewById(R.id.ImageButton04);

iListView = (ListView) findViewById(R.id.ListView01);

iTextView = (TextView) findViewById(R.id.TextView01);

/* 初始后三个按钮不可用 */

iStopButton.setEnabled(false);

iPlayButton.setEnabled(false);

iDeleteButton.setEnabled(false);

需要判断SD卡是否是插入状态,以保证我们可以长时间的进行录音。如果存在则取得SD卡路径作为录音的文件位置。然后取得SD卡中的.amr文件。getRecordFiles()是一个自定义的方法,后面将会有说明。

1.isSDCardExit = Environment.getExternalStorageState().equals(

2.android.os.Environment.MEDIA_MOUNTED);

3.if (isSDCardExit)

4.iRecAudioDir = Environment.getExternalStorageDirectory();

5.this.getRecordFiles();

6.iAdapter = new ArrayAdapter(this, R.layout.my_simple_list_item,

7.iRecordFiles);

8./* 将ArrayAdapter添加ListView对象中 */

9.iListView.setAdapter(iAdapter);

对第一个录音按钮我们最需要注意的是在iMediaRecorder.start()之前我们必须调用iMediaRecorder.prepare()来捕获和编码数据,而且prepare()必须要在设置音频源、编码器、以及文件格式之后才能调用!

view plaincopy to clipboardprint?

1.iRecordButton.setOnClickListener(new ImageButton.OnClickListener() {

2.@Override

3.public void onClick(View arg0) {

4.try {

5.if (!isSDCardExit) {

6.Toast.makeText(ActivityMain.this, "请插入SD Card",

7.Toast.LENGTH_LONG).show();

8.return;

9.}

10. /* 创建录音文件 */

11. iRecAudioFile = File.createTempFile(iTempFileNameString,

12. ".amr", iRecAudioDir);

13. iMediaRecorder = new MediaRecorder();

14. /* 设置录音来源为MIC */

15. iMediaRecorder

16. .setAudioSource(MediaRecorder.AudioSource.MIC);

17. iMediaRecorder

18. .setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);

19. iMediaRecorder

20. .setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);

21. iMediaRecorder.setOutputFile(iRecAudioFile

22. .getAbsolutePath());

23. iMediaRecorder.prepare();

24. iMediaRecorder.start();

25. iTextView.setText("正在录音");

26. iStopButton.setEnabled(true);

27. iPlayButton.setEnabled(false);

28. iDeleteButton.setEnabled(false);

29. isStopRecord = false;

30. } catch (IOException e) {

31. // TODO Auto-generated catch block

32. e.printStackTrace();

33. }

34. }

35. });

在停止录音的时候需要iMediaRecorder.stop()停止录音,一旦停止录音,必须从新配置MediaRecorder才可以。iMediaRecorder.release()用来释放和iMediaRecorder对象相关的所有资源。最后把iMediaRecorder赋值为null。

view plaincopy to clipboardprint?

1.iStopButton.setOnClickListener(new ImageButton.OnClickListener() {

2.@Override

3.public void onClick(View arg0) {

4.// TODO Auto-generated method stub

5.if (iRecAudioFile != null) {

6./* 停止录音 */

7.iMediaRecorder.stop();

8.iMediaRecorder.release();

9.iMediaRecorder = null;

10. /* 将录音频文件名给Adapter */

11. iAdapter.add(iRecAudioFile.getName());

12. iTextView.setText("停止:" + iRecAudioFile.getName());

13. iStopButton.setEnabled(false);

14. isStopRecord = true;

15. }

16. }

17. });

18. /* 播放 */

19. iPlayButton.setOnClickListener(new ImageButton.OnClickListener() {

20. @Override

21. public void onClick(View arg0) {

22. // TODO Auto-generated method stub

23. if (iPlayFile != null && iPlayFile.exists()) {

24. /* 打开播放程序 */

25. openFile(iPlayFile);

26. }

27. }

28. });

29. /* 删除 */

30. iDeleteButton.setOnClickListener(new ImageButton.OnClickListener() {

31. @Override

32. public void onClick(View arg0) {

33. // TODO Auto-generated method stub

34. if (iPlayFile != null) {

35. /* 先将Adapter删除文件名 */

36. iAdapter.remove(iPlayFile.getName());

37. /* 删除文件 */

38. if (iPlayFile.exists())

39. iPlayFile.delete();

40. iTextView.setText("删除完成");

41. }

42. }

43. });

44.

45. iListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

46. @Override

47. public void onItemClick(AdapterViewarg0, View arg1, int arg2,

48. long arg3) {

49. /* 当有点击文件名时将删除及播放按钮Enable */

50. iPlayButton.setEnabled(true);

51. iDeleteButton.setEnabled(true);

52. iPlayFile = new File(iRecAudioDir.getAbsolutePath()

53. + File.separator + ((CheckedTextView) arg1).getText());

54. iTextView.setText("您选择的是:" + ((CheckedTextView) arg1).getText());

55. }

56. });

在Activity的onStop()方法也要加进去释放iMediaRecorder的语句。

view plaincopy to clipboardprint?

1.@Override

2.protected void onStop() {

3.if (iMediaRecorder != null && !isStopRecord) {

4./* 停止录音 */

5.iMediaRecorder.stop();

6.iMediaRecorder.release();

7.iMediaRecorder = null;

8.}

9.super.onStop();

10. }

11.

12. 这是一个自定义方法,目的是从手机存储卡中取出以.amr结尾的文件。

13. private void getRecordFiles() {

14. iRecordFiles = new ArrayList();

15. if (isSDCardExit) {

16. File files[] = iRecAudioDir.listFiles();

17. if (files != null) {

18. for (int i = ; i < files.length; i++) {

19. if (files[i].getName().indexOf(".") >= ) {

20. String fileS = files[i].getName().substring(

21. files[i].getName().indexOf("."));

22. if (fileS.toLowerCase().equals(".amr"))

23. iRecordFiles.add(files[i].getName());

24. }

25. }

26. }

27. }

28. }

调用系统自带播放器来播放刚才录制好的声音片段。OPhone系统会根据文件类型来自动决定使用何种工具来打开对应的文件。当然我们还可以用OPhone提供的MediaPlayer类来实现声音片段的播放,由于篇幅有限,这里不再介绍。

view plaincopy to clipboardprint?

1.private void openFile(File aFile) {

2.Intent intent = new Intent();

3.intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

4.intent.setAction(android.content.Intent.ACTION_VIEW);

5.String type = getMIMEType(aFile);

6.intent.setDataAndType(Uri.fromFile(aFile), type);

7.startActivity(intent);

8.}

9.

10. private String getMIMEType(File aFile) {

11. String end = aFile.getName().substring(

12. aFile.getName().lastIndexOf(".") + 1, aFile.getName().length())

13. .toLowerCase();

14. String type = "";

15. if (end.equals("mp3") || end.equals("aac") || end.equals("aac")

16. || end.equals("amr") || end.equals("mpeg") || end.equals("mp4")) {

17. type = "audio";

18. } else if (end.equals("jpg") || end.equals("gif") || end.equals("png")

19. || end.equals("jpeg")) {

20. type = "image";

21. } else {

22. type = "*";

23. }

24. type += "/*";

25. return type;

26. }

添加权限许可

如果只是写好了程序还不算完工,最后我们需要在AndroidManifest.xml文件中将程序的录音权限打开!这样才能成为一个完整的程序。

view plaincopy to clipboardprint?

1.

2.android:versionCode="1"

3.android:versionName="1.0" package="com.ophone.iRecorder">

4.

5.android:icon="@drawable/icon"

6.android:label="@string/app_name">

7.

8.android:label="@string/app_name">

9.

10.

11. android:name="android.intent.action.MAIN" />

12.

13. android:name="android.intent.category.LAUNCHER" />

14.

15.

16.

17.

18.

19.

赞助本站

人工智能实验室

相关热词: MediaRecorder 录音

相关内容
AiLab云推荐
推荐内容
展开

热门栏目HotCates

Copyright © 2010-2024 AiLab Team. 人工智能实验室 版权所有    关于我们 | 联系我们 | 广告服务 | 公司动态 | 免责声明 | 隐私条款 | 工作机会 | 展会港