Android video playback-surfaceview and MediaPlayer

Source: Internet
Author: User

For several days did not write a blog, handling a bit of personal affairs with the usual overtime, basically time is not abundant, on the article said a bit with MediaPlayer to play music, this time on the use of MediaPlayer to and Surfaceview play with a video streaming media. MediaPlayer not only can play video, but also with the Surfaceview, Surfaceview is mainly used to display MediaPlayer playback of video streaming media screen rendering, the two can play together video.

Basic Maintenance

First look at the interface you want to implement:

If you read the previous article, it is actually very simple is a more progress bar, there is a surfaceview, is the following black area;

Layout file Code:

<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:orien tation= "vertical" tools:context= "com.example.googlevideo.MainActivity" > <edittext android:id= "@+id/edi T_musicpath "android:layout_width=" match_parent "android:layout_height=" wrap_content "android:hint=" output Into the MV path "/> <seekbar android:id=" @+id/seekbar_video "android:layout_width=" Match_parent "Android oid:layout_height= "Wrap_content"/> <linearlayout android:layout_width= "Match_parent" android:layou t_height= "wrap_content" android:orientation= "horizontal" > <button android:id= "@+id/btn_pla Y "android:layout_width=" wrap_content "android:layout_height=" Wrap_content "android:oncli ck= "Playevent" android:text= "Play"/&GT <button android:id= "@+id/btn_pause" android:layout_width= "Wrap_content" android:layout            _height= "Wrap_content" android:onclick= "pauseevent" android:text= "Pause"/> <button Android:id= "@+id/btn_stop" android:layout_width= "wrap_content" android:layout_height= "Wrap_cont Ent "android:onclick=" stopevent "android:text=" Stop "/> <button android:id=" @+ Id/btn_replay "android:layout_width=" wrap_content "android:layout_height=" Wrap_content "a ndroid:onclick= "Replayevent" android:text= "Replay"/> </LinearLayout> <surfaceview Android : id= "@+id/surface_video" android:layout_width= "match_parent" android:layout_height= "Match_parent"/></ Linearlayout>
Demo Implementation

before the implementation of the demo should talk about the principle of video playback, first determine the format of the video, this and decoding related, different formats of video coding, and then through the encoding format for decoding, and finally get a frame of the image, and these images quickly displayed in the interface, that is, to play a video. Surfaceview is doing this in Android. Surfaceview is used in conjunction with MediaPlayer, MediaPlayer also provides the appropriate method to set the Surfaceview display picture, only need to specify MediaPlayer display image for Surfaceview. Its full signature:void Setdisplay (Surfaceholder sh). It needs to pass a Surfaceholder object, Surfaceholder can be understood as Surfaceview loading a container that needs to display a frame image, which can be Surfaceholder.getholder () method is obtained. The steps to play a video with MediaPlayer with Surfaceview are roughly consistent with playback using MediaPlayer playback MP3, with the additional settings shown for Surfaceview.

Prepare a video that can be played first:

Play Video:

The code is as follows:

EditText = (editText) Findviewbyid (R.id.edit_musicpath); pathstring = Edittext.gettext (). toString (). Trim (); File File = new file (pathstring), if (File.exists ()) {try {mediaPlayer = new MediaPlayer (); Mediaplayer.setaudiostreamtype (Audiomanager.stream_music); Mediaplayer.setdatasource (pathstring);// Holdermediaplayer.setdisplay (holder) obtained through Surfaceview; Mediaplayer.prepare (); Mediaplayer.start (); btn_ Playbutton.setenabled (false);//Set bar's maximum value int max=mediaplayer.getduration (); Seekbarvideo.setmax (max);// Timer Update progress bar timer=new timer (); timetask=new TimerTask () {@Overridepublic void Run () {//TODO auto-generated method Stubseekba Rvideo.setprogress (Mediaplayer.getcurrentposition ());}; Timer.schedule (timetask, 0, 500);//reset display after video playback mediaplayer.setoncompletionlistener (new Oncompletionlistener () {@  overridepublic void Oncompletion (MediaPlayer MP) {//TODO auto-generated method Stubbtn_playbutton.setenabled (True);}});} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}} else {TOAST.MAketext (This, "Sorry, the path you entered has a problem, please check carefully", toast.length_short). Show (); 

Use of Seekbar:

Set bar's maximum value int max=mediaplayer.getduration (); Seekbarvideo.setmax (max);//Timer Update progress bar timer=new  timer (); timetask= New TimerTask () {@Overridepublic void Run () {//TODO auto-generated method Stubseekbarvideo.setprogress ( Mediaplayer.getcurrentposition ());}; Timer.schedule (timetask, 0, 500);

Where holder is Surfaceholder, obtained in OnCreate:

Surfaceview = (Surfaceview) Findviewbyid (r.id.surface_video); holder = Surfaceview.getholder ();// Compatible with the mobile version after 4.0, itself is not maintained holder.settype (surfaceholder.surface_type_push_buffers);

If the video is being played, it will have a sound when minimized, and it needs to be handled in the callback function:

Holder.addcallback (New Callback () {@Overridepublic void surfacedestroyed (Surfaceholder holder) {//TODO auto-generated Method STUBLOG.I (Tag, "destroyed Holder"); if (mediaplayer!=null&&mediaplayer.isplaying ()) {currentposition= Mediaplayer.getcurrentposition (); Mediaplayer.stop (); Mediaplayer.release (); Mediaplayer=null;timer.cancel (); Timetask.cancel (); timer=null;timetask=null;}} @Overridepublic void surfacecreated (Surfaceholder holder) {//TODO auto-generated method STUBLOG.I (tag, "created Holder"); (currentposition>0) {try {mediaPlayer = new MediaPlayer (); Mediaplayer.setaudiostreamtype (Audiomanager.stream_music); Mediaplayer.setdatasource (pathstring);//Holdermediaplayer.setdisplay acquired through Surfaceview (holder); Mediaplayer.prepare (); Mediaplayer.start (); Mediaplayer.seekto (currentposition); btn_playbutton.setenabled (false) ///After the video has been played, reset the display Mediaplayer.setoncompletionlistener (new Oncompletionlistener () {@Overridepublic void oncompletion ( MediaPlayer MP) {//TODO auto-generated method stubbtn_playbutton.sEtenabled (True);}}); int max=mediaplayer.getduration (); Seekbarvideo.setmax (max);//Timer Update progress bar timer=new timer (); timetask=new TimerTask () {@ overridepublic void Run () {//TODO auto-generated method Stubseekbarvideo.setprogress (Mediaplayer.getcurrentposition ( ));}}; Timer.schedule (timetask, 0, 500);}  catch (Exception e) {//Todo:handle Exception}}} @Overridepublic void Surfacechanged (surfaceholder holder, int format, int Width,int height) {//TODO auto-generated method STUBLOG.I (tag, "changed Holder");});

The progress bar is Seekbar, and it is necessary to assign the focus value to MediaPlayer if it is necessary to fast-forward or backward:

seekbarvideo= (SeekBar) Findviewbyid (R.id.seekbar_video); Seekbarvideo.setonseekbarchangelistener (new Onseekbarchangelistener () {@Overridepublic void Onstoptrackingtouch (SeekBar SeekBar) {//TODO auto-generated method Stubint position=seekbar.getprogress (); if (mediaplayer!=null&&mediaplayer.isplaying ()) { Mediaplayer.seekto (position);}} @Overridepublic void Onstarttrackingtouch (SeekBar SeekBar) {//TODO auto-generated method stub} @Overridepublic void Onprogresschanged (SeekBar SeekBar, int progress,boolean fromuser) {//TODO auto-generated Method stub}});

Pause Event:

public void pauseevent (view view) {if (Btn_pausebutton.gettext (). Equals ("continue")) {Mediaplayer.start (); btn_ Pausebutton.settext ("pause"); return;} if (MediaPlayer! = null && mediaplayer.isplaying ()) {mediaplayer.pause (); Btn_pausebutton.settext ("Continue");}}

Stop event:

public void stopevent (view view) {if (MediaPlayer! = null && mediaplayer.isplaying ()) {btn_playbutton.setenabled (true); Mediaplayer.stop ();//Release MediaPlayer otherwise it will consume memory mediaplayer.release (); mediaPlayer = null;} Btn_pausebutton.settext ("pause"); btn_playbutton.setenabled (true);}

Replay Event:

public void replayevent (view view) {surfaceview.setvisibility (view.visible); if (mediaPlayer! = null && Mediaplayer.isplaying ()) {mediaplayer.seekto (0);} else {playevent (view);} The playback status should be set when replaying btn_playbutton.setenabled (true);}

Android video playback-surfaceview and MediaPlayer

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.