最近在做Android视频播放的有关项目,其中有一项需求就是要求视频可以边加载缓存边播放,类似于优酷土豆的视频点播。网上找了一些相关的资料,比较了每种视频格式的优缺点之后,结合Android手机自身的优势,默认支持mp4编码和解码,最终采用mp4格式作为视频的存储格式。
其实最真实的流媒体协议传输格式并不是普通的http方式,而是rtsp,那样的话得搭建专门的流媒体服务器,成本比较高,采用普通的http方式,实现的是一种伪流媒体传输,但是对于常用的视频缓存播放也足够了。
要想实现视频的边缓存边播放,原则上就要求视频的存储格式是分段的,而mp4正好满足这个要求,只要将mp4的整体视频信息放在mp4文件的开头,这样只要加载了mp4文件的头部之后,就能解析出该mp4文件的时长,比特率等等,为后续的视频缓存做初始化设置,然后每加载一段mp4文件的数据流,通过解析头部来或得当前视频流的帧信息,并在播放器中播放,这样就能先加载一段进行播放,同时缓存后续的一段,依此原理就能实现。
本文的目的就是给大家介绍一种以此原理而开发一个Android视频边缓存边播放的示例,通过该示例的学习,相信大家能对该原理有更深入的理解。
在介绍具体的demo之前,先放上几张截图,分别为视频播放前的缓存,视频边缓存边播放,缓存完毕的视频播放。
代码解析
VideoViewDemo.java 主要是用来设置启动参数,设定网络视频的url地址和本地缓存的地址,本地缓存的地址可以不设置,程序会自己维护,如果您自己设置了,视频就会缓存到该位置。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | public class VideoViewDemo extends Activity { @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); //String url = "http://carey-blog-image.googlecode.com/files/vid_20120510_090204.mp4"; String url = "http://bbfile.b0.upaiyun.com/data/videos/2/vid_20120510_090204.mp4"; Intent intent = new Intent(); intent.setClass(VideoViewDemo.this, BBVideoPlayer.class); intent.putExtra("url", url); intent.putExtra("cache", Environment.getExternalStorageDirectory().getAbsolutePath() + "/VideoCache/" + System.currentTimeMillis() + ".mp4"); startActivity(intent); } } |
public class VideoViewDemo extends Activity { @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); //String url = "http://carey-blog-image.googlecode.com/files/vid_20120510_090204.mp4"; String url = "http://bbfile.b0.upaiyun.com/data/videos/2/vid_20120510_090204.mp4"; Intent intent = new Intent(); intent.setClass(VideoViewDemo.this, BBVideoPlayer.class); intent.putExtra("url", url); intent.putExtra("cache", Environment.getExternalStorageDirectory().getAbsolutePath() + "/VideoCache/" + System.currentTimeMillis() + ".mp4"); startActivity(intent); } }
BBVideoPlayer.java 就是视频缓存的核心了,READYBUFF定义了初始缓存区的大小,当视频加载到初始缓存区满的时候,播放器开始播放,CACHEBUFF则是核心交换缓存区,主要是用来动态调节缓存区,当网络环境较好的时候,该缓存区为初始大小,当网络环境差的时候,该缓存区会动态增加,主要就是为了避免视频播放的时候出现一卡一卡的现象。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 | public class BBVideoPlayer extends Activity { private VideoView mVideoView; private TextView tvcache; private String remoteUrl; private String localUrl; private ProgressDialog progressDialog = null; private static final int READY_BUFF = 2000 * 1024; private static final int CACHE_BUFF = 500 * 1024; private boolean isready = false; private boolean iserror = false; private int errorCnt = 0; private int curPosition = 0; private long mediaLength = 0; private long readSize = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.bbvideoplayer); findViews(); init(); playvideo(); } private void findViews() { this.mVideoView = (VideoView) findViewById(R.id.bbvideoview); this.tvcache = (TextView) findViewById(R.id.tvcache); } private void init() { Intent intent = getIntent(); this.remoteUrl = intent.getStringExtra("url"); System.out.println("remoteUrl: " + remoteUrl); if (this.remoteUrl == null) { finish(); return; } this.localUrl = intent.getStringExtra("cache"); mVideoView.setMediaController(new MediaController(this)); mVideoView.setOnPreparedListener(new OnPreparedListener() { public void onPrepared(MediaPlayer mediaplayer) { dismissProgressDialog(); mVideoView.seekTo(curPosition); mediaplayer.start(); } }); mVideoView.setOnCompletionListener(new OnCompletionListener() { public void onCompletion(MediaPlayer mediaplayer) { curPosition = 0; mVideoView.pause(); } }); mVideoView.setOnErrorListener(new OnErrorListener() { public boolean onError(MediaPlayer mediaplayer, int i, int j) { iserror = true; errorCnt++; mVideoView.pause(); showProgressDialog(); return true; } }); } private void showProgressDialog() { mHandler.post(new Runnable() { @Override public void run() { if (progressDialog == null) { progressDialog = ProgressDialog.show(BBVideoPlayer.this, "视频缓存", "正在努力加载中 ...", true, false); } } }); } private void dismissProgressDialog() { mHandler.post(new Runnable() { @Override public void run() { if (progressDialog != null) { progressDialog.dismiss(); progressDialog = null; } } }); } private void playvideo() { if (!URLUtil.isNetworkUrl(this.remoteUrl)) { mVideoView.setVideoPath(this.remoteUrl); mVideoView.start(); return; } showProgressDialog(); new Thread(new Runnable() { @Override public void run() { FileOutputStream out = null; InputStream is = null; try { URL url = new URL(remoteUrl); HttpURLConnection httpConnection = (HttpURLConnection) url .openConnection(); if (localUrl == null) { localUrl = Environment.getExternalStorageDirectory() .getAbsolutePath() + "/VideoCache/" + System.currentTimeMillis() + ".mp4"; } System.out.println("localUrl: " + localUrl); File cacheFile = new File(localUrl); if (!cacheFile.exists()) { cacheFile.getParentFile().mkdirs(); cacheFile.createNewFile(); } readSize = cacheFile.length(); out = new FileOutputStream(cacheFile, true); httpConnection.setRequestProperty("User-Agent", "NetFox"); httpConnection.setRequestProperty("RANGE", "bytes=" + readSize + "-"); is = httpConnection.getInputStream(); mediaLength = httpConnection.getContentLength(); if (mediaLength == -1) { return; } mediaLength += readSize; byte buf[] = new byte[4 * 1024]; int size = 0; long lastReadSize = 0; mHandler.sendEmptyMessage(VIDEO_STATE_UPDATE); while ((size = is.read(buf)) != -1) { try { out.write(buf, 0, size); readSize += size; } catch (Exception e) { e.printStackTrace(); } if (!isready) { if ((readSize - lastReadSize) > READY_BUFF) { lastReadSize = readSize; mHandler.sendEmptyMessage(CACHE_VIDEO_READY); } } else { if ((readSize - lastReadSize) > CACHE_BUFF * (errorCnt + 1)) { lastReadSize = readSize; mHandler.sendEmptyMessage(CACHE_VIDEO_UPDATE); } } } mHandler.sendEmptyMessage(CACHE_VIDEO_END); } catch (Exception e) { e.printStackTrace(); } finally { if (out != null) { try { out.close(); } catch (IOException e) { // } } if (is != null) { try { is.close(); } catch (IOException e) { // } } } } }).start(); } private final static int VIDEO_STATE_UPDATE = 0; private final static int CACHE_VIDEO_READY = 1; private final static int CACHE_VIDEO_UPDATE = 2; private final static int CACHE_VIDEO_END = 3; private final Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case VIDEO_STATE_UPDATE: double cachepercent = readSize * 100.00 / mediaLength * 1.0; String s = String.format("已缓存: [%.2f%%]", cachepercent); if (mVideoView.isPlaying()) { curPosition = mVideoView.getCurrentPosition(); int duration = mVideoView.getDuration(); duration = duration == 0 ? 1 : duration; double playpercent = curPosition * 100.00 / duration * 1.0; int i = curPosition / 1000; int hour = i / (60 * 60); int minute = i / 60 % 60; int second = i % 60; s += String.format(" 播放: %02d:%02d:%02d [%.2f%%]", hour, minute, second, playpercent); } tvcache.setText(s); mHandler.sendEmptyMessageDelayed(VIDEO_STATE_UPDATE, 1000); break; case CACHE_VIDEO_READY: isready = true; mVideoView.setVideoPath(localUrl); mVideoView.start(); break; case CACHE_VIDEO_UPDATE: if (iserror) { mVideoView.setVideoPath(localUrl); mVideoView.start(); iserror = false; } break; case CACHE_VIDEO_END: if (iserror) { mVideoView.setVideoPath(localUrl); mVideoView.start(); iserror = false; } break; } super.handleMessage(msg); } }; } |
public class BBVideoPlayer extends Activity { private VideoView mVideoView; private TextView tvcache; private String remoteUrl; private String localUrl; private ProgressDialog progressDialog = null; private static final int READY_BUFF = 2000 * 1024; private static final int CACHE_BUFF = 500 * 1024; private boolean isready = false; private boolean iserror = false; private int errorCnt = 0; private int curPosition = 0; private long mediaLength = 0; private long readSize = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.bbvideoplayer); findViews(); init(); playvideo(); } private void findViews() { this.mVideoView = (VideoView) findViewById(R.id.bbvideoview); this.tvcache = (TextView) findViewById(R.id.tvcache); } private void init() { Intent intent = getIntent(); this.remoteUrl = intent.getStringExtra("url"); System.out.println("remoteUrl: " + remoteUrl); if (this.remoteUrl == null) { finish(); return; } this.localUrl = intent.getStringExtra("cache"); mVideoView.setMediaController(new MediaController(this)); mVideoView.setOnPreparedListener(new OnPreparedListener() { public void onPrepared(MediaPlayer mediaplayer) { dismissProgressDialog(); mVideoView.seekTo(curPosition); mediaplayer.start(); } }); mVideoView.setOnCompletionListener(new OnCompletionListener() { public void onCompletion(MediaPlayer mediaplayer) { curPosition = 0; mVideoView.pause(); } }); mVideoView.setOnErrorListener(new OnErrorListener() { public boolean onError(MediaPlayer mediaplayer, int i, int j) { iserror = true; errorCnt++; mVideoView.pause(); showProgressDialog(); return true; } }); } private void showProgressDialog() { mHandler.post(new Runnable() { @Override public void run() { if (progressDialog == null) { progressDialog = ProgressDialog.show(BBVideoPlayer.this, "视频缓存", "正在努力加载中 ...", true, false); } } }); } private void dismissProgressDialog() { mHandler.post(new Runnable() { @Override public void run() { if (progressDialog != null) { progressDialog.dismiss(); progressDialog = null; } } }); } private void playvideo() { if (!URLUtil.isNetworkUrl(this.remoteUrl)) { mVideoView.setVideoPath(this.remoteUrl); mVideoView.start(); return; } showProgressDialog(); new Thread(new Runnable() { @Override public void run() { FileOutputStream out = null; InputStream is = null; try { URL url = new URL(remoteUrl); HttpURLConnection httpConnection = (HttpURLConnection) url .openConnection(); if (localUrl == null) { localUrl = Environment.getExternalStorageDirectory() .getAbsolutePath() + "/VideoCache/" + System.currentTimeMillis() + ".mp4"; } System.out.println("localUrl: " + localUrl); File cacheFile = new File(localUrl); if (!cacheFile.exists()) { cacheFile.getParentFile().mkdirs(); cacheFile.createNewFile(); } readSize = cacheFile.length(); out = new FileOutputStream(cacheFile, true); httpConnection.setRequestProperty("User-Agent", "NetFox"); httpConnection.setRequestProperty("RANGE", "bytes=" + readSize + "-"); is = httpConnection.getInputStream(); mediaLength = httpConnection.getContentLength(); if (mediaLength == -1) { return; } mediaLength += readSize; byte buf[] = new byte[4 * 1024]; int size = 0; long lastReadSize = 0; mHandler.sendEmptyMessage(VIDEO_STATE_UPDATE); while ((size = is.read(buf)) != -1) { try { out.write(buf, 0, size); readSize += size; } catch (Exception e) { e.printStackTrace(); } if (!isready) { if ((readSize - lastReadSize) > READY_BUFF) { lastReadSize = readSize; mHandler.sendEmptyMessage(CACHE_VIDEO_READY); } } else { if ((readSize - lastReadSize) > CACHE_BUFF * (errorCnt + 1)) { lastReadSize = readSize; mHandler.sendEmptyMessage(CACHE_VIDEO_UPDATE); } } } mHandler.sendEmptyMessage(CACHE_VIDEO_END); } catch (Exception e) { e.printStackTrace(); } finally { if (out != null) { try { out.close(); } catch (IOException e) { // } } if (is != null) { try { is.close(); } catch (IOException e) { // } } } } }).start(); } private final static int VIDEO_STATE_UPDATE = 0; private final static int CACHE_VIDEO_READY = 1; private final static int CACHE_VIDEO_UPDATE = 2; private final static int CACHE_VIDEO_END = 3; private final Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case VIDEO_STATE_UPDATE: double cachepercent = readSize * 100.00 / mediaLength * 1.0; String s = String.format("已缓存: [%.2f%%]", cachepercent); if (mVideoView.isPlaying()) { curPosition = mVideoView.getCurrentPosition(); int duration = mVideoView.getDuration(); duration = duration == 0 ? 1 : duration; double playpercent = curPosition * 100.00 / duration * 1.0; int i = curPosition / 1000; int hour = i / (60 * 60); int minute = i / 60 % 60; int second = i % 60; s += String.format(" 播放: %02d:%02d:%02d [%.2f%%]", hour, minute, second, playpercent); } tvcache.setText(s); mHandler.sendEmptyMessageDelayed(VIDEO_STATE_UPDATE, 1000); break; case CACHE_VIDEO_READY: isready = true; mVideoView.setVideoPath(localUrl); mVideoView.start(); break; case CACHE_VIDEO_UPDATE: if (iserror) { mVideoView.setVideoPath(localUrl); mVideoView.start(); iserror = false; } break; case CACHE_VIDEO_END: if (iserror) { mVideoView.setVideoPath(localUrl); mVideoView.start(); iserror = false; } break; } super.handleMessage(msg); } }; }
总体来说,原理比较简单,就是把视频加载了一段后,就送到播放器播放,如果出现了错误,则优先缓存一部分文件,然后再继续播放,类似的处理过程循环往复。
程序源代码下载: code
大家可以在实际环境中做测试,和依据实际情况动态维护缓存区,在具体的使用过程中有神马问题留言即可!
你好,googlecode源代码下载不了,能否提供另外连接或发我邮箱1035766456@qq.com
下载地址:http://pan.baidu.com/s/1BYBE3#path=%252F%25E5%258D%259A%25E5%25AE%25A2%25E8%25B5%2584%25E6%25BA%2590%25E5%2585%25B1%25E4%25BA%25AB%25E5%258C%25BA
你好,googlecode源代码下载不了,能否提供另外连接或发我邮箱webb.stone.huang@163.com
下载地址:http://pan.baidu.com/s/1BYBE3#path=%252F%25E5%258D%259A%25E5%25AE%25A2%25E8%25B5%2584%25E6%25BA%2590%25E5%2585%25B1%25E4%25BA%25AB%25E5%258C%25BA
亲,这个会卡的 第一段缓冲区数据读完之后就会停止了
用surfaceview和mediaplayer播放怎么不行啊?一直缓存到100就是不播放。
原demo能不能给一份?SOS啊!!!
怎么把moov放在mdat前面啊?
楼主,为什么我使用手机拍的视频,也不能实现缓冲下载啊,视频文件全部都下载到本地了,课时界面上还是loading,麻烦指导一下啊
有一个问题,再update cache的时候,如果不重新 mVideoView.setVideoPath(localUrl);mVideoView.start();的话,视频就不会继续播放了,但如果这样做的话(重新设置路径和重新启动),视频回闪烁一下,ui也回跳出来,用户体验很差,不知道是什么原因。case CACHE_VIDEO_UPDATE: if (iserror) { mVideoView.setVideoPath(localUrl); mVideoView.start(); iserror = false; } break;
我也遇到类似情况,把 READY_BUFF 改小后,就可以播放视频了。
楼主:报异常attachNewPlayer called in state 4
java.lang.IllegalStateException
at android.media.MediaPlayer.setDataSource(Native Method)怎么解决呀
您好,请问一下,视频缓冲一部分然后我断开网络,视频播放到缓冲的地方就弹出那个缓冲的dialog,我再打开网络但是它没有继续下载播放。这个怎么解决?谢谢。
求demo啊,网址打开没东西啊,楼主
你好 想咨询一下什么情况下回执行setOnErrorListener 这个方法。能否简单讲解一下 谢谢。
原来的文件下载链接出现问题,请到新的地方下载:博客资源共享区( http://pan.baidu.com/s/1BYBE3 ) VideoViewDemo.zip
thanks for share!
視頻本身就是mp4的,但出現一直加載緩存,100%還不是緩存的終點。這是為什麼呢?
怎么有的不是一边下载一边播放呢?有的是缓冲完成了,还在缓冲。还有就是使用那个qt-faststart (转换前的视频文件) (转换后的视频文件) 出现错误 ,错误如下: last atom in file was not a moov atom
@hypol: 这个我倒是没有亲自使用MediaRecorder录制过视频,平时的测试都是用系统的照相机直接录制的,你可以参考一下系统照相机的实现源码,估计是配置参数的问题,自己编写代码也是可以调整视频文件的格式的
博主:非常感谢你把这么好的Demo发出来供大家学习!我有个疑问,在我自己的手机上,用安卓自己的 MediaRecorder 类来录制MP4文件,可是出来的文件,一开始是mdat,而moov是放在文件结尾的。这样不进行处理的话就无法直接HTTP渐进式播放。请问你手机拍的MP4是如何实现moov放在文件开头的?
@润物无声: 哦,原来是这样啊,非常感谢您的热心回复!
可是,我刚才在我的手机上(没有修改过的安卓2.3.4系统)用系统的相机拍摄的是3GP格式,我看了文件,同样是 moov放在了文件的结尾,而文件开头是mdat。怎么我跟你的手机不同哦。。
大哥使用你的案例 报错啊。使用缓冲的时候会报错,申明非法mediaPlayer.setDataSource(localUrl);申明非法。
是不是localUrl的文件没有建立成功,导致文件读取错误,或者给我一份详细的log信息,光凭这个信息无法找出原因所在。
06-26 16:24:08.410: W/System.err(14571): at android.os.Handler.dispatchMessage(Handler.java:99)
06-26 16:24:08.410: W/System.err(14571): at android.os.Looper.loop(Looper.java:132)
06-26 16:24:08.410: W/System.err(14571): at android.app.ActivityThread.main(ActivityThread.java:4123)
06-26 16:24:08.410: W/System.err(14571): at java.lang.reflect.Method.invokeNative(Native Method)
06-26 16:24:08.410: W/System.err(14571): at java.lang.reflect.Method.invoke(Method.java:491)
06-26 16:24:08.410: W/System.err(14571): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:844)
06-26 16:24:08.410: W/System.err(14571): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
06-26 16:24:08.410: W/System.err(14571): at dalvik.system.NativeStart.main(Native Method)
06-26 16:24:08.415: E/MediaPlayer(14571): setDataSource called in state 4
06-26 16:24:08.415: W/System.err(14571): java.lang.IllegalStateException
06-26 16:24:08.415: W/System.err(14571): at android.media.MediaPlayer.setDataSource(Native Method)
06-26 16:24:08.415: W/System.err(14571): at com.zhourunsheng.videodemo.BBVideoPlayer$2.handleMessage(BBVideoPlayer.java:498)
06-26 16:24:08.415: W/System.err(14571): at android.os.Handler.dispatchMessage(Handler.java:99)
06-26 16:24:08.415: W/System.err(14571): at android.os.Looper.loop(Looper.java:132)
06-26 16:24:08.415: W/System.err(14571): at android.app.ActivityThread.main(ActivityThread.java:4123)
06-26 16:24:08.415: W/System.err(14571): at java.lang.reflect.Method.invokeNative(Native Method)
06-26 16:24:08.415: W/System.err(14571): at java.lang.reflect.Method.invoke(Method.java:491)
06-26 16:24:08.415: W/System.err(14571): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:844)
06-26 16:24:08.415: W/System.err(14571): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
版主,我试验的效果怎么是完整下载之后才能播放啊? 缓冲100就是整个文件全部下载吗? 不是说一段一段的加载的吗?
@zin.yan: 问题出在视频文件的格式上面,请参照博文《android-视频播放之流媒体格式处理》http://blog.zhourunsheng.com/2012/05/android-视频播放之流媒体格式处理/
贵站交换友情链接,本站已开通自动申请功能
来关注一下