本文共 3280 字,大约阅读时间需要 10 分钟。
HLS(HTTP Live Streaming)是苹果公司针对iPhone、iPod、iTouch和iPad等移动设备而开发的基于HTTP协议的流媒体解决方案。在 HLS 技术中 Web 服务器向客户端提供接近实时的音视频流。但在使用的过程中是使用的标准的 HTTP 协议,所以这时,只要使用 HLS 的技术,就能在普通的 HTTP 的应用上直接提供点播和直播。在App Store中的视频相关的应用,基本都是应用的此种技术。该技术基本原理是将视频文件或视频流切分成小片(ts)并建立索引文件(m3u8)。支持的视频流编码为H.264,音频流编码为AAC。
上面是一个m3u8的例子
现在主流的视频网站基本都是用这中格式做在线视频。Android原生系统好像是不支持m3u协议的,所以一般情况要继承第三方的播放器,百度或者vatimio 使用参考各自的api文档即可比较简单。
参考上面的例子,可分析出:
这玩意就是我们要的视频源文件,拷贝地址到浏览器可以下载到xxxx.ts的文件。
我们缓存的思路也很简单:
- 解析原始的m3u8 获取每个短视频的源地址。
- 下载所有的短视频到本地。
- 根据原始的meu8生成本地版的m3u8。
- 把本地生成的m3u8路径传入播放器。
下面根据这个思路敲代码即可…
public static ListparseStringFromUrl(String url) { List resultList = null; HttpResponse res = HttpConnect.getResponseFromUrl(url); try { if (res != null) { resultList =new ArrayList ; InputStream in = res.getEntity.getContent; BufferedReader reader = new BufferedReader( new InputStreamReader(in)); String line = ""; while ((line = reader.readLine) != null) { if (line.startsWith("#")) { } else if (line.length > 0 && line.startsWith("http://")) { resultList.add(line); } } in.close; } } catch (Exception e) { e.printStackTrace; } return resultList;}
这里写代码片
###2.下载视频
我们把视频文件保存在SD卡目录下,文件名可以自己定了,我用的是1.ts,2.ts。。这样的。
public static String getNativeM3u(String url,ListpathList,String saveFilePath) { HttpResponse res = HttpConnect.getResponseFromUrl(url); int num=0; //需要生成的目标buff StringBuffer buf = new StringBuffer; try { if (res != null) { InputStream in = res.getEntity.getContent; BufferedReader reader = new BufferedReader( new InputStreamReader(in)); String line = ""; while ((line = reader.readLine) != null) { if (line.length > 0 && line.startsWith("http://")) { //replce 这行的内容 buf.append("file:/"+saveFilePath+num+".ts\r\n"); num++; }else { buf.append(line+"\r\n"); } } } } catch (Exception e) { e.printStackTrace; } return buf.toString;}
url 是m3u8的地址
pathList 为上面解析出来的ts视频地址的list
saveFilePath 为本地保存ts的路径
然后把这个生成的m3u8文件写到本地即可。
/** * 将内容回写到文件中 * @param filePath * @param content * / public static void write(String filePath, String content) { BufferedWriter bw = null; try { // 根据文件路径创建缓冲输出流 bw = new BufferedWriter(new FileWriter(filePath)); // 将内容写入文件中 bw.write(content); } catch (Exception e) { e.printStackTrace; } finally { // 关闭流 if (bw != null) { try { bw.close; } catch (IOException e) { bw = null; } } } }
要播放的时候把这个本地的m3u8地址扔个播放器即可,就这么简单~
附上demo的地址:
转载地址:http://xrcqf.baihongyu.com/