搭建HLS直播測試環境
阿新 • • 發佈:2019-01-01
簡介
開發中需要一個不依賴外界環境的HLS直播伺服器。
本文介紹:
- 用
mp4
檔案作為直播視訊源,而不用攝像頭 - 通過
FFmpeg
將mp4
檔案形成直播的rtmp
流,push
到Nginx伺服器上 - Nginx安裝支援
rtmp
模組,可以播放包括rtmp
和hls
的直播視訊 - Nginx配置支援
rtmp
和hls
直播 - Web頁面使用
Videojs
播放hls
視訊
本文的環境為macOS 10.12.6
。
搭建最簡單的rtmp視訊播放服務
安裝Nginx和相關模組
brew tap homebrew/nginx
安裝支援rtmp模組的Nginx伺服器:
brew install nginx-full --with-rtmp-module
成功安裝後,啟動Nginx:
nginx
配置rtmp模組
配置檔案:/usr/local/etc/nginx/nginx.conf,和http
塊並列,建立一個rtmp
塊:
rtmp {
server {
listen 1935;
application live {
live on;
record off;
}
}
}
儲存後,執行:
nginx -s reload
安裝FFmpeg並執行命令push rtmp流
安裝:
brew install ffmpeg
執行push rtmp流命令:
ffmpeg -re -i your_source.mp4 -vcodec copy -f flv rtmp://localhost:1935/live/source
rtmp://localhost:1935/live/source
,其中:
live
和nginx.conf
中的application live
的live對應source
是可以自定義的
使用VLC播放rtmp流
安裝VLC:
brew cask install vlc
或者通過VLC官網下載安裝。
啟動VLC,選單:File -> Open Network...
,輸入:rtmp://localhost:1935/live/source
,其中source
是我們剛才自定義的。
如果VLC能播放直播流,說明安裝成功。這時停止FFmpeg,VLC的播放也會很快停止,說明是直播。
配置Nginx支援HLS直播
Nginx的rtmp模組,也支援對hls流的播放。需要在nginx.conf
在http
塊的server
塊內,增加:
location /hls {
# Disable cache
add_header Cache-Control no-cache;
# CORS setup
add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Expose-Headers' 'Content-Length';
# allow CORS preflight requests
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
types {
application/vnd.apple.mpegurl m3u8;
video/mp2t ts;
}
root /tmp/;
add_header Cache-Control no-cache;
}
因為是測試,root
我設定在/tmp
目錄,該目錄會在重啟macOS後自動清空。
另外,需要修改之前配置的rtmp
塊:
rtmp {
server {
listen 1935;
chunk_size 4000;
application show {
live on;
#enable HLS
hls on;
hls_path /tmp/hls;
hls_fragment 3;
hls_playlist_length 20;
}
}
}
配置後重新載入Nginx:
nginx -s reload
執行FFmpeg push hls流的命令:
ffmpeg -re -i your_source.mp4-vcodec libx264 -vprofile baseline -acodec aac -strict -2 -f flv rtmp://localhost:1935/live/source
然後可以在Safari瀏覽器開啟連結http://localhost:8080/hls/source.m3u8
播放。ffmpeg
命令執行後需要稍等一會兒才可以播放。
在Web頁面中播放HLS直播
在Chrome瀏覽器中播放hls,需要使用videojs和它的hls外掛。videojs會自動識別瀏覽器是否支援hls,只當瀏覽器不原生支援的情況下用hls外掛。
以下程式碼在Chrome 60.0
執行通過,/index.html
:
<!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 width="640"
data-setup='{}'>
<source src="/hls/stream.m3u8" type="application/x-mpegURL">
</video>
</body>
</html>