Video pre-loading for Android mediaplayer

Source: Internet
Author: User

This article from http://blog.csdn.net/hellogv/, reference must indicate the source!

This article is based on "Play with Android mediaplayer Media Proxy" to implement a common function of a video client ~~~Pre-Load. To learn the content introduced in this article, we strongly recommend that you read "Play with Android mediaplayer Media Proxy" from a simple perspective, you know.

Pre-loading is divided into two types. This article introduces the "Proxy Server" method:

1. Save and play: Download and play.

Advantage: fast loading and playback, easy to implement; disadvantage: you cannot drag the area not stored; suitable for audio media

2. proxy Server: Download the Media Header in advance (the header size is S1 byte)-> listen to the player request, when the request is a pre-loaded URL-> the proxy returns the media header to the player as response, and changes the ranage to S1 byte to send the request-> the proxy server is purely passthrough.

Advantages: fast loading and playback, supports dragging; disadvantages: complicated implementation; suitable for Video Media

Pre-loading not only shortens the video media loading process, but alsoSegmented stitching"Provide support ...... in layman's terms, IOS players are handsome and rich, supporting two players to play part videos seamlessly. Android players are male and can only play one instance one by one, there is a significant pain point when switching to a video segment ...... pre-loading can shorten the pause time.

First, let's take a look at the pre-loading effect. The pre-loading duration of 1420 MS is 2633 ms, and the pre-loading duration of the video is ms:

========================================================== ========================================================== ============================

 

The source code of this article can be downloaded at http://download.csdn.net/detail/hellogv/4486051. the mp4search used in this article is based on Baidu ....

Httpgetproxy. Java is the core of this article. The main implementation of the proxy server is as follows:

/*** Proxy server class ** @ author hellogv **/public class httpgetproxy {final static Public String tag = "httpgetproxy "; /** port with Link */private int remoteport =-1;/** remote server address */private string remotehost; /** port used by the proxy server */private int localport;/** local server address */private string localhost; private serversocket localserver = NULL; /** socket */private socket sckplayer = NULL for sending and receiving Media Player requests;/** socket for sending and receiving Media Server requests */PRI Vate socket sckserver = NULL; private socketaddress address;/** download thread */private downloadthread download = NULL; /*** initialize the proxy server ** @ Param localport the port listened by the proxy server */Public httpgetproxy (INT localport) {try {localport = localport; localhost = C. local_ip_address; localserver = new serversocket (localport, 1, inetaddress. getbyname (localhost);} catch (exception e) {system. exit (0) ;}}/*** download the URL to the SD card in advance to implement pre-loading * @ para M urlstring * @ return the preload file name * @ throws exception */Public String prebuffer (string urlstring, int size) throws exception {If (download! = NULL & download. isdownloading () download. stopthread (true); Uri tmpuri = new uri (urlstring); string filename = proxyutils. urltofilename (tmpuri. getpath (); string filepath = C. getbufferdir () + "/" + filename; download = new downloadthread (urlstring, filepath, size); download. startthread (); Return filepath;}/*** convert the network URL to a local URL, and replace 127.0.0.1 with the network domain name ** @ Param URL network URL * @ return [0]: MP4 real URL after redirection, [1]: local URL */Public String [] Ge Tlocalurl (string urlstring) {// ---- exclude HTTP special ---- // string TargetUrl = proxyutils. getredirecturl (urlstring); // ---- obtain the link of the local proxy server ---- // string localurl = NULL; Uri originaluri = Uri. create (TargetUrl); remotehost = originaluri. gethost (); If (originaluri. getport ()! =-1) {// URL with portaddress = new inetsocketaddress (remotehost, originaluri. getport (); // use the default port remoteport = originaluri. getport (); // Save the port. Replace localurl = TargetUrl in transit. replace (remotehost + ":" + originaluri. getport (), localhost + ":" + localport);} else {// URL without portaddress = new inetsocketaddress (remotehost, C. http_port); // use port 80 remoteport =-1; localurl = TargetUrl. replace (remotehost, localhost + ":" + Localport);} string [] result = new string [] {TargetUrl, localurl}; return result ;} /*** start Proxy Server asynchronously ** @ throws ioexception */Public void asynstartproxy () {New thread () {public void run () {startproxy ();}}. start ();} private void startproxy () {httpparser = NULL; int bytes_read; Boolean enableprebuffer = false; // The byte [] local_request = new byte [1024]; byte [] remote_reply = new byte [1024]; while (tru E) {Boolean hasresponseheader = false; try {// disable the past socketif (sckplayer! = NULL) sckplayer. Close (); If (sckserver! = NULL) sckserver. close ();} catch (ioexception E1) {} Try {// ---------------------------------------- // listen for mediaplayer requests, mediaplayer-> Proxy Server // listen sckplayer = localserver. accept (); log. E ("tag", "------------------------------------------------------------------"); If (download! = NULL & download. isdownloading () download. stopthread (false); httpparser = new httpparser (remotehost, remoteport, localhost, localport); proxyrequest request = NULL; while (bytes_read = sckplayer. getinputstream (). read (local_request ))! =-1) {byte [] buffer = httpparser. getrequestbody (local_request, bytes_read); If (buffer! = NULL) {request = httpparser. getproxyrequest (buffer); break;} Boolean isexists = new file (request. _ prebufferfilepath ). exists (); enableprebuffer = isexists & request. _ isreqrange0; // both of them can use the preload log. E (TAG, "enableprebuffer:" + enableprebuffer); senttoserver (request. _ body); // -------------------------------------------------------- // send the network server feedback to the mediaplayer, network server-> Proxy Server-> mediaplayer //------------------------------- ----------------------- Boolean enablesendheader = true; while (bytes_read = sckserver. getinputstream (). Read (remote_reply ))! =-1) {byte [] tmpbuffer = new byte [bytes_read]; system. arraycopy (remote_reply, 0, tmpbuffer, 0, tmpbuffer. length); If (hasresponseheader) {sendtomp (tmpbuffer);} else {list <byte []> httpresponse = httpparser. getresponsebody (remote_reply, bytes_read); If (httpresponse. size ()> 0) {hasresponseheader = true; If (enablesendheader) {// send HTTP header to mediaplayersendtomp (httpresponse. get (0); string responsestr = ne W string (httpresponse. get (0); log. E (TAG + "<---", responsestr);} If (enableprebuffer) {// send prebuffer to mediaplayerint filebuffersize = sendprebuffertomp (request. _ prebufferfilepath); If (filebuffersize> 0) {// resend the request to the server string newrequeststr = httpparser. modifyrequestrange (request. _ body, filebuffersize); log. E (TAG + "-Pre->", newrequeststr); enableprebuffer = false; // do not process HTTP headersenttoser of response next time Ver (newrequeststr); enablesendheader = false; hasresponseheader = false; Continue ;}// send the remaining data if (httpresponse. size () = 2) {sendtomp (httpresponse. get (1) ;}}} log. E (TAG ,"......... over .......... "); // close two socketsckplayers. close (); sckserver. close ();} catch (exception e) {log. E (TAG, E. tostring (); log. E (TAG, proxyutils. getexceptionmessage (E) ;}} private int sendprebuffertomp (string filename) throws ioexcepti On {int filebuffersize = 0; byte [] file_buffer = new byte [1024]; int bytes_read = 0; fileinputstream finputstream = new fileinputstream (filename); While (bytes_read = finputstream. read (file_buffer ))! =-1) {filebuffersize + = bytes_read; byte [] tmpbuffer = new byte [bytes_read]; system. arraycopy (file_buffer, 0, tmpbuffer, 0, bytes_read); sendtomp (tmpbuffer);} finputstream. close (); log. E (TAG, "Read completed... download: "+ download. getdownloadedsize () + ", read:" + filebuffersize); Return filebuffersize;} private void sendtomp (byte [] bytes) throws ioexception {sckplayer. getoutputstream (). write (bytes); sckplayer. getoutputstream (). FL Ush ();} private void senttoserver (string requeststr) throws ioexception {try {If (sckserver! = NULL) sckserver. close () ;}catch (exception ex) {}sckserver = new socket (); sckserver. connect (Address); sckserver. getoutputstream (). write (requeststr. getbytes (); // send the mediaplayer request sckserver. getoutputstream (). flush ();}}

 

 

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.