nginx與nginx-rtmp-module搭建流媒體服務器
轉載自my student 克明zhang
現在,一起學習一下如何自己搭建一個流媒體服務器吧!
本次搭建流媒體使用的環境是centos 7.0+nginx;
讓我們一起開始奇妙的流媒體之旅吧!
1、下載nginx-rtmp-module:
nginx-rtmp-module的官方github地址:https://github.com/arut/nginx-rtmp-module
使用命令:
[php] view plain copy
- git clone https://github.com/arut/nginx-rtmp-module.git
將nginx-rtmp-module下載到linux中。
2、安裝nginx:
nginx的官方網站為:http://nginx.org/en/download.html
[php] view plain copy
- wget http://nginx.org/download/nginx-1.8.1.tar.gz
- tar -zxvf nginx-1.8.1.tar.gz
- cd nginx-1.8.1
- ./configure --prefix=/usr/local/nginx --add-module=../nginx-rtmp-module --with-http_ssl_module
-
make && make install
本次默認安裝目錄為:/root, add-module為下載的nginx-rtmp-module文件路徑。
安裝時候可能會報錯沒有安裝openssl,需要執行命令:
[php] view plain copy
- yum -y install openssl openssl-devel
3、修改nginx配置文件:
- vi /usr/local/nginx/conf/nginx.conf
加入以下內容:
[php] view plain copy
-
rtmp {
- server {
- listen 1935; #監聽的端口
- chunk_size 4000;
- application hls { #rtmp推流請求路徑
- live on;
- hls on;
- hls_path /usr/share/nginx/html/hls;
- hls_fragment 5s;
- }
- }
- }
hls_path需要可讀可寫的權限。
修改http中的server模塊:
[php] view plain copy
- server {
- listen 81;
- server_name localhost;
- #charset koi8-r;
- #access_log logs/host.access.log main;
- location / {
- root /usr/share/nginx/html;
- index index.html index.htm;
- }
- #error_page 404 /404.html;
- # redirect server error pages to the static page /50x.html
- #
- error_page 500 502 503 504 /50x.html;
- location = /50x.html {
- root html;
- }
當然了,root可以跟據自己的需求來改的。
然後啟動nginx:
自己手動創建路徑mkdir -p /usr/share/nginx/html/hls
[php] view plain copy
- /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
關於更多rtmp的參數可以參考:https://github.com/arut/nginx-rtmp-module/wiki
4、開始推流
做好以上的配置後,就可以開始推流了,我們可以使用obs來推流。
在設置->串流 中填寫信息:URL為 rtmp://xxx:1935/hls,xxx為你的服務器的IP地址,hls是用來存放流媒體的。
秘鑰可以隨便填寫一個,用來播放的時候識別播放哪個流媒體的,例如填寫test等。
填寫完畢後,點擊開始串流,就說明我們的流媒體服務器搭建成功了。
5、觀看直播(拉流)
觀看直播就比較簡單了,可以簡單的使用h5的vedio標簽就可以觀看了。
可以訪問http://xxx:81/hls/mystream.m3u8來觀看直播,其中xxx為你的服務器IP地址,
或者使用
[php] view plain copy
- <video>
- <source src="http://xxx:81/hls/test.m3u8"/>
- <p class="warning">Your browser does not support HTML5 video.</p>
- </video>
同上, xxx寫的是你服務器IP地址。
然後使用手機訪問這個網站就能夠觀看直播了。延遲大概在20S左右。
(在IOS的safari瀏覽器中可以正常觀看)
寫在最後
為什麽延遲 那麽高呢?這是因為服務器將視頻流切斷成一個個小的以.ts結尾的文件。
(hls文件夾內容。即推流到該文件夾了)
而我們訪問的是.m3u8文件,這個文件內容是將一個個ts文件串聯起來的,這就達到了一個播放的效果,所以看起來會有很大的延遲。
(m3u8文件內容)
如果降低延遲也不是沒有方法,可以設置切片生成的大小以及訪問的速度,但是這樣大大增加了服務器的壓力。
當然,我們也可以用rtmp拉流工具(VLC等)來看該直播,延遲大概在2-5S左右,拉流地址與推流地址一致。
nginx與nginx-rtmp-module搭建流媒體服務器