您好!欢迎来到源码码网

Android使用MediaRecorder录制音频

  • 源码教程
  • 来源:源码码网
  • 编辑:admin
  • 时间:2021-01-14 19:49
  • 阅读:523

Android SDK 提供了使用 MediaRecorder 类实现对音频和视频进行录制的功能。MediaRecorder 对象在运行过程中存在多种状态,其状态转化如图 1 所示。

MediaRecorder对象状态转化图

图 1  MediaRecorder对象状态转化图

从图 1 中可以看到:

1)创建 MediaRecorder 对象后处于 Initial 状态。

MediaRecorder 对象会占用硬件资源,因此不再需要时,应该调用 release() 方法销毁。在其他状态调用 reset() 方法,可以使得 MediaRecorder 对象重新回到 Initial 状态,达到复用 MediaRecorder 对象的目的。

2)在 Initial 状态调用 setVideoSource() 或者 setAudioSource() 之后,MediaRecorder 将进入 Initialized 状态。

对于音频录制,目前 OPhone 平台支持从麦克风或者电话两个音频源录制数据。在 Initialized 状态的 MediaRecorder 还需要设置编码格式、文件数据路径、文件格式等信息,设置之后 MediaRecorder 进入 DataSourceConfigured 状态。

3)在 DataSourceConfigured 状态调用 prepare() 方法,MediaRecorder 对象将进入 Prepared 状态,录制前的状态准备就绪。

4)在 Prepared 状态调用 start() 方法,MediaRecorder 进入 Recording 状态,声音录制可能只需一段时间,这时 MediaRecorder 一直处于录制状态。

5)在 Recording 状态调用 stop() 方法,MediaRecorder 将停止录制,并将录制内容输出到指定文件。

MediaRecorder 定义了两个内部接口 OnErrorListener 和 OnInfoListener 来监听录制过程中的错误信息。

例如,当录制的时间长度达到了最大限制或者录制文件的大小达到了最大文件限制时,系统会回调已经注册的 OnInfoListener 接口的 onInfo() 方法。

使用 MediaRecorder 类进行音频录制的基本步骤如下:

1)建立 MediaRecorder 类的对象。

MediaRecorder recorder=new MediaRecorder();

2)设置音频来源。

recorder.setAudioSource(MediaRecorder.AudioSource.MIC);


3)设置音频输出格式。

recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);


4)设置音频编码方式。

recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);


5)设置音频文件的保存位置及文件名。

recorder.setOutputFile(PATH_NAME);


6)将录音器置于准备状态。

recorder.prepare();


7)启动录音器。

recorder.start();


8)音频录制。

9)音频录制完成,停止录音器。

recorder.stop();


10)释放录音器对象。

recorder.release();

实例 AudioRecord 演示了使用 MediaRecorder 类对音频进行录制的过程,运行效果如图 2 所示。

AudioRecord的运行效果

图 2  AudioRecord的运行效果

该运行效果对应的布局文件 main.xml 的代码如下:


  1. <?xml version="l.0" encoding="utf-8"?>


  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

  3. android:layout_width="fill_parent"

  4. android:layout_height="fill_parent"

  5. android:orientation="vertical">


  6. <TextView

  7. android:layout_width="fill_parent"

  8. android:layout_height="wrap_content"

  9. android:layout_marginLeft="70dp"

  10. android:layout_marginTop="30dp"

  11. android:text="@string/hello" />


  12. <LinearLayout

  13. android:layout_width="fill_parent"

  14. android:layout_height="wrap_content"

  15. android:layout_marginTop="30dp"

  16. android:orientation="horizontal">


  17. <ImageButton

  18. android:id="@+id/st"

  19. android:layout_width="wrap_content"

  20. android:layout_height="wrap_content"

  21. android:layout_marginLeft="20dp"

  22. android:scaleType="fitXY"

  23. android:src="0drawable/st" />


  24. <ImageButton

  25. android:id="@+id/stop"

  26. android:layout_width="wrap_content"

  27. android:layout_height="wrap_content"

  28. android:layout_marginLeft="30dp"

  29. android:scaleType="fitXY"

  30. android:src="0drawable/stop" />


  31. </LinearLayout>


  32. <LinearLayout

  33. android:layout_width="fill_parent"

  34. android:layout_height="wrap_content"

  35. android:orientation="horizontal">


  36. <TextView

  37. android:layout_width="wrap_content"

  38. android:layout_height="wrap_content"

  39. android:layout_marginLeft="21dp"

  40. android:text="@string/start" />


  41. <TextView

  42. android:layout_width="wrap_content"

  43. android:layout_height="wrap_content"

  44. android:layout_marginLeft="43dp"

  45. android:text="@string/stop" />


  46. <TextView

  47.       android:id="@+id/sttext"

  48.       android:layout_width="fill_parent"

  49.       android:layout_height="wrap_content" />

  50. </LinearLayout>

  51. </LinearLayout>

实例 AudioRecord 中 AndroidManifest.xml 文件的代码如下:

  1. <?xml version="1.0" encoding="utf-8"?>

  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"

  3. package="introduction.android.audiorecord"

  4. android:versionCode="1"

  5. android:versionName="1.0">


  6. <uses-sdk android:minSdkVersion="14" />

  7. <application

  8. android:allowBackup="true"

  9. android:icon="@mipmap/ic_launcher"

  10. android:label="@string/app_name"

  11. android:roundIcon="@mipmap/ic_launcher_round"

  12. android:supportsRtl="true"

  13. android:theme="@style/AppTheme">

  14. <activity android:name=".MainActivity">

  15. <intent-filter>

  16. <action android:name="android.intent.action.MAIN" />

  17. <category android:name="android.intent.category.LAUNCHER" />

  18. </intent-filter>

  19. </activity>

  20. </application>


  21. </manifest>


其中:

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

表明进行音频录制的用户权限。


实例 AudioRecord 中 MainActivity.java 的代码如下:


  1. package introduction.android.audiorecord;


  2. import java.io.File;

  3. import java.io.IOException;



  4. import android.app.Activity;


  5. import android.media.MediaRecorder;

  6. import android.os.Bundle;

  7. import android.os.Environment;

  8. import android.util.Log;

  9. import android.view.View;


  10. import android.view.View.OnClickListener;


  11. import android.widget.ImageButton;

  12. import android.widget.TextView;


  13. import android.widget.Toast;


  14. public class MainActivity extends Activity implements OnClickListener {


  15. /**

  16.     * Called when the activity is first created.

  17.     */

  18. private ImageButton st, stop;

  19. private TextView sttext;

  20. private MediaRecorder mRecorder;

  21. private File recordPath;

  22. private File recordFile;


  23. @Override

  24. public void onCreate(Bundle savedInstanceState) {

  25. super.onCreate(savedInstanceState);

  26. setContentView(R.layout.activity_main);


  27. st = (ImageButton) findViewById(R.id.st);

  28. stop = (ImageButton) findViewById(R.id.stop);

  29. sttext = (TextView) findViewById(R.id.sttext);

  30. st.setOnClickListener(this);

  31. stop.setOnClickListener(this);

  32. }


  33. public void start() {

  34. if (checkSDCard()) {

  35. recordPath = Environment.getExternalStorageDirectory();

  36. File path = new File(recordPath.getPath() + File.separator + "audioRecords");

  37. if (!path.mkdirs()) {

  38. Log.d("audioRecorder", "创建目录失败");

  39. return;

  40. }

  41. } else {

  42. Toast.makeText(MainActivity.this, "SDcard未连接",

  43. Toast.LENGTH_LONG).show();

  44. return;

  45. }


  46. try {

  47. recordFile = File.createTempFile(String.valueOf("myrecord_"), ".amr", recordPath);

  48. } catch (IOException e) {

  49. Log.d("audioRecorder", "文件创建失败");

  50. }

  51. mRecorder = new MediaRecorder();

  52. //设置麦克风

  53. mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);

  54. //输入文件格式

  55. mRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);

  56. //音频文件编码

  57. mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);

  58. //输出文件路径

  59. mRecorder.setOutputFile(recordFile.getAbsolutePath());

  60. //开始录音

  61. try {

  62. mRecorder.prepare();

  63. mRecorder.start();

  64. } catch (IllegalStateException e) {

  65. e.printStackTrace();

  66. } catch (IOException e) {

  67. e.printStackTrace();

  68. }

  69. }


  70. public void stop() {

  71. try {

  72. if (mRecorder != null) {

  73. mRecorder.stop();

  74. mRecorder.release();

  75. mRecorder = null;

  76. }

  77. } catch (IllegalStateException e) {

  78. }

  79. }


  80. private boolean checkSDCard() {


  81. // TODO Auto-generated method stub

  82. //检测SD卡是否插入手机中

  83. if (android.os.Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

  84. return true;

  85. }

  86. return false;

  87. }


  88. @Override

  89. public void onClick(View v) {

  90. // TODO Auto-generated method stub

  91. if (v == st) {

  92. MainActivity.this.start();

  93. sttext.setText("正在录音。。。。");

  94. if (v == stop) {

  95. sttext.setText("停止录音。。。。");

  96. MainActivity.this.stop();

  97. }

  98. }

  99. }

  100. }

该应用程序运行后,首先检测 SD 卡是否插入手机中。若 SD 卡在手机中,则会在 SD 卡的 audioRecords 目录下创建以“myRecord_”为前缀、以“.amr”为后缀的临时文件,并将录音内容写入该文件中。

后台录制音频

结合 Android 系统提供的相关 API,借助于 MediaRecorder 类,可以实现一些比较有意思的功能。比如,在手机中监听短信的功能,当有符合特定要求的短信到来时,启动相应服务在后台进行录音,进而将手机变化为一个可远程控制的录音机。

接下来我们在此处不去实现短信内容验证功能,而只演示通过短信远程启动后台服务并进行录音的功能,我们可以举一反三。

实例 AudioRecordService 演示了该功能。该实例实现了 BroadcastReceiver 类的子类,对手机短信息进行监听。当有短信来时,该 BroadcastReceiver 开始在后台录音并将录音文件保存在 SD 卡中,同时启动一个线程进行计时,当录音进行一分钟后,关闭录音程序。

实例 AudioRecordService 中 MessageReceiver.java 的代码如下:

  1. package introduction.android.audiorecord;


  2. import java.io.File;

  3. import java.io.IOException;


  4. import android.content.BroadcastReceiver;

  5. import android.content.Context;

  6. import android.content.Intent;

  7. import android.media.MediaRecorder;

  8. import android.os.Bundle;

  9. import android.os.Environment;

  10. import android.util.Log;


  11. public class MessageReceiver extends BroadcastReceiver {

  12. private File recordPath;

  13. private File recordFile;

  14. private MediaRecorder mRecorder;

  15. private long startTime;


  16. @Override

  17. public void onReceive(Context context, Intent intent) {

  18. // TODO Auto-generated method stub

  19. if (intent.getAction().equals("android.proider.Telephony.SMS_RECEIVER")) {

  20. recordBegin();

  21. new Thread(timing).start();

  22. }

  23. }


  24. private Runnable timing = new Runnable() {

  25. private long currentTime = System.currentTimeMillis();


  26. @Override

  27. public void run() {

  28. // TODO Auto-generated method stub

  29. while (currentTime < startTime + 60 * 1000) {

  30. try {

  31. Thread.sleep(1000);

  32. } catch (InterruptedException e) {

  33. // TODO Auto-generated catch block

  34. e.printStackTrace();

  35. }

  36. recordStop();

  37. }

  38. }

  39. };


  40. private void recordBegin() {

  41. // TODO Auto-generated method stub

  42. startTime = System.currentTimeMillis();

  43. recordPath = Environment.getExternalStorageDirectory();

  44. File path = new File(recordPath.getPath() + File.separator + "audioRecords");

  45. recordPath = path;

  46. try {

  47. recordFile = File.createTempFile(String.valueOf("myrecord_"), ".amr",

  48. recordPath);

  49. } catch (IOException e) {

  50. Log.d("audioRecorder", "文件创建失败");

  51. }

  52. mRecorder = new MediaRecorder();

  53. mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);

  54. mRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);

  55. mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);

  56. mRecorder.setOutputFile(recordFile.getAbsolutePath());

  57. try {

  58. mRecorder.prepare();

  59. mRecorder.start();

  60. } catch (IllegalStateException e) {

  61. e.printStackTrace();

  62. } catch (IOException e) {

  63. e.printStackTrace();

  64. }

  65. }


  66. protected void recordStop() {

  67. // TODO Auto-generated method stub

  68. mRecorder.stop();

  69. mRecorder.release();

  70. mRecorder = null;

  71. }

  72. }

由于实例 AudioRecordService 涉及接收短信和使用录音功能,因此需要在 AndroidManifest. xml 文件中声明相应的用户权限。

AndroidManifest.xml 文件的代码如下:

  1. <?xml version="1.0" encoding="utf-8"?>

  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"

  3. package="introduction.android.audiorecord"

  4. android:versionCode="1"

  5. android:versionName="1.0">


  6. <uses-sdk android:minSdkVersion="14" />

  7. <application

  8. android:allowBackup="true"

  9. android:icon="@mipmap/ic_launcher"

  10. android:label="@string/app_name"

  11. android:roundIcon="@mipmap/ic_launcher_round"

  12. android:supportsRtl="true"

  13. android:theme="@style/AppTheme">

  14. <activity android:name=".MainActivity">

  15. <intent-filter>

  16. <action android:name="android.intent.action.MAIN" />

  17. <category android:name="android.intent.category.LAUNCHER" />

  18. </intent-filter>

  19. </activity>

  20. </application>


  21. <uses-permission android:name="android.perssion.RECEIVE_SMS" />

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

  23. </manifest>


特别声明:
1、如无特殊说明,内容均为本站原创发布,转载请注明出处;
2、部分转载文章已注明出处,转载目的为学习和交流,如有侵犯,请联系客服删除;
3、编辑非《源码码网》的文章均由用户编辑发布,不代表本站立场,如涉及侵犯,请联系删除;
全部评论(0)
推荐阅读
  • bootstrap ui框架能用在uniapp中吗?
  • bootstrap ui框架能用在uniapp中吗?
  • BootstrapUI框架通常是前端开发中的一种工具,它提供了一套预定义的CSS样式和组件,用于快速构建响应式布局的网页。然而,UniApp是一个使用Vue.js开发跨平台应用的框架,它可以用来开发iOS、Android、以及各种小程序和H5应用。
  • 互动社区
  • 来源:源码码网
  • 编辑:热度建站
  • 时间:2024-04-12 00:04
  • 阅读:148
  • css实现banner图由中心点动态放大效果
  • css实现banner图由中心点动态放大效果
  • 在日常的网页设计中,为了让网页增加一定的特效以达到交互的目的,我们尝尝会在网页中使用一些动画效果。今天来说说实现banner图由中心点动态放大效果,实现这个效果需要用到css中的动画:animation​和关键帧:@keyframes,具体示例如下:
  • 源码教程
  • 来源:源码码网
  • 编辑:源码码网
  • 时间:2024-04-11 18:52
  • 阅读:165
  • countUp.js实现鼠标滑动到某个位置数字自动滚动增加的效果
  • countUp.js实现鼠标滑动到某个位置数字自动滚动增加的效果
  • 在网页开发中为了提升网页的交互效果,经常会用到使用js给网页增加一定的特效,下边就来说说使用js实现鼠标滑动到某个位置数字自动滚动增加的效果。其实这种效果有很多中解决办法,自己也可以去写,下边我们借助countUp.js来实现,关于这个js文件,我放在末尾:
  • 源码教程
  • 来源:源码码网
  • 编辑:源码码网
  • 时间:2024-04-08 09:20
  • 阅读:239
  • 响应式网页设计思路及注意事项
  • 响应式网页设计思路及注意事项
  • 一、什么是响应式网页响应式网页设计就是让网页具有根据设备类型应用CSS样式的能力。设计:设想、计划。设计就是把想法实现。网页设计:按照一定的设计思路布局网页内容。传统网页设计:都是针对PC端浏览器而设计的,不具备查询设备的能力,更不能对多种访问设备做出响应。传统网页设计的弊端:在移动互联网时代,传统的网页设计不适合多屏幕时代。响应式网页设计应运而生。响应式网页设计是一种设计网页的思想/方法。响应:指让我们的网页能够自动查询用户的访问设备
  • 源码教程
  • 来源:源码码网
  • 编辑:源码码网
  • 时间:2024-04-02 11:24
  • 阅读:145
  • css中rel的属性值都有哪些,分别代表什么意思
  • css中rel的属性值都有哪些,分别代表什么意思
  • 在HTML中,元素的rel属性用于定义当前文档与被链接文档之间的关系。这个属性在CSS的上下文中经常与样式表关联,但rel属性的用途远不止于此。以下是一些常见的rel属性值及其意义:1、stylesheet:表示被链接的文档是一个样式表。这通常用于链接CSS文件。
  • 源码教程
  • 来源:源码码网
  • 编辑:源码码网
  • 时间:2024-03-28 12:28
  • 阅读:277
联系客服
源码代售 源码咨询 素材咨询 联系客服
029-84538663
手机版

扫一扫进手机版
返回顶部