[Android] 录音与播放录音实现
http://blog.csdn.net/cxf7394373/article/details/8313980
android开发文档中有一个关于录音的类MediaRecord,一张图介绍了基本的流程:
- MediaRecorder recorder = new MediaRecorder();
- recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
- recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
- recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
- recorder.setOutputFile(PATH_NAME);
- recorder.prepare();
- recorder.start(); // Recording is now started
- ...
- recorder.stop();
- recorder.reset(); // You can reuse the object by going back to setAudioSource() step
- recorder.release(); // Now the object cannot be reused
我在这里实现了一个简单的程序,过程和上述类似,录音以及录音的播放。

- package com.cxf;
- import java.io.IOException;
- import android.app.Activity;
- import android.media.MediaPlayer;
- import android.media.MediaRecorder;
- import android.os.Bundle;
- import android.os.Environment;
- import android.util.Log;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- public class RecordActivity extends Activity {
- private static final String LOG_TAG = "AudioRecordTest";
- //语音文件保存路径
- private String FileName = null;
- //界面控件
- private Button startRecord;
- private Button startPlay;
- private Button stopRecord;
- private Button stopPlay;
- //语音操作对象
- private MediaPlayer mPlayer = null;
- private MediaRecorder mRecorder = null;
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- //开始录音
- startRecord = (Button)findViewById(R.id.startRecord);
- startRecord.setText(R.string.startRecord);
- //绑定监听器
- startRecord.setOnClickListener(new startRecordListener());
- //结束录音
- stopRecord = (Button)findViewById(R.id.stopRecord);
- stopRecord.setText(R.string.stopRecord);
- stopRecord.setOnClickListener(new stopRecordListener());
- //开始播放
- startPlay = (Button)findViewById(R.id.startPlay);
- startPlay.setText(R.string.startPlay);
- //绑定监听器
- startPlay.setOnClickListener(new startPlayListener());
- //结束播放
- stopPlay = (Button)findViewById(R.id.stopPlay);
- stopPlay.setText(R.string.stopPlay);
- stopPlay.setOnClickListener(new stopPlayListener());
- //设置sdcard的路径
- FileName = Environment.getExternalStorageDirectory().getAbsolutePath();
- FileName += "/audiorecordtest.3gp";
- }
- //开始录音
- class startRecordListener implements OnClickListener{
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- mRecorder = new MediaRecorder();
- mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
- mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
- mRecorder.setOutputFile(FileName);
- mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
- try {
- mRecorder.prepare();
- } catch (IOException e) {
- Log.e(LOG_TAG, "prepare() failed");
- }
- mRecorder.start();
- }
- }
- //停止录音
- class stopRecordListener implements OnClickListener{
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- mRecorder.stop();
- mRecorder.release();
- mRecorder = null;
- }
- }
- //播放录音
- class startPlayListener implements OnClickListener{
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- mPlayer = new MediaPlayer();
- try{
- mPlayer.setDataSource(FileName);
- mPlayer.prepare();
- mPlayer.start();
- }catch(IOException e){
- Log.e(LOG_TAG,"播放失败");
- }
- }
- }
- //停止播放录音
- class stopPlayListener implements OnClickListener{
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- mPlayer.release();
- mPlayer = null;
- }
- }
- }
2.2 main.xml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/hello" />
- <Button
- android:id="@+id/startRecord"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- />
- <Button
- android:id="@+id/stopRecord"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- />
- <Button
- android:id="@+id/startPlay"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- />
- <Button
- android:id="@+id/stopPlay"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- />
- </LinearLayout>
2.3 Manifest.xml
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.cxf"
- android:versionCode="1"
- android:versionName="1.0" >
- <uses-sdk android:minSdkVersion="4" />
- <application
- android:icon="@drawable/ic_launcher"
- android:label="@string/app_name" >
- <activity
- android:name=".RecordActivity"
- android:label="@string/app_name" >
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- </application>
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
- <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
- <uses-permission android:name="android.permission.RECORD_AUDIO" />
- </manifest>
- <?xml version="1.0" encoding="utf-8"?>
- <resources>
- <string name="hello"></string>
- <string name="app_name">Record</string>
- <string name="startRecord">开始录音</string>
- <string name="stopRecord">结束录音</string>
- <string name="startPlay">开始播放</string>
- <string name="stopPlay">结束播放</string>
- </resources>
今天在调用MediaRecorder.stop(),报错了,Java.lang.RuntimeException: stop failed.
- E/AndroidRuntime(7698): Cause by: java.lang.RuntimeException: stop failed.
- E/AndroidRuntime(7698): at android.media.MediaRecorder.stop(Native Method)
- E/AndroidRuntime(7698): at com.tintele.sos.VideoRecordService.stopRecord(VideoRecordService.java:298)
报错代码如下:
- if (mediarecorder != null) {
- mediarecorder.stop();
- mediarecorder.release();
- mediarecorder = null;
- if (mCamera != null) {
- mCamera.release();
- mCamera = null;
- }
- }
stop()方法源代码如下:
- /**
- * Stops recording. Call this after start(). Once recording is stopped,
- * you will have to configure it again as if it has just been constructed.
- * 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.
- *
- * @throws IllegalStateException if it is called before start()
- */
- 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);
改后代码如下:
- if (mediarecorder != null) {
- //added by ouyang start
- try {
- //下面三个参数必须加,不加的话会奔溃,在mediarecorder.stop();
- //报错为:RuntimeException:stop failed
- mediarecorder.setOnErrorListener(null);
- mediarecorder.setOnInfoListener(null);
- mediarecorder.setPreviewDisplay(null);
- mediarecorder.stop();
- } catch (IllegalStateException e) {
- // TODO: handle exception
- Log.i("Exception", Log.getStackTraceString(e));
- }catch (RuntimeException e) {
- // TODO: handle exception
- Log.i("Exception", Log.getStackTraceString(e));
- }catch (Exception e) {
- // TODO: handle exception
- Log.i("Exception", Log.getStackTraceString(e));
- }
- //added by ouyang end
- mediarecorder.release();
- mediarecorder = null;
- if (mCamera != null) {
- mCamera.release();
- mCamera = null;
- }
- }
[Android] 录音与播放录音实现的更多相关文章
- C# 录音和播放录音-NAudio
在使用C#进行录音和播放录音功能上,使用NAudio是个不错的选择. NAudio是个开源,相对功能比较全面的类库,它包含录音.播放录音.格式转换.混音调整等操作,具体可以去Github上看看介绍和源 ...
- MT6737 Android N 平台 Audio系统学习----录音到播放录音流程分析
http://blog.csdn.net/u014310046/article/details/54133688 本文将从主mic录音到播放流程来进行学习mtk audio系统架构. 在AudioF ...
- 【Android】20.4 录音
分类:C#.Android.VS2015: 创建日期:2016-03-13 一.简介 利用Android提供的MediaRecorder类可直接录制音频. 1.权限要求 录制音频和视频需要下面的权限: ...
- AVFoundation之录音及播放
录音 在开始录音前,要把会话方式设置成AVAudioSessionCategoryPlayAndRecord //设置为播放和录音状态,以便可以在录制完之后播放录音 AVAudioSession *s ...
- C# NAudio录音和播放音频文件-实时绘制音频波形图(从音频流数据获取,而非设备获取)
NAudio的录音和播放录音都有对应的类,我在使用Wav格式进行录音和播放录音时使用的类时WaveIn和WaveOut,这两个类是对功能的回调和一些事件触发. 在WaveIn和WaveOut之外还有对 ...
- C# NAudio录音和播放音频文件及实时绘制音频波形图(从音频流数据获取,而非设备获取)
下午写了一篇关于NAudio的录音.播放和波形图的博客,不太满意,感觉写的太乱,又总结了下 NAudio是个相对成熟.开源的C#音频开发工具,它包含录音.播放录音.格式转换.混音调整等功能.本次介绍主 ...
- Android开发教程 录音和播放
首先要了解andriod开发中andriod多媒体框架包含了什么,它包含了获取和编码多种音频格式的支持,因此你几耍轻松把音频合并到你的应用中,若设备支持,使用MediaRecorder APIs便可以 ...
- Android平台下实现录音及播放录音功能的简介
录音及播放的方法如下: package com.example.audiorecord; import java.io.File; import java.io.IOException; import ...
- Android 实时录音和回放,边录音边播放 (KTV回音效果)
上一篇介绍了如何使用Mediarecorder来录音,以及播放录音.不过并没有达到我的目的,一边录音一边播放.今天就讲解一下如何一边录音一边播放.使用AndioRecord录音和使用AudioTrac ...
随机推荐
- js修改剪切板内容的方法
代码如下: //绑定在了body上,也可以绑定在其他可用元素行,但是不是所有元素都支持copy事件. $(document.body).bind({ copy: function(e) {//copy ...
- JSP内置对象——out,get与post
JSP内置对象是Web容器创建的一组对象,不使用new关键字就可以的内置对象.JSP九大内置对象:out,request,response,session,application,page,pageC ...
- java 实现对指定目录的文件进行下载
@RequestMapping("/exportDocument") @ResponseBody public void exportDocument(HttpServletReq ...
- 【BZOJ2792】[Poi2012]Well 二分+双指针法
[BZOJ2792][Poi2012]Well Description 给出n个正整数X1,X2,...Xn,可以进行不超过m次操作,每次操作选择一个非零的Xi,并将它减一. 最终要求存在某个k满足X ...
- python2--升级python3
先安装开发工具包: yum -y group install "Development Tools" 安装Python的依赖包: yum -y install openssl-de ...
- Oracle之rman常用命令及维护(51CTO风哥rman课程)
list 查看数据库备份的信息 查询数据库对应物 list incarnation; list backup summary; 列出当前备份信息及汇总 B是备份 F是全备 A是归档 第三个A是是否有效 ...
- c# 日常记录,(获取系统时间、return),一些文件隐藏无法引用,c#多个窗体之间传值
1.获取系统时间 DateTime.Now.ToString(); DateTime dt =DateTime.Now; dt.AddDays(1); //增加一天 dt.AddDays(-1);// ...
- 巨蟒python全栈开发-第11阶段 devops-git入门1
大纲 1.git命令初识 2.git reset与diff 3.git区域总结 4.git 远程仓库 5.git stash 1.git命令初识 2.git reset与diff 3.git区域总结 ...
- kibana5.6源码分析3--目录结构
kibana5.6的项目目录结构: bin:系统启动脚本目录 config:kibana配置文件目录 data:估计是缓存一些系统数据的,uuid放在这里面 docs: maps:此目录包含TileM ...
- FROM_UNIXTIME(unix_timestamp), FROM_UNIXTIME(unix_timestamp,format)
w SELECT ro.*, FROM_UNIXTIME(ro.wstart,'%Y%m%d') FROM room_order ro
