Android Local video player version Mediaplay

Source: Internet
Author: User
Tags try catch

This article is a custom video player that can be switched on screen (the computer is separated due to changes in size when changing the screen), such as:







--------------Play Video Summary:

2 Ways of Surfaceview+mediaplayer and Videoview

There is a surfaceholder in the Surfaceview, which is obtained through the Surfaceview.getholder () method, plus settype if a compatible 2.3 system is required (surfaceholder.surface_type_ Push_buffers); otherwise only the sound has no image. There are 3 life cycles surfacecreated, surfacechanged, surfacedestroyed.

Read 2 methods in raw directory

Uri.parse ("android.resource://" + getpackagename () + "/" + R.raw.video));

ASSETFILEDESCRIPTORAFD = Getresources (). OPENRAWRESOURCEFD (

R.raw.por);

Mp_test.setdatasource (Afd.getfiledescriptor (),

Afd.getstartoffset (), afd.getlength ());

Afd.close ();

Set app theme without title

@android: Style/theme.light.notitlebar

Activity restart due to shielding change

Android:configchanges= "Keyboard|orientation|screensize"

Set the screen to solid

GetWindow (). Clearflags (WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

Set activity direction to portrait

android:screenorientation= "Portrait"

Gets whether the current screen is a horizontal screen or a vertical screen

Getresources (). GetConfiguration (). Orientation

Manually switch the screen

Setrequestedorientation (Activityinfo.screen_orientation_landscape);

Monitor the action of the toggle screen

Onconfigurationchanged

Code-behind title

Requestwindowfeature (window.feature_no_title); (Must be before setcontent)

Code request full-screen mode

GetWindow (). Addflags (WindowManager.LayoutParams.FLAG_FULLSCREEN);

Code Clear Full Screen mode

GetWindow (). Clearflags (WindowManager.LayoutParams.FLAG_FULLSCREEN);

Adapt to different video sizes to achieve the effect of non-stretch videos

Setvideoparms method, calculated based on the proportions of the video and the scale of the display area

Write 2 sets of controls in a set of layouts to fit the screen

Proper use of LinearLayout's weight attribute for adaptation

Use Audiomanager to adjust system system volume

Seekbar initialization, monitoring when changing

Broadcast is emitted when the system volume changes

Android.media.VOLUME_CHANGED_ACTION Monitor System Volume change

Seekbar Monitor if Fromuser,mediaplayer note try

The flag of the current activity add, when the activity leaves, it will clear out


-------------Project Code videoactivity class:

/** * Play Video Page * * @author Hasee * */public class Videoactivity extends Activity implements Onpreparedlistener,onseekbarchan Gelistener {private MediaPlayer mediaplayer;private surfaceview sv_video;private relativelayout rl_top;private Button bt_start_or_pause;//Play or pause button private SeekBar sb_progress;//video progress bar ImageView Mchangesceen;imageview Mcenterpause; LinearLayout Mllmenu; LinearLayout mlltitle;private SeekBar sb_vol;//Volume progress bar private Audiomanager am;private int currentposition;// Record current progress value @overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);// Double buffered Setcontentview (R.layout.activity_video); Initview (); InitData ();} private void Initview () {Sv_video = (Surfaceview) Findviewbyid (r.id.sv_video); bt_start_or_pause = (Button) Findviewbyid (r.id.bt_start_or_pause); rl_top = (relativelayout) Findviewbyid (r.id.rl_top); sb_progress = (SeekBar) findViewById ( r.id.sb_progress); Sb_vol = (SeekBar) Findviewbyid (R.id.sb_vol); mchangesceen= (ImageView) Findviewbyid (r.id.bt_ Change); mcenterpause= (ImageView) Findviewbyid (r.id.video_center_pause); mllmenu= (LinearLayout) Findviewbyid (R.id.video_ menu); mlltitle= (LinearLayout) Findviewbyid (r.id.video_menu_title);//Sv_video.getholder (). SetType ( Surfaceholder.surface_type_push_buffers)////compatible with versions 2.3 and below, otherwise only the sound does not have a picture Sv_video.getholder (). Addcallback (New Callback () {@Overridepublic void surfacecreated (Surfaceholder holder) {//PlayVideo () when the page is visible;} @Overridepublic void surfacedestroyed (Surfaceholder holder) {//When the page is not visible stopvideo ();} @Overridepublic void Surfacechanged (surfaceholder holder, int format, int width, int height) {}});} private void InitData () {registerreceiver (Volreceiver, New Intentfilter ("Android.media.VOLUME_CHANGED_ACTION")); am = (Audiomanager) Getsystemservice (context.audio_service);//Keep the screen solid GetWindow (). Addflags ( WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); Sb_vol.setmax (Am.getstreammaxvolume (Audiomanager.stream_music) ); Sb_vol.setprogress (Am.getstreamvolume (Audiomanager.stream_music)); Sb_progress.setonseekbaRchangelistener (this); Sb_vol.setonseekbarchangelistener (this);} private void PlayVideo () {mediaPlayer = new mediaPlayer (); try {//Get the file under the raw directory//assetfiledescriptor afd = getresources (). O PENRAWRESOURCEFD (//R.raw.por);//Mediaplayer.setdatasource (Afd.getfiledescriptor (), 0,//afd.getLength ());// Get the files under the raw directory Mediaplayer.setdatasource (this, Uri.parse ("android.resource://" + getpackagename () + "/" + r.raw.test)); Mediaplayer.setlooping (True); Mediaplayer.setonpreparedlistener (this); Mediaplayer.setdisplay (Sv_video.getHolder ()); Mediaplayer.prepareasync ();} catch (Exception e) {e.printstacktrace ();}} private void Stopvideo () {canprogress = False;if (MediaPlayer! = null && mediaplayer.isplaying ()) {try {Currentpos ition = Mediaplayer.getcurrentposition (); Mediaplayer.pause (); Mediaplayer.stop (); Mediaplayer.release (); MediaPlayer = null;} catch (Exception e) {}} @Overridepublic void Onprepared (MediaPlayer MP) {//Description MediaPlayer prepared try {Sb_progress.setmax ( Mp.getduration ()); SetParam (MP, Island ()); MP. Start (); if (currentposition > 0) {mp.seekto (currentposition); currentposition = 0;} Startprogress ();} catch (Exception e) {}}/** * Determines whether the current horizontal screen * * @return */private Boolean Island () {if (Getresources (). GetConfiguration (). Orient ation = = configuration.orientation_portrait) {return false;} else {return true;}} @Overridepublic void onconfigurationchanged (Configuration newconfig) {super.onconfigurationchanged (newconfig); Newconfig.orientation = = configuration.orientation_portrait) {log.e ("pid", "vertical screen"); SetParam (MediaPlayer, false); GetWindow (). Clearflags (WindowManager.LayoutParams.FLAG_FULLSCREEN);} else if (newconfig.orientation = = Configuration.orientation_landscape) {log.e ("pid", "Horizontal screen"),//Remove status bar GetWindow (). Addflags (WindowManager.LayoutParams.FLAG_FULLSCREEN); SetParam (MediaPlayer, True);}} /** * Set Video size to achieve non-stretched effect * * @param MP * @param island */private void SetParam (MediaPlayer MP, Boolean Island) {float screen Width = Getwindowmanager (). Getdefaultdisplay (). getwidth (); float screenheight = SCReenwidth/16f * 9F;IF (island) {screenheight = Getwindowmanager (). Getdefaultdisplay (). GetHeight ();} float Videowdith = Mp.getvideowidth (); Float videoheight = Mp.getvideoheight (); Float Screenpor = Screenwidth/screenheigh t;//16:9float Videopor = videowdith/videoheight;//9:16viewgroup.layoutparams pa = sv_video.getlayoutparams (); if (vide Opor <= screenpor) {pa.height = (int) screenheight;pa.width = (int) (screenheight * videopor);} else {pa.width = (int) Screenwidth;pa.height = (int) (SCREENWIDTH/VIDEOPOR);} Viewgroup.layoutparams Rl_pa = Rl_top.getlayoutparams (); rl_pa.width = Pa.width;rl_pa.height = Pa.height;rl_ Top.setlayoutparams (RL_PA); Sv_video.setlayoutparams (PA);}  Private Boolean canprogress = True;private void Startprogress () {canprogress = True;new Thread () {public void run () {while (canprogress) {try {sleep ($); Sb_progress.setprogress (Mediaplayer.getcurrentposition ());} catch (Exception e) {}}};}. Start ();} @Overrideprotected void OnDestroy () {Super.ondestroy (); UnregisterrEceiver (volreceiver);} @Overridepublic void onprogresschanged (SeekBar SeekBar, int progress, Boolean fromuser) {if (!fromuser) return;switch (SE Ekbar.getid ()) {case R.id.sb_progress:try {if (mediaPlayer! = null) {Mediaplayer.seekto (progress);}} catch (Exception e) {}break;case R.id.sb_vol:am.setstreamvolume (audiomanager.stream_music, progress,audiomanager.flag_show_ui); ;}} @Overridepublic void Onstarttrackingtouch (SeekBar SeekBar) {} @Overridepublic void Onstoptrackingtouch (SeekBar SeekBar {}/** * System volume changes when the broadcast receiver */private broadcastreceiver volreceiver = new Broadcastreceiver () {@Overridepublic void OnReceive ( Context context, Intent Intent) {sb_vol.setprogress (Am.getstreamvolume (Audiomanager.stream_music));}}; public void OnClick (View v) {switch (V.getid ()) {case R.id.bt_start_or_pause:try {if (Bt_start_or_pause.gettext (). Equals ("Play")) {//is currently playing, then pause Mediaplayer.pause ();//canprogress = False;bt_start_or_pause.settext ("pause"); Mcenterpause.setvisibility (view.visible);} else if (bt_start_or_pause.gettext (). Equals ("pause")) {//is currently paused, then play Mediaplayer.start ();//canprogress = True;bt_start_or_pause.settext (" Play "); Mcenterpause.setvisibility (View.gone);}} catch (Exception e) {}break;case r.id.bt_change://clicked on the vertical and horizontal screen switch to get the current screen orientation if (getresources (). GetConfiguration (). Orientation = = configuration.orientation_portrait) {//Current is vertical screen, toggle Cheng setrequestedorientation (activityinfo.screen_ Orientation_landscape);} else {//is currently a horizontal screen, switch to vertical screen setrequestedorientation (activityinfo.screen_orientation_portrait);} Break;case R.id.video_center_pause:try {if (Bt_start_or_pause.gettext () equals ("Play")) {//is currently playing, Then pause Mediaplayer.pause ();//canprogress = False;bt_start_or_pause.settext ("pause");} else if (Bt_start_or_pause.gettext () equals ("pause")) {//is currently paused, then play Mediaplayer.start ();//canprogress = True;bt_start_ Or_pause.settext ("Play");}} catch (Exception e) {}mcenterpause.setvisibility (view.gone); break;}} /** timed Hide */private Handler mdismisshandler = new Handler () {@Overridepublic void Handlemessage (Message msg) {MLLMENU.SETVI SibIlity (View.gone); mlltitle.setvisibility (View.gone); Auto-hide of title bar}}; @Overridepublic Boolean ontouchevent (Motionevent event) {if (Event.getaction () ==motionevent.action_  Down) {mllmenu.setvisibility (view.visible); mlltitle.setvisibility (view.visible); Title bar display}mdismisshandler.sendemptymessagedelayed (0,3000); return super.ontouchevent (event);}}
-----------------------activity_video.xml Layout:

<?xml version= "1.0" encoding= "Utf-8"? ><relativelayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Match_parent "android:layout_height=" match_parent "android:background=" #fff "&G    T <relativelayout android:id= "@+id/rl_top" android:layout_width= "Match_parent" android:layout_height = "Match_parent" android:background= "#000" > <linearlayout android:id= "@+id/video_menu_title "Android:layout_width=" match_parent "android:layout_height=" 50DP "android:visibility=" Go                Ne "android:background=" #000 "> <textview android:textcolor=" #fff " Android:layout_width= "Match_parent" android:layout_height= "Match_parent" android:gravity= " Center "android:text=" video title "/> </LinearLayout> <surfaceview android:id=            "@+id/sv_video"android:layout_below= "@+id/video_menu_title" android:layout_width= "Match_parent" Android:layout_heig ht= "300dip" android:layout_centerinparent= "true"/> <imageview android:id= "@+id/video_c Enter_pause "android:onclick=" OnClick "android:layout_width=" 100DP "android:layout_height = "100DP" android:layout_centerinparent= "true" android:visibility= "Gone" android:src= "@dra Wable/video_pause "/> <linearlayout android:id=" @+id/video_menu "Android:layout_width=" M Atch_parent "android:layout_height=" 50DP "android:background=" #000 "android:visibility=" G One "android:orientation=" horizontal "android:layout_alignparentbottom=" true "> <but ton android:id= "@+id/bt_start_or_pause" android:layout_width= "60DP" android:l     ayout_height= "50DP"           android:text= "Play" android:onclick= "OnClick"/> <seekbar Android:id= "@+id/sb_progress" android:layout_width= "0dip" android:layout_height= "50di                P "android:layout_weight=" 3 "android:indeterminate=" false "/> <seekbar                 Android:id= "@+id/sb_vol" android:layout_width= "0dip" android:layout_height= "50dip"                android:layout_weight= "1"/> <imageview android:id= "@+id/bt_change"                Android:layout_width= "40DP" android:layout_height= "40DP" android:onclick= "OnClick" android:src= "@drawable/changescreen"/> </LinearLayout> </relativelayout></relat Ivelayout>

Note The androidmanifest manifest file is added to the activity:

<span style= "FONT-SIZE:18PX;" >  android:configchanges= "keyboard|orientation|screensize" </span>

Create the Raw folder in the Res file and paste it in test. MP4 file playback.

Since Google has stopped updating the version of Eclipse, I use the Android Studio software development, project attention point Image:



Mainactivity class and there is no code, mainly to provide developers a page of their own projects, and then in the inside with intent jump to videoactivity.class on it, want the project to leave me a message.


Summarize:

  1. note points for video playback:
    1. Sub-thread to change the video progress bar
    2. Note where the try catch operates on the MediaPlayer (including the camera in the custom camera)
    3. Remember Surfaceview three life cycle methods, each time after minimizing, back to play, are already not the same holder
    4. Get the video aspect ratio and screen width to height ratio, then you can determine how to stretch the video based on the width or height of the screen without causing distortion
    5. mediaplayer release :
        1. First pause
        2. stop
        3. re-release
        4. reset empty
        5. This is the safest
        1. to be in Androidmanifest.xml Configure the activity of the video
      1. Use the broadcast to listen for the corresponding volume changes, because sometimes we use the volume keys or change the volume in the settings
      2. Assetfiledescriptor classes that can be used to read raw files

The native mechanism of 2,mediaplayer:

A. Because many of the methods in MediaPlayer, such as the IsPlaying () method, are written by the JNI mechanism, its GC recovery mechanism is different from the usual method. Therefore, it is very easy to have an illegal stack exception and so on, so it is better to add a trycatch for processing.

B. Internal is the native method, this native method, in the case of not necessarily, theGC will be recycled, so do not know when the call will jump out of a IllegalStateException exception


Android Local video player version Mediaplay

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.