我的Android进阶之旅------>Android视频录制小例子
============================首先看看官网上关于视频捕捉的介绍================================
Capturing videos
Video capture using the Android framework requires careful management of the Camera
object
and coordination with the MediaRecorder
class.
When recording video with Camera
,
you must manage the Camera.lock()
andCamera.unlock()
calls
to allow MediaRecorder
access
to the camera hardware, in addition to the Camera.open()
and Camera.release()
calls.
Note: Starting with Android 4.0 (API level 14), the Camera.lock()
and Camera.unlock()
calls
are managed for you automatically.
Unlike taking pictures with a device camera, capturing video requires a very particular call order. You must follow a specific order of execution to successfully prepare for and capture video with your application, as detailed below.
- Open Camera - Use the
Camera.open()
to
get an instance of the camera object. - Connect Preview - Prepare a live camera image preview by connecting a
SurfaceView
to
the camera usingCamera.setPreviewDisplay()
. - Start Preview - Call
Camera.startPreview()
to
begin displaying the live camera images. - Start Recording Video - The following steps must be completed in order to successfully record video:
- Unlock the Camera - Unlock the camera for use by
MediaRecorder
by
callingCamera.unlock()
. - Configure MediaRecorder - Call in the following
MediaRecorder
methods in
this order. For more information, see theMediaRecorder
reference
documentation.setCamera()
-
Set the camera to be used for video capture, use your application's current instance ofCamera
.setAudioSource()
-
Set the audio source, useMediaRecorder.AudioSource.CAMCORDER
.setVideoSource()
-
Set the video source, useMediaRecorder.VideoSource.CAMERA
.- Set the video output format and encoding. For Android 2.2 (API Level 8) and higher, use the
MediaRecorder.setProfile
method,
and get a profile instance usingCamcorderProfile.get()
.
For versions of Android prior to 2.2, you must set the video output format and encoding parameters:setOutputFormat()
-
Set the output format, specify the default setting orMediaRecorder.OutputFormat.MPEG_4
.setAudioEncoder()
-
Set the sound encoding type, specify the default setting orMediaRecorder.AudioEncoder.AMR_NB
.setVideoEncoder()
-
Set the video encoding type, specify the default setting orMediaRecorder.VideoEncoder.MPEG_4_SP
.
setOutputFile()
-
Set the output file, usegetOutputMediaFile(MEDIA_TYPE_VIDEO).toString()
from the example method in the Saving
Media Files section.setPreviewDisplay()
-
Specify theSurfaceView
preview
layout element for your application. Use the same object you specified for Connect Preview.
Caution: You must call these
MediaRecorder
configuration
methods in this order, otherwise your application will encounter errors and the recording will fail. - Prepare MediaRecorder - Prepare the
MediaRecorder
with
provided configuration settings by callingMediaRecorder.prepare()
. - Start MediaRecorder - Start recording video by calling
MediaRecorder.start()
.
- Unlock the Camera - Unlock the camera for use by
- Stop Recording Video - Call the following methods in order, to successfully complete a video recording:
- Stop MediaRecorder - Stop recording video by calling
MediaRecorder.stop()
. - Reset MediaRecorder - Optionally, remove the configuration settings from the recorder by calling
MediaRecorder.reset()
. - Release MediaRecorder - Release the
MediaRecorder
by
callingMediaRecorder.release()
. - Lock the Camera - Lock the camera so that future
MediaRecorder
sessions
can use it by callingCamera.lock()
.
Starting with Android 4.0 (API level 14), this call is not required unless theMediaRecorder.prepare()
call
fails.
- Stop MediaRecorder - Stop recording video by calling
- Stop the Preview - When your activity has finished using the camera, stop the preview using
Camera.stopPreview()
. - Release Camera - Release the camera so that other applications can use it by calling
Camera.release()
.
Note: It is possible to use MediaRecorder
without
creating a camera preview first and skip the first few steps of this process. However, since users typically prefer to see a preview before starting a recording, that process is not discussed here.
Tip: If your application is typically used for recording video, set setRecordingHint(boolean)
to true
prior
to starting your preview. This setting can help reduce the time it takes to start recording.
============================再看看官网上关于音频捕捉的介绍================================
Audio Capture
The Android multimedia framework includes support for capturing and encoding a variety of common audio formats, so that you can easily integrate audio into your applications. You can record audio using the MediaRecorder
APIs
if supported by the device hardware.
This document shows you how to write an application that captures audio from a device microphone, save the audio and play it back.
Note: The Android Emulator does not have the ability to capture audio, but actual devices are likely to provide these capabilities.
Performing Audio Capture
Audio capture from the device is a bit more complicated than audio and video playback, but still fairly simple:
- Create a new instance of
android.media.MediaRecorder
. - Set the audio source using
MediaRecorder.setAudioSource()
.
You will probably want to useMediaRecorder.AudioSource.MIC
. - Set output file format using
MediaRecorder.setOutputFormat()
. - Set output file name using
MediaRecorder.setOutputFile()
. - Set the audio encoder using
MediaRecorder.setAudioEncoder()
. - Call
MediaRecorder.prepare()
on
the MediaRecorder instance. - To start audio capture, call
MediaRecorder.start()
. - To stop audio capture, call
MediaRecorder.stop()
. - When you are done with the MediaRecorder instance, call
MediaRecorder.release()
on
it. CallingMediaRecorder.release()
is
always recommended to free the resource immediately.
下面就看看该小例子的代码吧。
文件1.该应用的布局文件,res/layout/main.xml
<!-- 帧布局 -->
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"> <!-- 用来展示画面 -->
<SurfaceView android:id="@+id/surfaceView"
android:layout_width="fill_parent" android:layout_height="fill_parent" /> <!-- 相对布局,该界面默认不显示出来,当触摸屏幕时候显示出来 -->
<RelativeLayout android:layout_width="fill_parent"
android:layout_height="fill_parent" android:visibility="gone"
android:id="@+id/buttonlayout">
<!-- 刻录按钮 -->
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_alignParentRight="true"
android:layout_alignParentBottom="true" android:layout_marginRight="10dp"
android:text="@string/recoderbutton" android:onClick="recoder"
android:id="@+id/recoderbutton" />
<!-- 停止按钮 -->
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_toLeftOf="@id/recoderbutton"
android:layout_alignTop="@id/recoderbutton" android:layout_marginRight="30dp"
android:text="@string/stopbutton" android:onClick="stop"
android:id="@+id/stopbutton"
android:enabled="false"/>
</RelativeLayout>
</FrameLayout>
文件2:布局文件所用到的资源文件,res/values/string.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, RecoderActivity!</string>
<string name="app_name">视频刻录小例子</string>
<string name="recoderbutton">刻录</string>
<string name="stopbutton">停止</string>
<string name="noSDcard">检测到手机没有存储卡!请插入手机存储卡再开启本应用</string>
<string name="maxDuration">已经达到最长录制时间</string>
</resources>
文件3:该应用的主程序,RecoderActivity.java
package cn.oyp.recoder; import java.io.File; import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.media.MediaRecorder;
import android.media.MediaRecorder.OnInfoListener;
import android.os.Bundle;
import android.os.Environment;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast; public class RecoderActivity extends Activity {
// 用来显示图片
private SurfaceView surfaceView;
// 刻录和停止按钮布局
private RelativeLayout buttonlayout;
// 刻录按钮
private Button recoderbutton;
// 停止按钮
private Button stopbutton;
// 媒体刻录对象
private MediaRecorder mediaRecorder; /** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 窗口特效为无标题
requestWindowFeature(Window.FEATURE_NO_TITLE);
// 设置窗口全屏
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
// 设定屏幕显示为横向
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setContentView(R.layout.main); buttonlayout = (RelativeLayout) this.findViewById(R.id.buttonlayout);
recoderbutton = (Button) this.findViewById(R.id.recoderbutton);
stopbutton = (Button) this.findViewById(R.id.stopbutton); surfaceView = (SurfaceView) this.findViewById(R.id.surfaceView);
// 获取的画面直接输出到屏幕上
surfaceView.getHolder()
.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
// 画面分辨率
surfaceView.getHolder().setFixedSize(176, 144);
// 保持屏幕高亮
surfaceView.getHolder().setKeepScreenOn(true);
} // 点击刻录按钮处理方法
public void recoder(View v) {
try {
// 判断是否存在SD卡
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
// 将刻录的视频保存到SD卡中
File videoFile = new File(
Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".3gp");
mediaRecorder = new MediaRecorder();
// 设置声音采集来源于麦克风
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
// 设置视频采集来源于摄像头
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
// 设置输出格式为3gp
mediaRecorder
.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
// 设置视频尺寸
mediaRecorder.setVideoSize(surfaceView.getWidth(),
surfaceView.getHeight());
// 设置每秒钟捕捉画面个数为5帧
mediaRecorder.setVideoFrameRate(5);
// 设置声音编码
mediaRecorder
.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
// 设置视频编码
mediaRecorder.setAudioEncoder(MediaRecorder.VideoEncoder.H264);
// 设置视频的最大持续时间
mediaRecorder.setMaxDuration(10000);
mediaRecorder.setOnInfoListener(new OnInfoListener() {
@Override
public void onInfo(MediaRecorder mr, int what, int extra) {
if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED) {
Toast.makeText(getApplicationContext(),
R.string.maxDuration, Toast.LENGTH_LONG)
.show();
if (mediaRecorder != null) {
mediaRecorder.stop();
mediaRecorder.release();
mediaRecorder = null;
}
}
}
});
// 设置刻录的视频保存路径
mediaRecorder.setOutputFile(videoFile.getAbsolutePath());
// 设置预览显示
mediaRecorder.setPreviewDisplay(surfaceView.getHolder()
.getSurface());
// 预期准备
mediaRecorder.prepare();
// 开始刻录
mediaRecorder.start();
} else {
Toast.makeText(getApplicationContext(), R.string.noSDcard,
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
// 刻录按钮不可点击
recoderbutton.setEnabled(false);
// 停止按钮可点击
stopbutton.setEnabled(true);
} // 点击停止按钮处理方法
public void stop(View v) {
// 停止刻录,并释放资源
if (mediaRecorder != null) {
mediaRecorder.stop();
mediaRecorder.release();
mediaRecorder = null;
}
// 刻录按钮可点击
recoderbutton.setEnabled(true);
// 停止按钮不可点击
stopbutton.setEnabled(false);
} /** 当触摸屏幕的时候,将对焦和拍照按钮布局显示出来 */
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
buttonlayout.setVisibility(ViewGroup.VISIBLE);
return true;
}
return super.onTouchEvent(event);
} }
文件4:该应用的描述文件 ,AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cn.oyp.recoder" android:versionCode="1" android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" /> <!-- 摄像头权限 -->
<uses-permission android:name="android.permission.CAMERA" />
<!-- 录制音频权限 -->
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<!-- 在SD卡中创建和删除文件权限 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<!-- 往SD卡中写入数据的权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".RecoderActivity" android:label="@string/app_name"
android:screenOrientation="landscape">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity> </application>
</manifest>
=================================================================================================
作者:欧阳鹏 欢迎转载,与人分享是进步的源泉!
转载请保留原文地址:http://blog.csdn.net/ouyang_peng
==================================================================================================
我的Android进阶之旅------>Android视频录制小例子的更多相关文章
- 我的Android进阶之旅------>Android颜色值(#AARRGGBB)透明度百分比和十六进制对应关系以及计算方法
我的Android进阶之旅-->Android颜色值(RGB)所支持的四种常见形式 透明度百分比和十六进制对应关系表格 透明度 十六进制 100% FF 99% FC 98% FA 97% F7 ...
- 我的Android进阶之旅------>Android中查看应用签名信息
一.查看自己的证书签名信息 如上一篇文章<我的Android进阶之旅------>Android中制作和查看自定义的Debug版本Android签名证书>地址:http://blog ...
- 我的Android进阶之旅------>Android利用温度传感器实现带动画效果的电子温度计
要想实现带动画效果的电子温度计,需要以下几个知识点: 1.温度传感器相关知识. 2.ScaleAnimation动画相关知识,来进行水印刻度的缩放效果. 3.android:layout_weight ...
- 我的Android进阶之旅------>Android实现用Android手机控制PC端的关机和重启的功能(三)Android客户端功能实现
我的Android进阶之旅------>Android实现用Android手机控制PC端的关机和重启的功能(一)PC服务器端(地址:http://blog.csdn.net/ouyang_pen ...
- 我的Android进阶之旅------> Android为TextView组件中显示的文本添加背景色
通过上一篇文章 我的Android进阶之旅------> Android在TextView中显示图片方法 (地址:http://blog.csdn.net/ouyang_peng/article ...
- 我的Android进阶之旅------> Android在TextView中显示图片方法
面试题:请说出Android SDK支持哪些方式显示富文本信息(不同颜色.大小.并包含图像的文本信息),并简要说明实现方法. 答案:Android SDK支持如下显示富文本信息的方式. 1.使用Tex ...
- 我的Android进阶之旅------>Android疯狂连连看游戏的实现之实现游戏逻辑(五)
在上一篇<我的Android进阶之旅------>Android疯狂连连看游戏的实现之加载界面图片和实现游戏Activity(四)>中提到的两个类: GameConf:负责管理游戏的 ...
- 我的Android进阶之旅------>Android疯狂连连看游戏的实现之加载界面图片和实现游戏Activity(四)
正如在<我的Android进阶之旅------>Android疯狂连连看游戏的实现之状态数据模型(三)>一文中看到的,在AbstractBoard的代码中,当程序需要创建N个Piec ...
- 我的Android进阶之旅------>Android疯狂连连看游戏的实现之状态数据模型(三)
对于游戏玩家而言,游戏界面上看到的"元素"千变万化:但是对于游戏开发者而言,游戏界面上的元素在底层都是一些数据,不同数据所绘制的图片有所差异而已.因此建立游戏的状态数据模型是实现游 ...
- 我的Android进阶之旅------>Android疯狂连连看游戏的实现之开发游戏界面(二)
连连看的游戏界面十分简单,大致可以分为两个区域: 游戏主界面区 控制按钮和数据显示区 1.开发界面布局 本程序使用一个RelativeLayout作为整体的界面布局元素,界面布局上面是一个自定义组件, ...
随机推荐
- Java过滤器(Filter)与SpringMVC拦截器(Interceptor)之间的关系与区别
过滤器和拦截器的区别: ①拦截器是基于java的反射机制的,而过滤器是基于函数回调. ②拦截器不依赖与servlet容器,过滤器依赖与servlet容器. ③拦截器只能对action请求起作用,而过滤 ...
- Windows无法删除文件 提示找不到该项目怎么办
1 如图所示,我想要删除某个文件,提示如图所示,一般用360的强力删除也不管用. 2 在桌面新建一个文本文档,并输入以下内容.保存为bat格式(比如Delete.bat).然后把这个删不掉的文件拖 ...
- gitlab创建项目代码:
cd (当前工程文件夹目录) git init //初始化git git remote add origin http://worker.njbandou.com/KLElevator/kle ...
- 通过Navicat for MySQL远程连接的时候报错mysql 1130 的解决方法
用Navicat连接远程MYSQL,提示如下错误,我以为是自己的防火墙问题,但是关了,依然不行. ERROR 1130: Host '192.168.1.3' is not allowed to co ...
- python 搭建环境
直接命令行里面 1.进入相应的目录 ,然后python,然后python setup.py 2.或者直接python C:\Python27\Lib\site-packages\xlrd-0.9.3\ ...
- Acceptor-Connector模式一(Acceptor的工作)V2.0
前言:ACE Acceptor-Connector模式 首先这样的模式肯定是面向连接的TCP/IP协议. 无论是什么场景.差点儿面向连接的通信程序总是由一端主动发起连接,一端监听等待对方的连接. 这就 ...
- UE4射击小游戏原型
尝试使用了下blueprint,不知道是bug还是不熟悉,blueprint有些地方运行的跟逻辑不太一样.不管ue4目前,快速做原型倒是蛮方便的.就等着官方发更多教程讲述关于新的matinee,Nav ...
- git 4种对象的理解
git中有四种基本对象类型,可以说Git的所有操作都是通过这四种对象完成的.下图是<Git版本控制管理>中文第二版的原话,顺便吐槽一下,这本书真的翻译的一般.. 下面说下我的理解吧,首先b ...
- struts2中怎样处理404?
眼下在做一个网络应用程序,struts2 + spring + hibernate,server是tomcat.希望用户在IE地址栏乱敲的时候.所敲入的全部没有定义的URL都能被程序捕捉到,然后转到一 ...
- ps选框工具全解
我们每次选择工具的时候,ps上面都会变成特定的选项,比如说下面这些: 比如说选区工具的话就分为新选区.添加选区.交叉选区之类的,这些都是需要在实战中练习的. 不单单是选区有这个工具,其他的也有这个功能 ...