源码教程 2025年06月7日
0 收藏 0 点赞 732 浏览 9174 个字
摘要 :

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

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

Android使用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 所示。

Android使用MediaRecorder录制音频

图 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>

微信扫一扫

支付宝扫一扫

版权: 转载请注明出处:https://www.zuozi.net/1020.html

管理员

相关推荐
2025-07-05

对于一些使用WordPress进行外贸建站的商家来说,大部分人会通过在WordPress中添加JS代码和CSS样式表…

701
2025-07-05

当商家遇到WordPress独立站改版或者域名到期等问题时,不免会涉及到WordPress域名的更改,那么这一…

715
2025-07-05

用户在使用WooCommerce进行跨境电商独立站搭建工作时,有可能会借助WooCommerce短代码实现更加醒目…

307
2025-07-05

随着外贸建站行业的不断深入发展,WordPress的多语言功能也显得越来越重要,一个具有多语言的独立站…

1,039
2025-07-05

WooCommerce作为WordPress外贸建站生态的一部分,WooCommerce运费设置是商家在建站过程中不可忽视的…

835
2025-07-05

在外贸建站的过程中,有些商家会选择使用WordPress幻灯片为网站页面增加一定的动感和可观性,进而提…

723
发表评论
暂无评论

还没有评论呢,快来抢沙发~

助力内容变现

将您的收入提升到一个新的水平

点击联系客服

在线时间:08:00-23:00

客服QQ

122325244

客服电话

400-888-8888

客服邮箱

122325244@qq.com

扫描二维码

关注微信客服号