Simple video player using videoview

Source: Internet
Author: User

The videoview is encapsulated in the mediaplayer. Android framework and provides the videoview class to encapsulate mediapalyer. This videoview class is very useful. The gallery of Android is also implemented using videoview. In contrast, it is easier to use. The mediaplayer. oncompletionlistener interface will be notified when video broadcasting is complete. In this example, a simple program is ended as follows:

An immature player, http://www.eoemarket.com/soft/370334.html, is being completed.

Import android. app. activity; import android. content. context; import android. content. intent; import android. content. PM. activityinfo; import android. content. res. configuration; import android. media. audiomanager; import android.net. uri; import android. OS. bundle; import android. OS. environment; import android. OS. handler; import android. OS. message; import android. text. textutils; import android. view. display; import and Roid. view. gesturedetector. simpleongesturelistener; import android. view. gesturedetector; import android. view. motionevent; import android. view. view; import android. view. viewgroup; import android. view. windowmanager; import android. widget. imageview; public class videoplayeractivity extends activity implements oncompletionlistener {private string mpath; private string mtitle; private videoview mvideoview; privat E view mvolumebrightnesslayout; private imageview moperationbg; private imageview moperationpercent; private audiomanager maudiomanager;/** maximum sound */private int mmaxvolume; /** current sound */private int mvolume =-1;/** current brightness */private float mbrightness =-1f; /** current scaling mode */private int mlayout = videoview. video_layout_zoom; private gesturedetector mgesturedetector; private mediacontroller mmediacontroller; @ override Public void oncreate (bundle icicle) {super. oncreate (icicle); intent = getintent (); mpath = intent. getstringextra ("path"); mtitle = intent. getstringextra ("title"); If (textutils. isempty (mpath) mpath = environment. getexternalstoragedirectory () + "/Video/you are crazy. FLV "; else if (intent. getdata ()! = NULL) mpath = intent. getdata (). tostring (); setcontentview (R. layout. videoview); mvideoview = (videoview) findviewbyid (R. id. surface_view); mvolumebrightnesslayout = findviewbyid (R. id. operation_volume_brightness); moperationbg = (imageview) findviewbyid (R. id. operation_bg); moperationpercent = (imageview) findviewbyid (R. id. operation_percent); maudiomanager = (audiomanager) getsystemservice (context. audio_ser Vice); mmaxvolume = maudiomanager. getstreammaxvolume (audiomanager. stream_music); If (mpath. startswith ("http:") mvideoview. setvideouri (URI. parse (mpath); elsemvideoview. setvideopath (mpath); // mvideoview. setoncompletionlistener (this); mmediacontroller = new mediacontroller (this); // set the display name mmediacontroller. setfilename (mtitle); mvideoview. setmediacontroller (mmediacontroller); mvideoview. requestfocus (); mgesture Detector = new gesturedetector (this, new mygesturelistener (); listener (activityinfo. Listener) ;}@ overrideprotected void onpause () {super. onpause (); If (mvideoview! = NULL) mvideoview. Pause () ;}@ overrideprotected void onresume () {super. onresume (); If (mvideoview! = NULL) mvideoview. Resume () ;}@ overrideprotected void ondestroy () {super. ondestroy (); If (mvideoview! = NULL) mvideoview. stopplayback () ;}@ overridepublic Boolean ontouchevent (motionevent event) {If (mgesturedetector. ontouchevent (event) return true; // process the gesture to end the switch (event. getaction () & motionevent. action_mask) {Case motionevent. action_up: endgesture (); break;} return Super. ontouchevent (event);}/** gesture end */private void endgesture () {mvolume =-1; mbrightness =-1f; // hide mdismisshandler. removemessages (0); mdism Isshandler. sendemptymessagedelayed (0,500);} private class mygesturelistener extends simpleongesturelistener {/** double-click */@ overridepublic Boolean ondoubletap (motionevent e) {If (mlayout = videoview. video_layout_zoom) mlayout = videoview. video_layout_origin; elsemlayout ++; If (mvideoview! = NULL) mvideoview. setvideolayout (mlayout, 0); Return true;}/** slide */@ overridepublic Boolean onscroll (motionevent E1, motionevent E2, float distancex, float distancey) {float moldx = e1.getx (), moldy = e1.gety (); int y = (INT) e2.getrawy (); display disp = getwindowmanager (). getdefadisplay display (); int login wwidth = Disp. getwidth (); int returns wheight = Disp. getheight (); If (moldx> descriwwidth * 4.0/5) // slide to the right Dynamic onvolumeslide (moldy-y)/windowheight); else if (moldx <symbol wwidth/5.0) // slide onbrightnessslide (moldy-y)/windowheight) on the left; return Super. onscroll (E1, E2, distancex, distancey) ;}/ ** timed hide */private handler mdismisshandler = new handler () {@ overridepublic void handlemessage (Message MSG) {mvolumebrightnesslayout. setvisibility (view. gone) ;}};/*** slide to change the sound size ** @ Param percent */private void onvol Umeslide (float percent) {If (mvolume =-1) {mvolume = maudiomanager. getstreamvolume (audiomanager. stream_music); If (mvolume <0) mvolume = 0; // displays moperationbg. setimageresource (R. drawable. video_volumn_bg); mvolumebrightnesslayout. setvisibility (view. visible);} int Index = (INT) (percent * mmaxvolume) + mvolume; If (index> mmaxvolume) Index = mmaxvolume; else if (index <0) Index = 0; // change the audio maudiomanager. s Etstreamvolume (audiomanager. stream_music, index, 0); // change the progress bar viewgroup. layoutparams Lp = moperationpercent. getlayoutparams (); LP. width = findviewbyid (R. id. operation_full ). getlayoutparams (). width * index/mmaxvolume; moperationpercent. setlayoutparams (LP);}/*** slide to change brightness ** @ Param percent */private void onbrightnessslide (float percent) {If (mbrightness <0) {mbrightness = getwindow (). getattributes (). SC Reenbrightness; If (mbrightness <= 0.00f) mbrightness = 0.50f; If (mbrightness <0.01f) mbrightness = 0.01f; // display moperationbg. setimageresource (R. drawable. video_brightness_bg); mvolumebrightnesslayout. setvisibility (view. visible);} windowmanager. layoutparams LPA = getwindow (). getattributes (); LPA. screenbrightness = mbrightness + percent; If (LPA. screenbrightness> 1.0f) LPA. screenbrightness = 1.0f; else if (L Pa. screenbrightness <0.01f) LPA. screenbrightness = 0.01f; getwindow (). setattributes (LPA); viewgroup. layoutparams Lp = moperationpercent. getlayoutparams (); LP. width = (INT) (findviewbyid (R. id. operation_full ). getlayoutparams (). width * LPA. screenbrightness); moperationpercent. setlayoutparams (LP) ;}@ overridepublic void onconfigurationchanged (configuration newconfig) {If (mvideoview! = NULL) mvideoview. setvideolayout (mlayout, 0); Super. onconfigurationchanged (newconfig) ;}@ overridepublic void oncompletion (mediaplayer player) {finish ();}}

Videoview is a media playback display and Control control provided by the Android system. Its structure is as follows:

Prototype: videoview extendsSurfaceviewImplements mediacontroller.Mediaplayercontrol

Class Structure:

Java. Lang. Object
? Android. View. View
? Android. View. surfaceview
? Android. widget. videoview

Based on the videoview prototype, we can see that if you build a more complex and distinctive Video View,Surfaceview must be inherited and mediaplayercontrol interfaces must be implemented.. Surfaceview supports display and mediaplayercontrol supports media control.


Core playback class:
import android.app.Activity;import android.os.Bundle;import android.os.Environment;import android.util.Log;import android.view.SurfaceHolder;import android.view.SurfaceView;public class PlayerActivity extends Activity implements OnBufferingUpdateListener, OnCompletionListener, OnPreparedListener, OnVideoSizeChangedListener, SurfaceHolder.Callback {private static final String TAG = "MediaPlayerDemo";private int mVideoWidth;private int mVideoHeight;private MediaPlayer mMediaPlayer;private SurfaceView mPreview;private SurfaceHolder holder;private String path = Environment.getExternalStorageDirectory() + "/Moon.mp4";private boolean mIsVideoSizeKnown = false;private boolean mIsVideoReadyToBePlayed = false;@Overridepublic void onCreate(Bundle icicle) {super.onCreate(icicle);setContentView(R.layout.mediaplayer);mPreview = (SurfaceView) findViewById(R.id.surface);holder = mPreview.getHolder();holder.addCallback(this);}private void playVideo() {doCleanUp();try {mMediaPlayer = new MediaPlayer(this);mMediaPlayer.setDataSource(path);mMediaPlayer.setDisplay(holder);mMediaPlayer.prepareAsync();mMediaPlayer.setScreenOnWhilePlaying(true);mMediaPlayer.setOnBufferingUpdateListener(this);mMediaPlayer.setOnCompletionListener(this);mMediaPlayer.setOnPreparedListener(this);mMediaPlayer.setOnVideoSizeChangedListener(this);} catch (Exception e) {Log.e(TAG, "error: " + e.getMessage(), e);}}@Override  public void onBufferingUpdate(MediaPlayer arg0, int percent) {Log.d(TAG, "onBufferingUpdate percent:" + percent);}@Override  public void onCompletion(MediaPlayer arg0) {Log.d(TAG, "onCompletion called");mMediaPlayer.release();}@Override  public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {Log.v(TAG, "onVideoSizeChanged called");if (width == 0 || height == 0) {Log.e(TAG, "invalid video width(" + width + ") or height(" + height + ")");return;}mIsVideoSizeKnown = true;mVideoWidth = width;mVideoHeight = height;if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {startVideoPlayback();}}@Override  public void onPrepared(MediaPlayer mediaplayer) {Log.d(TAG, "onPrepared called");mIsVideoReadyToBePlayed = true;if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {startVideoPlayback();}}@Override  public void surfaceChanged(SurfaceHolder surfaceholder, int i, int j, int k) {Log.d(TAG, "surfaceChanged called" + i + "  " + j + "   " + k);}@Override  public void surfaceDestroyed(SurfaceHolder surfaceholder) {Log.d(TAG, "surfaceDestroyed called");}@Override  public void surfaceCreated(SurfaceHolder holder) {Log.d(TAG, "surfaceCreated called");playVideo();}@Overrideprotected void onPause() {super.onPause();releaseMediaPlayer();doCleanUp();}@Overrideprotected void onDestroy() {super.onDestroy();releaseMediaPlayer();doCleanUp();}private void releaseMediaPlayer() {if (mMediaPlayer != null) {mMediaPlayer.release();mMediaPlayer = null;}}private void doCleanUp() {mVideoWidth = 0;mVideoHeight = 0;mIsVideoReadyToBePlayed = false;mIsVideoSizeKnown = false;}private void startVideoPlayback() {Log.v(TAG, "startVideoPlayback");holder.setFixedSize(mVideoWidth, mVideoHeight);mMediaPlayer.start();}}



Simple video player using videoview

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.