Writing code that captures videos on Android

http://integratingstuff.com/2010/10/18/writing-code-that-captures-videos-on-android/


Writing code that captures videos on Android

Although the Google guys did a good job on the Android documentation, the explanation on how to write code that captures videos is somewhat short.
In this tutorial, we are going to write an activity that is able to preview, start and stop video capturing, and give more explanation on it than the basic documentation does.
We are going to do this for Android 2.1, but after that, we will discuss differences with 2.2.
Finally, we will be illustrating how the undocumented 2.1 non-public api on MediaRecorder can be called through reflection.
This article is aimed at Android developers.

Setting the permissions

Since we are going to use the camera, the following line will definitely need to be declared in our AndroidManifest file:

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

If we dont specify this, we will get a “Permission Denied” exception as soon as we try to access the camera from our code.

It is good practice to tell the app what features of the camera we are going to use too:

<uses-feature android:name="android.hardware.camera"/>
<uses-feature:name="android.hardware.camera.autofocus"/>

If we dont specify these however, the app will just assume that all camera features are used(camera, autofocus and flash). So to just make it work, we dont need to declare these.

We are also going to record audio during the video capture. So we also declare:

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

Setting up the camera preview

Before we are going to discuss the actual video capturing, we are going to make sure that everything the camera is seeing is previewed to the screen.

Surfaceview is a special type of view that basically gives you a surface to draw too. Its used in various scenarios, such as to draw 2D or 3D objects to, or to play videos.

In this case, we are going to draw the camera input to such a a surfaceview, so the user is able to preview the video/sees what he is recording.

We define a camera_surface.xml layout file in which we setup the surfaceview:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="fill_parent" android:layout_height="fill_parent">
	<SurfaceView android:id="@+id/surface_camera" xmlns:android="http://schemas.android.com/apk/res/android"
		android:layout_width="fill_parent"
		android:layout_height="fill_parent"
		android:layout_centerInParent="true"
		android:layout_weight="1">
	</SurfaceView>
</RelativeLayout>

The following activity will then use the surfaceview in the above layout xml and start rendering the camera input to the screen:

public class CustomVideoCamera extends Activity implements SurfaceHolder.Callback{

	private static final String TAG = "CAMERA_TUTORIAL";

	private SurfaceView surfaceView;
	private SurfaceHolder surfaceHolder;
	private Camera camera;
	private boolean previewRunning;

        @Override
        public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.camera_surface);
                surfaceView = (SurfaceView) findViewById(R.id.surface_camera);
                surfaceHolder = surfaceView.getHolder();
                surfaceHolder.addCallback(this);
                surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }

        @Override
	public void surfaceCreated(SurfaceHolder holder) {
		camera = Camera.open();
		if (camera != null){
			Camera.Parameters params = camera.getParameters();
			camera.setParameters(params);
		}
		else {
			Toast.makeText(getApplicationContext(), "Camera not available!", Toast.LENGTH_LONG).show();
			finish();
		}
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
		if (previewRunning){
			camera.stopPreview();
		}
		Camera.Parameters p = camera.getParameters();
		p.setPreviewSize(width, height);
		p.setPreviewFormat(PixelFormat.JPEG);
		camera.setParameters(p);

		try {
			camera.setPreviewDisplay(holder);
			camera.startPreview();
			previewRunning = true;
		}
		catch (IOException e) {
			Log.e(TAG,e.getMessage());
			e.printStackTrace();
		}
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		camera.stopPreview();
		previewRunning = false;
		camera.release();
	}
}

The main thing we are doing here is implementing a SurfaceHolder.Callback. This callback enables us to intervene when our surface is created, changed(format or size changes) or destroyed. Without this callback, our screen would just remain black.
After the surface is created, we obviously want to display what the camera is seeing. First, we are getting a reference to the camera by calling the static method Camera.open(). We only need to do this once, so we put this in the surfaceCreated method.
The actual start of the preview happens in the surfaceChanged method. This is because this method will not only be called right after surface creation(the first “change”), but also everytime something essential to the surface changes, and we want to stop previewing then, change some parameters and restart the preview. For example, we are using the passed width and height to set the preview size. By putting all of this in the surfaceChanged method, we are making sure our preview always remains consistent with our surface.
When the surface is destroyed(this happens for example at onPause or onDestroy of the activity), we are releasing the camera again, because otherwise other apps, like the native camera app, will start giving “Camera already in use” exceptions.

On a final note,

surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

means the surface is not going to own its buffers, and this surface type is typically used for camera stuff.

Note: Instead of making the activity implement the surface callback, you could also make a class that extends SurfaceView, make that one implement the Callback and use that subclass in the layout xml instead of the SurfaceView. If your activity is getting very long in terms of code, this might be a good thing to do.

Capturing the video

We are now adding the following method to our activity, which will be called when the user decides to start recording:

        private MediaRecorder mediaRecorder;
	private final int maxDurationInMs = 20000;
	private final long maxFileSizeInBytes = 500000;
	private final int videoFramesPerSecond = 20;

	public boolean startRecording(){
		try {
			camera.unlock();

			mediaRecorder = new MediaRecorder();

			mediaRecorder.setCamera(camera);
			mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
			mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

			mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);

			mediaRecorder.setMaxDuration(maxDurationInMs);

			tempFile = new File(getCacheDir(),cacheFileName);
			mediaRecorder.setOutputFile(tempFile.getPath());

			mediaRecorder.setVideoFrameRate(videoFramesPerSecond);
			mediaRecorder.setVideoSize(surfaceView.getWidth(), surfaceView.getHeight());

			mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
			mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);

			mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());

			mediaRecorder.setMaxFileSize(maxFileSizeInBytes);

                        mediaRecorder.prepare();
			mediaRecorder.start();

			return true;
		} catch (IllegalStateException e) {
			Log.e(TAG,e.getMessage());
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			Log.e(TAG,e.getMessage());
			e.printStackTrace();
			return false;
		}
	}

In this method we are preparing the MediaRecorder with all the necessary details.

First, we unlock the camera so we can pass it in a usable state to another process, in this case the recording process. We are doing this in the third line of the code.

Then we are setting all the properties of the MediaRecorder.
Two things are important here.
The order in which the methods are called is the first one. For example, we need to set the sources before setting the encoders and we have to set encoders before calling prepare.
The second important and less documented one, is that ALL properties have to be set. Prepare is a very sensitive and obscure method. The implementation is a native function that just returns an error code in case something goes wrong. So, for example, if you forget to set “maxDuration” on the above mediaRecorder, you will get some obscure “prepare failed” error on most devices, which will not give you any hint at all you didnt set the maxDuration property. Many people assume that these properties are not required at all, and are getting these hard to debug errors.

After preparing the recorder, we start the actual recording.

Stop recording

Then we stop recording in the following method:

public void stopRecording(){
	mediaRecorder.stop();
	camera.lock();
}

which speaks for itself.

Note: To finish the activity, our methods still need to be linked to button actions. We are leaving this to the reader. The easiest way is probably to add stop and start buttons to the layout xml file with the surfaceview, whose onClick attribute points to some action on the activity that calls respectively the startRecording and stopRecording method.

Android 2.1 vs 2.2

At the time of this writing, most Android devices are still running on 2.1 and most developers are aiming their apps to be compatible with 2.1 and above. Which makes sense, if one looks at some Android platform distribution information.

The reference documentation is already updated for 2.2 though.

If we take a look again at the official instructions again,

we notice that we have gone through all the steps mentioned there. We clarified some steps, like “passing a fully initialized SurfaceHolder” and we also took care of the “see Media recorder information” part.

But some things we did different too. We are looking at the 2.2 instructions, and some methods are not yet available in 2.1.
In general, the camera API has been changing/improving at lightning speed. The downside to this is that old apis are getting deprecated very fast and that you cant just use the latest api, since you would seriously hurt your potential number of customers on the market.

Portrait orientation

In 2.2, the setDisplayOrientation method is there, but it isnt in 2.1. Actually, portrait mode for capturing videos through the api is only supported since 2.2, as clearly stated in the New Developer APIs paragraph of Android 2.2 highlights.
So, for our activity, it is necessary to specify

android:screenOrientation="landscape"

Otherwise, it is likely that the camera will have a 90 degrees discrepancy with what the user is seeing(which can be changed by setting the rotation parameter on the camera, but hacking into the code to make the camera work with portrait mode on 2.1 is outside the scope of this tutorial).

Reconnect

Another method that is not there yet in 2.1, so we are obviously not calling it.

PixelFormat.JPEG

This constant, which we are using in our activity above, is already deprecrated in 2.2. But since ImageFormat.JPEG, the suggested replacement, is not there yet in 2.1, we are forced to use the deprecated api.

Calling the undocumented setParameters method on MediaRecorder

In 2.2, there are setters for the properties videoBitrate, audioBitrate, audioChannels and audioSamplingRate onMediaRecorder.
In 2.1, these properties cant be set officially.

If we take a look at the VideoCamera implementation at the android source code, in the 2.1 tree, we find code like:

mMediaRecorder.setParameters(String.format("video-param-encoding-bitrate=%d", mProfile.mVideoBitrate));
mMediaRecorder.setParameters(String.format("audio-param-encoding-bitrate=%d", mProfile.mAudioBitrate));
mMediaRecorder.setParameters(String.format("audio-param-number-of-channels=%d", mProfile.mAudioChannels));
mMediaRecorder.setParameters(String.format("audio-param-sampling-rate=%d", mProfile.mAudioSamplingRate));

Unfortunately, although it is present on all 2.1 devices as far as I know, the setParameters method is not part of the public API, so 2.1 developers are left in the cold there.
Luckily, there is a workaround.

When preparing the MediaRecorder you can add the following lines:

Method[] methods = mediaRecorder.getClass().getMethods();
for (Method method: methods){
	if (method.getName().equals("setParameters")){
		try {
			method.invoke(mediaRecorder, String.format("video-param-encoding-bitrate=%d", 360000));
			method.invoke(mediaRecorder, String.format("audio-param-encoding-bitrate=%d", 23450));
			method.invoke(mediaRecorder, String.format("audio-param-number-of-channels=%d", 1));
			method.invoke(mediaRecorder, String.format("audio-param-sampling-rate=%d",8000));
		} catch (IllegalArgumentException e) {
			Log.e(TAG,e.getMessage());
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			Log.e(TAG,e.getMessage());
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			Log.e(TAG,e.getMessage());
			e.printStackTrace();
		}
	}
}

Through reflection, we are iterating over the available methods on the MediaRecorder. If we find the setParameters method, we invoke the found method for the same effect as in the camera app for the android 2.1 source code.

 

内容概要:本文设计了一种基于PLC的全自动洗衣机控制系统内容概要:本文设计了一种,采用三菱FX基于PLC的全自动洗衣机控制系统,采用3U-32MT型PLC作为三菱FX3U核心控制器,替代传统继-32MT电器控制方式,提升了型PLC作为系统的稳定性与自动化核心控制器,替代水平。系统具备传统继电器控制方式高/低水,实现洗衣机工作位选择、柔和过程的自动化控制/标准洗衣模式切换。系统具备高、暂停加衣、低水位选择、手动脱水及和柔和、标准两种蜂鸣提示等功能洗衣模式,支持,通过GX Works2软件编写梯形图程序,实现进洗衣过程中暂停添加水、洗涤、排水衣物,并增加了手动脱水功能和、脱水等工序蜂鸣器提示的自动循环控制功能,提升了使用的,并引入MCGS组便捷性与灵活性态软件实现人机交互界面监控。控制系统通过GX。硬件设计包括 Works2软件进行主电路、PLC接梯形图编程线与关键元,完成了启动、进水器件选型,软件、正反转洗涤部分完成I/O分配、排水、脱、逻辑流程规划水等工序的逻辑及各功能模块梯设计,并实现了大形图编程。循环与小循环的嵌; 适合人群:自动化套控制流程。此外、电气工程及相关,还利用MCGS组态软件构建专业本科学生,具备PL了人机交互C基础知识和梯界面,实现对洗衣机形图编程能力的运行状态的监控与操作。整体设计涵盖了初级工程技术人员。硬件选型、; 使用场景及目标:I/O分配、电路接线、程序逻辑设计及组①掌握PLC在态监控等多个方面家电自动化控制中的应用方法;②学习,体现了PLC在工业自动化控制中的高效全自动洗衣机控制系统的性与可靠性。;软硬件设计流程 适合人群:电气;③实践工程、自动化及相关MCGS组态软件与PLC的专业的本科生、初级通信与联调工程技术人员以及从事;④完成PLC控制系统开发毕业设计或工业的学习者;具备控制类项目开发参考一定PLC基础知识。; 阅读和梯形图建议:建议结合三菱编程能力的人员GX Works2仿真更为适宜。; 使用场景及目标:①应用于环境与MCGS组态平台进行程序高校毕业设计或调试与运行验证课程项目,帮助学生掌握PLC控制系统的设计,重点关注I/O分配逻辑、梯形图与实现方法;②为工业自动化领域互锁机制及循环控制结构的设计中类似家电控制系统的开发提供参考方案;③思路,深入理解PL通过实际案例理解C在实际工程项目PLC在电机中的应用全过程。控制、时间循环、互锁保护、手动干预等方面的应用逻辑。; 阅读建议:建议结合三菱GX Works2编程软件和MCGS组态软件同步实践,重点理解梯形图程序中各环节的时序逻辑与互锁机制,关注I/O分配与硬件接线的对应关系,并尝试在仿真环境中调试程序以加深对全自动洗衣机控制流程的理解。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值