1. 程式人生 > >【學習筆記】HLS技術簡介&實現網頁播放m3u8直播源

【學習筆記】HLS技術簡介&實現網頁播放m3u8直播源

HLS (HTTP Live Streaming)是Apple公司研發的流媒體傳輸技術,包括一個m3u8的索引檔案、多個ts分片檔案和key加密串檔案。這項技術主要應用於點播和直播領域。

詳細簡介可參考:百度百科-HLS

之前在做電視直播網站的時候,涉及到了這項技術,特此記錄以下關鍵的程式碼:

線上或本地播放m3u8檔案,比較穩定的方法是使用github上的開源庫:Video.js

該庫封裝了很多操作,直接使用即可,無需我們手動去解析m3u8獲取ts分片檔案,很方便,感謝作者。

示例程式碼如下:

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>videojs-contrib-hls embed</title>

  <link href="https://unpkg.com/video.js/dist/video-js.css" rel="stylesheet">
  <script src="https://unpkg.com/video.js/dist/video.js"></script>
  <script src="https://unpkg.com/videojs-contrib-hls/dist/videojs-contrib-hls.js"></script>
  
</head>
<body>
  <h1>Video.js Example Embed</h1>

  <video id="my_video_1" class="video-js vjs-default-skin" controls preload="auto" width="640" height="268" 
  data-setup='{}'>
    <source src="http://d2zihajmogu5jn.cloudfront.net/bipbop-advanced/bipbop_16x9_variant.m3u8" type="application/x-mpegURL">
  </video>
  
  <script>
  </script>
  
</body>
</html>

其中,source可以有多個。

線上引入的js檔案有時訪問速度會很慢,建議下載