Android audio and video recording mediarecorder usage example

Source: Internet
Author: User

Mediarecorder enables recording and recording.

Mediarecorder official instructions:

Http://developer.android.com/reference/android/media/MediaRecorder.html

When using mediarecorder for recording videos, you must strictly abide by the function call sequence in the API instructions. Otherwise, the video cannot be executed successfully.

The following is an example of video recording using mediarecorder.

This program can be normally recorded on the Qualcomm msm7225 platform's  u8500 2.2 version. However, Lenovo a750 on the mtk mt6575 platform cannot run properly and video recording cannot be implemented.

The video can be recorded on the Zhan Xun 8810 2.3.5 platform, but there is no sound to play. You can view the video data through mediainfo, but it cannot be played on the PC, it may be a problem during recording.

It can be seen that the program recorded through camera has a strong dependence on the platform and hardware, and the same program varies greatly on different mobile phones.

1. Activity Class

Public class mainactivity extends activity implements surfaceholder. callback {Private Static final string tag = "mainactivity"; private surfaceview msurfaceview; private button mbtnstartstop; private Boolean mstartedflg = false; private mediarecorder mrecorder; private surfaceholder msurfaceholder; @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); requestwin Dowfeature (window. feature_no_title); // remove the title bar getwindow (). setflags (windowmanager. layoutparams. flag_fullscreen, windowmanager. layoutparams. flag_fullscreen); // sets full screen // sets setrequestedorientation (activityinfo. screen_orientation_landscape); // select semi-transparent mode, which is used in a surfaceview activity. Getwindow (). setformat (pixelformat. translucent); setcontentview (R. layout. activity_main); msurfaceview = (surfaceview) findviewbyid (R. id. surfaceview); mbtnstartstop = (button) findviewbyid (R. id. btnstartstop); mbtnstartstop. setonclicklistener (New onclicklistener () {@ overridepublic void onclick (view v) {// todo auto-generated method stubif (! Mstartedflg) {// startif (mrecorder = NULL) {mrecorder = new mediarecorder (); // create mediarecorder} Try {// set audio and video source and Encoder // these two items need to be placed before setoutputformat mrecorder. setaudiosource (mediarecorder. audiosource. camcorder); mrecorder. setvideosource (mediarecorder. videosource. camera); // set output file formatmrecorder. setoutputformat (mediarecorder. outputformat. three_gpp); // these two items need to be placed in setou Mrecorder after tputformat. setaudioencoder (mediarecorder. audioencoder. amr_nb); mrecorder. setvideoencoder (mediarecorder. videoencoder. h263); mrecorder. setvideosize (320,240); mrecorder. setvideoframerate (20); mrecorder. setpreviewdisplay (msurfaceholder. getsurface (); // set output file path string Path = getsdpath (); If (path! = NULL) {file dir = new file (path + "/recordtest"); If (! Dir. exists () {dir. mkdir ();} Path = dir + "/" + getdate () + ". 3GP "; mrecorder. setoutputfile (PATH); log. D (TAG, "BF mrecorder. prepare () "); mrecorder. prepare (); log. D (TAG, "af mrecorder. prepare () "); log. D (TAG, "BF mrecorder. start () "); mrecorder. start (); // recording is now started log. D (TAG, "af mrecorder. start () "); mstartedflg = true; mbtnstartstop. settext ("stop"); log. D (TAG, "Start recording... ") ;} Catch (exception e) {e. printstacktrace () ;}} else {// stopif (mstartedflg) {try {log. D (TAG, "stop recording... "); log. D (TAG, "BF mrecorder. stop ("); mrecorder. stop (); log. D (TAG, "af mrecorder. stop ("); mrecorder. reset (); // You can reuse the object by going back to setaudiosource () Step mbtnstartstop. settext ("START");} catch (exception e) {e. printstacktrace () ;}} mstartedflg = false; // set button s Tatus flag }}); surfaceholder holder = msurfaceview. getholder (); // get Holder. addcallback (this); // The callback interface added by holder // settype must be set to avoid errors. holder. settype (surfaceholder. surface_type_push_buffers);}/*** obtain the system time * @ return */public static string getdate () {calendar CA = calendar. getinstance (); int year = Ca. get (calendar. year); // obtain the year int month = Ca. get (calendar. month); // obtain the month int day = Ca. get (calen Dar. date); // get the day int minute = Ca. get (calendar. minute); // minute int hour = Ca. get (calendar. hour); // hour int second = Ca. get (calendar. second); // second string date = "" + year + (month + 1) + day + hour + minute + second; log. D (TAG, "date:" + date); return date;}/*** get SD path * @ return */Public String getsdpath () {file sddir = NULL; boolean sdcardexist = environment. getexternalstoragestate (). equals (Android Oid. OS. environment. media_mounted); // determines whether the SD card exists if (sdcardexist) {sddir = environment. getexternalstoragedirectory (); // get the return sddir directory. tostring () ;}return null ;}@ overridepublic void surfacechanged (surfaceholder holder, int format, int width, int height) {// todo auto-generated method stub // change holder, this holder is the holder obtained in oncreate and is assigned to msurfaceholder = holder; log. D (TAG, "Surface Changed 1 ") ;}@ overridepublic void surfacecreated (surfaceholder holder) {// todo auto-generated method stub // set holder, which is the holder that is obtained in oncreate, grant it to msurfaceholder = holder; log. D (TAG, "surfacechanged 2") ;}@ overridepublic void surfacedestroyed (surfaceholder holder) {// todo auto-generated method stub // when surfacedestroyed is used, the object is set to null msurfaceview = NULL; msurfaceholder = NULL; if (Mrecorder! = NULL) {mrecorder. Release (); // now the object cannot be reused mrecorder = NULL; log. D (TAG, "surfacedestroyed release mrecorder ");}}}

2. layout File

The layout file only has one surface for displaying the recorded video and one button for controlling the start and end.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"     android:orientation="horizontal">    <SurfaceView  android:id="@+id/surfaceview"  android:layout_weight="1" android:layout_width="0dip"  android:layout_height="fill_parent" />         <Button        android:id="@+id/btnStartStop"        android:layout_width="55dip"        android:layout_height="wrap_content"        android:layout_gravity="center"        android:text="Start"        tools:context=".MainActivity" /></LinearLayout>

3. add permissions to the manifest File

You need to add permissions to use camera, mic, and SD card. The Code is as follows:

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

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.