http://blog.csdn.net/cxf7394373/article/details/8313980

android开发文档中有一个关于录音的类MediaRecord,一张图介绍了基本的流程:

给出了一个常用的例子:
  1. 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();   // Recording is now started
  8. ...
  9. recorder.stop();
  10. recorder.reset();   // You can reuse the object by going back to setAudioSource() step
  11. recorder.release(); // Now the object cannot be reused

我在这里实现了一个简单的程序,过程和上述类似,录音以及录音的播放。

1.基本界面如下:
 
2.工程中各文件内容如下:
  2.1 Activity——RecordActivity
  1. package com.cxf;
  2. import java.io.IOException;
  3. import android.app.Activity;
  4. import android.media.MediaPlayer;
  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.Button;
  12. public class RecordActivity extends Activity {
  13. private static final String LOG_TAG = "AudioRecordTest";
  14. //语音文件保存路径
  15. private String FileName = null;
  16. //界面控件
  17. private Button startRecord;
  18. private Button startPlay;
  19. private Button stopRecord;
  20. private Button stopPlay;
  21. //语音操作对象
  22. private MediaPlayer mPlayer = null;
  23. private MediaRecorder mRecorder = null;
  24. /** Called when the activity is first created. */
  25. @Override
  26. public void onCreate(Bundle savedInstanceState) {
  27. super.onCreate(savedInstanceState);
  28. setContentView(R.layout.main);
  29. //开始录音
  30. startRecord = (Button)findViewById(R.id.startRecord);
  31. startRecord.setText(R.string.startRecord);
  32. //绑定监听器
  33. startRecord.setOnClickListener(new startRecordListener());
  34. //结束录音
  35. stopRecord = (Button)findViewById(R.id.stopRecord);
  36. stopRecord.setText(R.string.stopRecord);
  37. stopRecord.setOnClickListener(new stopRecordListener());
  38. //开始播放
  39. startPlay = (Button)findViewById(R.id.startPlay);
  40. startPlay.setText(R.string.startPlay);
  41. //绑定监听器
  42. startPlay.setOnClickListener(new startPlayListener());
  43. //结束播放
  44. stopPlay = (Button)findViewById(R.id.stopPlay);
  45. stopPlay.setText(R.string.stopPlay);
  46. stopPlay.setOnClickListener(new stopPlayListener());
  47. //设置sdcard的路径
  48. FileName = Environment.getExternalStorageDirectory().getAbsolutePath();
  49. FileName += "/audiorecordtest.3gp";
  50. }
  51. //开始录音
  52. class startRecordListener implements OnClickListener{
  53. @Override
  54. public void onClick(View v) {
  55. // TODO Auto-generated method stub
  56. mRecorder = new MediaRecorder();
  57. mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
  58. mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
  59. mRecorder.setOutputFile(FileName);
  60. mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
  61. try {
  62. mRecorder.prepare();
  63. } catch (IOException e) {
  64. Log.e(LOG_TAG, "prepare() failed");
  65. }
  66. mRecorder.start();
  67. }
  68. }
  69. //停止录音
  70. class stopRecordListener implements OnClickListener{
  71. @Override
  72. public void onClick(View v) {
  73. // TODO Auto-generated method stub
  74. mRecorder.stop();
  75. mRecorder.release();
  76. mRecorder = null;
  77. }
  78. }
  79. //播放录音
  80. class startPlayListener implements OnClickListener{
  81. @Override
  82. public void onClick(View v) {
  83. // TODO Auto-generated method stub
  84. mPlayer = new MediaPlayer();
  85. try{
  86. mPlayer.setDataSource(FileName);
  87. mPlayer.prepare();
  88. mPlayer.start();
  89. }catch(IOException e){
  90. Log.e(LOG_TAG,"播放失败");
  91. }
  92. }
  93. }
  94. //停止播放录音
  95. class stopPlayListener implements OnClickListener{
  96. @Override
  97. public void onClick(View v) {
  98. // TODO Auto-generated method stub
  99. mPlayer.release();
  100. mPlayer = null;
  101. }
  102. }
  103. }

2.2 main.xml

  1. <?xml version="1.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:text="@string/hello" />
  10. <Button
  11. android:id="@+id/startRecord"
  12. android:layout_width="fill_parent"
  13. android:layout_height="wrap_content"
  14. />
  15. <Button
  16. android:id="@+id/stopRecord"
  17. android:layout_width="fill_parent"
  18. android:layout_height="wrap_content"
  19. />
  20. <Button
  21. android:id="@+id/startPlay"
  22. android:layout_width="fill_parent"
  23. android:layout_height="wrap_content"
  24. />
  25. <Button
  26. android:id="@+id/stopPlay"
  27. android:layout_width="fill_parent"
  28. android:layout_height="wrap_content"
  29. />
  30. </LinearLayout>

2.3 Manifest.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3. package="com.cxf"
  4. android:versionCode="1"
  5. android:versionName="1.0" >
  6. <uses-sdk android:minSdkVersion="4" />
  7. <application
  8. android:icon="@drawable/ic_launcher"
  9. android:label="@string/app_name" >
  10. <activity
  11. android:name=".RecordActivity"
  12. android:label="@string/app_name" >
  13. <intent-filter>
  14. <action android:name="android.intent.action.MAIN" />
  15. <category android:name="android.intent.category.LAUNCHER" />
  16. </intent-filter>
  17. </activity>
  18. </application>
  19. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  20. <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
  21. <uses-permission android:name="android.permission.RECORD_AUDIO" />
  22. </manifest>
 2.4 string.xml
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <resources>
  3. <string name="hello"></string>
  4. <string name="app_name">Record</string>
  5. <string name="startRecord">开始录音</string>
  6. <string name="stopRecord">结束录音</string>
  7. <string name="startPlay">开始播放</string>
  8. <string name="stopPlay">结束播放</string>
  9. </resources>

今天在调用MediaRecorder.stop(),报错了,Java.lang.RuntimeException: stop failed.

  1. E/AndroidRuntime(7698): Cause by: java.lang.RuntimeException: stop failed.
  2. E/AndroidRuntime(7698):            at android.media.MediaRecorder.stop(Native Method)
  3. E/AndroidRuntime(7698):            at com.tintele.sos.VideoRecordService.stopRecord(VideoRecordService.java:298)

报错代码如下:

  1. if (mediarecorder != null) {
  2. mediarecorder.stop();
  3. mediarecorder.release();
  4. mediarecorder = null;
  5. if (mCamera != null) {
  6. mCamera.release();
  7. mCamera = null;
  8. }
  9. }

stop()方法源代码如下:

  1. /**
  2. * Stops recording. Call this after start(). Once recording is stopped,
  3. * you will have to configure it again as if it has just been constructed.
  4. * Note that a RuntimeException is intentionally thrown to the
  5. * application, if no valid audio/video data has been received when stop()
  6. * is called. This happens if stop() is called immediately after
  7. * start(). The failure lets the application take action accordingly to
  8. * clean up the output file (delete the output file, for instance), since
  9. * the output file is not properly constructed when this happens.
  10. *
  11. * @throws IllegalStateException if it is called before start()
  12. */
  13. public native void stop() throws IllegalStateException;

源代码中说了:Note that a RuntimeException is intentionally thrown to the application, if no valid audio/video data has been received when stop() is called. This happens if stop() is called immediately after start().The failure lets the application take action accordingly to clean up the output file (delete the output file, for instance), since the output file is not properly constructed when this happens.

现在,在mediarecorder.stop();这一句报错了,现在在mediarecorder.stop();这句之前加几句就不会报错了

mediarecorder.setOnErrorListener(null);
mediarecorder.setOnInfoListener(null);  
mediarecorder.setPreviewDisplay(null);

改后代码如下:

    1. if (mediarecorder != null) {
    2. //added by ouyang start
    3. try {
    4. //下面三个参数必须加,不加的话会奔溃,在mediarecorder.stop();
    5. //报错为:RuntimeException:stop failed
    6. mediarecorder.setOnErrorListener(null);
    7. mediarecorder.setOnInfoListener(null);
    8. mediarecorder.setPreviewDisplay(null);
    9. mediarecorder.stop();
    10. } catch (IllegalStateException e) {
    11. // TODO: handle exception
    12. Log.i("Exception", Log.getStackTraceString(e));
    13. }catch (RuntimeException e) {
    14. // TODO: handle exception
    15. Log.i("Exception", Log.getStackTraceString(e));
    16. }catch (Exception e) {
    17. // TODO: handle exception
    18. Log.i("Exception", Log.getStackTraceString(e));
    19. }
    20. //added by ouyang end
    21. mediarecorder.release();
    22. mediarecorder = null;
    23. if (mCamera != null) {
    24. mCamera.release();
    25. mCamera = null;
    26. }
    27. }

[Android] 录音与播放录音实现的更多相关文章

  1. C# 录音和播放录音-NAudio

    在使用C#进行录音和播放录音功能上,使用NAudio是个不错的选择. NAudio是个开源,相对功能比较全面的类库,它包含录音.播放录音.格式转换.混音调整等操作,具体可以去Github上看看介绍和源 ...

  2. MT6737 Android N 平台 Audio系统学习----录音到播放录音流程分析

    http://blog.csdn.net/u014310046/article/details/54133688 本文将从主mic录音到播放流程来进行学习mtk audio系统架构.  在AudioF ...

  3. 【Android】20.4 录音

    分类:C#.Android.VS2015: 创建日期:2016-03-13 一.简介 利用Android提供的MediaRecorder类可直接录制音频. 1.权限要求 录制音频和视频需要下面的权限: ...

  4. AVFoundation之录音及播放

    录音 在开始录音前,要把会话方式设置成AVAudioSessionCategoryPlayAndRecord //设置为播放和录音状态,以便可以在录制完之后播放录音 AVAudioSession *s ...

  5. C# NAudio录音和播放音频文件-实时绘制音频波形图(从音频流数据获取,而非设备获取)

    NAudio的录音和播放录音都有对应的类,我在使用Wav格式进行录音和播放录音时使用的类时WaveIn和WaveOut,这两个类是对功能的回调和一些事件触发. 在WaveIn和WaveOut之外还有对 ...

  6. C# NAudio录音和播放音频文件及实时绘制音频波形图(从音频流数据获取,而非设备获取)

    下午写了一篇关于NAudio的录音.播放和波形图的博客,不太满意,感觉写的太乱,又总结了下 NAudio是个相对成熟.开源的C#音频开发工具,它包含录音.播放录音.格式转换.混音调整等功能.本次介绍主 ...

  7. Android开发教程 录音和播放

    首先要了解andriod开发中andriod多媒体框架包含了什么,它包含了获取和编码多种音频格式的支持,因此你几耍轻松把音频合并到你的应用中,若设备支持,使用MediaRecorder APIs便可以 ...

  8. Android平台下实现录音及播放录音功能的简介

    录音及播放的方法如下: package com.example.audiorecord; import java.io.File; import java.io.IOException; import ...

  9. Android 实时录音和回放,边录音边播放 (KTV回音效果)

    上一篇介绍了如何使用Mediarecorder来录音,以及播放录音.不过并没有达到我的目的,一边录音一边播放.今天就讲解一下如何一边录音一边播放.使用AndioRecord录音和使用AudioTrac ...

随机推荐

  1. Android无线测试之—UiAutomator UiWatcher API介绍一

    UiWatcher类介绍与中断监听检查条件 一.UiWatcher类说明 1.Uiwatcher用于处理脚本执行过程中遇到非预想的步骤 2.UiWatcher使用场景 1)测试过程中来了一个电话 2) ...

  2. window 发布已编译好的ASP文件到IIS

    1.进入window 7的控制面板,点击程序,选择程序和功能中的 打开或关闭Windows功能.安装IIS

  3. Spring Security OAuth2 源码分析

    Spring Security OAuth2 主要两部分功能:1.生成token,2.验证token,最大概的流程进行了一次梳理 1.Server端生成token (post /oauth/token ...

  4. klg-jpa:spring-data-jpa 最佳实践

    klg-jpa:spring-data-jpa 最佳实践 项目介绍 码云地址:https://gitee.com/klguang/klg-jpa JPA是sun为POJO持久化制定的标准规范,用来操作 ...

  5. Quartz.net 基于配置的调度程序实践

    1.Nuget 搜索并安装Quartz.net 2.3.3  2.添加配置到App.config <?xml version="1.0" encoding="utf ...

  6. HDU4686—Arc of Dream

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4686 题目意思:给出一个n,算这个式子,给出A0,B0,AX,AY,然后存在以下的递推关系. a0 = ...

  7. iOS 10 获取相册相机权限

            AVAudioSession *audioSession = [[AVAudioSession alloc]init]; [audioSession requestRecordPerm ...

  8. Android 判断当前thread 是否是UI thread

    在Android 中判断当前的Thread是否是UI Thread 的方法: 1. if (Looper.myLooper() == Looper.getMainLooper()) { // Curr ...

  9. 即使关闭了nagle算法,粘包依旧存在

    JAVA高级架构 https://mp.weixin.qq.com/s?src=11&timestamp=1542107581&ver=1242&signature=OoktA ...

  10. Web性能测试通用标准

    性能指标 通过 不通过 备注 响应时间 <期望时间 >期望时间 1.所有性能指标期望值是根据性能测试申请单取值: 2.响应时间2-5-8原则: 响应时间在2-5秒内,系统的响应速度比较快: ...