分类:C#、Android、VS2015;

创建日期:2016-03-13

一、简介

利用Android提供的MediaRecorder类可直接录制音频。

1、权限要求

录制音频和视频需要下面的权限:

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

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

2、基本设计步骤

(1)初始化和录制

录制音频的基本设计步骤如下:

(1) 创建MediaRecorder对象。

(2) 调用SetAudioSource方法指定使用哪个硬件设备捕获音频输入(比如麦克风)。

(3) 调用SetOutputFormat方法指定录音输出文件的格式。

(4) 调用SetAudioEncoder方法设置音频编码类型。

(5) 调用SetOutputFile方法指定输出的音频文件。

(6) 调用Prepare方法初始化录音器。

(7) 调用Start方法开始录音。

下面的代码演示了如何实现:

protected MediaRecorder recorder;

void RecordAudio (String filePath)

{

try {

if (File.Exists (filePath)) {

File.Delete (filePath);

}

if (recorder == null) {

recorder = new MediaRecorder (); // Initial state.

} else {

recorder.Reset ();

recorder.SetAudioSource (AudioSource.Mic);

recorder.SetOutputFormat (OutputFormat.ThreeGpp);

recorder.SetAudioEncoder (AudioEncoder.AmrNb);

// Initialized state.

recorder.SetOutputFile (filePath);

// DataSourceConfigured state.

recorder.Prepare (); // Prepared state

recorder.Start (); // Recording state.

}

} catch (Exception ex) {

Console.Out.WriteLine( ex.StackTrace);

}

}

(2)停止录音

调用MediaRecorder 的Stop方法停止录音:

recorder.Stop();

(3)清除录音占用的资源

一旦停止了MediaRecorder,调用Reset方法将其置于空闲状态(idle state):

recorder.Reset();

当不再使用MediaRecorder实例时,必须释放其占用的资源:

recorder.Release();

二、示例

该例子的功能是录制来自麦克风的音频,如果笔记本带有麦克风,可直接通过模拟器来观察运行效果。录制以后,可直接单击播放按钮测试录制的效果。

这同样也是一个简单的示例,没有考虑录音过程中电话打入的情况,也没有考虑其他复杂的控制。

1、运行截图

2、设计步骤

(1)AndroidManifest.xml文件

在该文件中添加下面的权限(如果有了就不用添加了)。

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

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

(2)添加ch2004Main.axml文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="@+id/ch2004_btnRecStart"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="开始录音" />
<Button
android:id="@+id/ch2004_btnRecStop"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="停止录音" />
<Button
android:id="@+id/ch2004_btnPlayStart"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="播放录音" />
<Button
android:id="@+id/ch2004_btnPlayStop"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="停止播放录音" />
<TextView
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/ch2004_textView1"
android:gravity="center_horizontal"
android:layout_marginTop="30dp" />
</LinearLayout>

(3)添加ch2004MainActivity.cs文件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Media; namespace MyDemos.SrcDemos
{
[Activity(Label = "ch2004MainActivity")]
[IntentFilter(new[] { Intent.ActionMain },
Categories = new[] { Intent.CategoryDefault, ch.MyDemosCategory })]
public class ch2004MainActivity : Activity
{
string filePath;
MediaRecorder recorder;
MediaPlayer player;
Button btnRecStart, btnRecStop, btnPlayStart, btnPlayStop;
TextView textView1; protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.ch2004Main);
//指定SD卡录制的音频文件路径
filePath = string.Format("{0}/{1}/myRecord.mp3",
Android.OS.Environment.ExternalStorageDirectory.Path,
Android.OS.Environment.DirectoryMusic);
textView1 = FindViewById<TextView>(Resource.Id.ch2004_textView1); btnRecStart = FindViewById<Button>(Resource.Id.ch2004_btnRecStart);
btnRecStart.Click += delegate
{
textView1.Text = "正在录音...";
try
{
StartRecorder();
}
catch (Exception ex)
{
Console.Out.WriteLine(ex.StackTrace);
}
}; btnRecStop = FindViewById<Button>(Resource.Id.ch2004_btnRecStop);
btnRecStop.Click += delegate
{
StopRecorder();
textView1.Text = "录音已停止。";
}; btnPlayStart = FindViewById<Button>(Resource.Id.ch2004_btnPlayStart);
btnPlayStart.Click += delegate
{
textView1.Text = "正在播放录音...";
try
{
player = new MediaPlayer();
player.Reset();
player.SetDataSource(filePath);
player.Prepare();
player.Start();
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
}
};
btnPlayStop = FindViewById<Button>(Resource.Id.ch2004_btnPlayStop);
btnPlayStop.Click += delegate
{
player.Stop();
textView1.Text = "播放已停止。";
}; } private void StartRecorder()
{
try
{
if (System.IO.File.Exists(filePath))
{
System.IO.File.Delete(filePath);
}
if (recorder == null)
{
recorder = new MediaRecorder(); // Initial state.
}
else
{
recorder.Reset();
}
recorder.SetAudioSource(AudioSource.Mic); //录制来自麦克风的声音
recorder.SetOutputFormat(OutputFormat.Mpeg4);
recorder.SetAudioEncoder(AudioEncoder.AmrNb);
recorder.SetOutputFile(filePath);
recorder.Prepare();
recorder.Start();
}
catch (Exception ex)
{
Console.Out.WriteLine(ex.StackTrace);
}
} private void StopRecorder()
{
if (recorder != null)
{
recorder.Stop();
recorder.Release();
recorder = null;
}
}
}
}

在模拟器中观察运行的效果,单击【录音】按钮开始录音,录音完毕后,直接单击【播放录音】就可以测试录制效果。

【Android】20.4 录音的更多相关文章

  1. 【Android】【录音】Android录音--AudioRecord、MediaRecorder

    [Android][录音]Android录音--AudioRecord.MediaRecorder Android提供了两个API用于实现录音功能:android.media.AudioRecord. ...

  2. Android 使用MediaRecorder录音

    package com.example.HyyRecord; import android.app.Activity; import android.content.Intent; import an ...

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

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

  4. Android 使用MediaRecorder录音调用stop()方法的时候报错【转】

    本文转载自:http://blog.csdn.net/u014737138/article/details/49738827 这个问题在网上看到了太多的答案,一直提示说按照官网的api的顺序来,其实解 ...

  5. android 20 Intnet类重要的成员变量

    Intnet类重要的成员变量: <intent-filter> <action android:name="android.intent.action.MAIN" ...

  6. [Exception Android 20] - Error:Execution failed for task ':app:processDebugResources'

    Error:Execution failed for task ':app:processDebugResources'. > com.android.ide.common.process.Pr ...

  7. Android 实现电话录音(窃听)

    配置文件 <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android=&qu ...

  8. android中通话录音

    file = new File(Environment.getExternalStorageDirectory(), this.incomeNumber + System.currentTimeMil ...

  9. Android录音应用

    首先是xml布局文件: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xm ...

随机推荐

  1. 字符串的公共前缀对Mysql B+树查询影响回溯分析

        年前项目组接微信公众号. 上线之后,跟微信相关的用cid列的查询会话的SQL变慢了几十倍!思考这个问题思考了非常久.从出现以来一直是我心头的一个结.cid这一列是建了索引的,普通的cid列更新 ...

  2. WebService 之 身份验证

    在项目开发,我们经常会使用WebService,但在使用WebService时我们经常会考虑到了WebService是安全问题,很容易想到通过一组用户名与密码来防止非法用户的调用 . 一.Networ ...

  3. iOS 设置UILabel 的内边距

    iOS 设置UILabel 的内边距 - (void)drawTextInRect:(CGRect)rect { UIEdgeInsets insets = {, , , }; [super draw ...

  4. wepy - 与原生有什么不同(request)

    关于request导入,清先查看这篇文档了解大概 缺陷: wx.request一个页面最多支持10个wx.request,况且不能保证请求先后顺序  对于wepy来说,使用了ES6 的Promise以 ...

  5. iOS——Quartz2D

    0. 复习. 1.基本图形绘制 * 线段(线宽.线段样式) * 矩形(空心.实心.颜色) * 三角形.四边形等形状 1> 说明 - (void)drawRect:(CGRect)rect 什么时 ...

  6. Linux高级权限管理

    传统的UGO(rwx-wx-wx)权限模型,无法解决当多个组需要对一个文件执行某些权限的问题. ACL :访问控制列表access control list一种高级的权限机制,允许我们对文件或者文件夹 ...

  7. 1z0-052 q209_11

    11: Your database instance is started using the server parameter file (SPFILE). You executed a comma ...

  8. Android:Dialog中隐藏键盘的注意事项

    场景:弹出一个Dialog.里面有一个EditText.用来输入内容.由于输入时.须要弹出键盘.所以当Dialog消失时.键盘要一起隐藏. 如今我们做一个自己定义的Dialog MyDialog ex ...

  9. C#时间戳转换[转发]

    http://www.cnblogs.com/qingliuyu/p/3835858.html 以下是C#下的日期与unix时间戳的相互转换: /// <summary> /// 日期转换 ...

  10. QQ概念版(WPF制作)

    984 QQ概念版 编辑   QQ 概念版是腾讯首款NUI(自然用户交互)产品,全面实现了多点触摸操作.是腾讯利用微软最新一代的客户端展现层技术--WPF,打造的IM产品. 中文名 QQ 概念版 游戏 ...