1. 程式人生 > >Android 實現m3u8視訊快取

Android 實現m3u8視訊快取

1.M3U8協議

HLS(HTTP Live Streaming)是蘋果公司針對iPhone、iPod、iTouch和iPad等移動裝置而開發的基於HTTP協議的流媒體解決方案。在 HLS 技術中 Web 伺服器向客戶端提供接近實時的音視訊流。但在使用的過程中是使用的標準的 HTTP 協議,所以這時,只要使用 HLS 的技術,就能在普通的 HTTP 的應用上直接提供點播和直播。在App Store中的視訊相關的應用,基本都是應用的此種技術。該技術基本原理是將視訊檔案或視訊流切分成小片(ts)並建立索引檔案(m3u8)。支援的視訊流編碼為H.264,音訊流編碼為AAC。

#EXTM3U

#EXT-X-TARGETDURATION:19

#EXT-X-VERSION:2

#EXTINF:10,

http://122.225.31.106/6775ED76AE94E84581E2FA4D03/0300080B0053D05A49A22808DF700EC607AF80-D3EF-E08A-FB37-918809D8CF4C.mp4.ts?ts_start=0&ts_end=10&ts_seg_no=0

#EXTINF:10,

http://122.225.31.106/6775ED76AE94E84581E2FA4D03/0300080B0053D05A49A22808DF700EC607AF80-D3EF-E08A-FB37-918809D8CF4C.mp4.ts?ts_start=10&ts_end=20&ts_seg_no=1

…………..

#EXTINF:12,

http://122.225.31.85/657DD4BEC15488401753C7200C/0300080B0A53D05A49A22808DF700EC607AF80-D3EF-E08A-FB37-918809D8CF4C.mp4.ts?ts_start=320&ts_end=336&ts_seg_no=396

#EXT-X-ENDLIST

上面是一個m3u8的例子

現在主流的視訊網站基本都是用這中格式做線上視訊。

2.播放

         Android原生系統好像是不支援m3u協議的,所以一般情況要繼承第三方的播放器,百度或者vatimio 使用參考各自的api文件即可比較簡單。

3.快取

         參考上面的例子,可分析出

http://122.225.31.106/6775ED76AE94E84581E2FA4D03/0300080B0053D05A49A22808DF700EC607AF80-D3EF-E08A-FB37-918809D8CF4C.mp4.ts?ts_start=0&ts_end=10&ts_seg_no=0

這玩意就是我們要的視訊原始檔,拷貝地址到瀏覽器可以下載到xxxx.ts的檔案。

         我們快取的思路也很簡單:

1.      解析原始的m3u8 獲取每個短視訊的源地址。

2.      下載所有的短視訊到本地。

3.      根據原始的meu8生成本地版的m3u8。

4.      把本地生成的m3u8路徑傳入播放器。

 下面根據這個思路敲程式碼即可…

4.喜聞樂見的程式碼

解析m3u8:

public static List<String> parseStringFromUrl(String url) {
		List<String> resultList = null;
		HttpResponse res = HttpConnect.getResponseFromUrl(url);
		try {
			if (res != null) {
				resultList = new ArrayList<String>();
				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.下載視訊 這個參考檔案下載的程式碼即可。

3. 我們把視訊檔案儲存在SD卡目錄下,檔名可以自己定了,我用的是1.ts,2.ts。。這樣的。

public static String getNativeM3u(String url,List<String> pathList,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");
					}
				}
				in.close();
			}
		} 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://apk.hiapk.com/appinfo/com.shixforever.gamevideo

ti4 中國戰隊好猛 B神可惜了~