導語
隨着直播平台爆發式增長,直播平台從 PC 端轉戰移動端,緊跟着直播的潮流,自己學習實現了一套簡單的 H5 視頻推流的解決方案,下面就給小伙伴們分享一下自己學習過程中的經驗。
環境部署
1、 配置、安裝 Nginx;
# ./configure --sbin-path=/usr/local/nginx/nginx --conf-path=/usr/local/nginx/nginx.pid --with-http_ssl_module --with-pcre=/usr/local/src/pcre-8.39 --with-zlib=/usr/local/src/zlib-1.2.11 --with-openssl=/usr/local/openssl/ # make # make install # /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf //啟動Ngnix # netstat -ano | grep 80
2、擴展 Nginx-rtmp-module
# ./configure --add-module=/usr/local/src/nginx-rtmp-module-master --with-openssl=/usr/local/openssl/ # make # make install # vim /usr/local/ngnix/conf/ngnix.conf include /usr/localcinx-rtmp-module-master/testinx.conf; # vim /usr/localcinx-rtmp-module-master/testinx.conf rtmp { server { listen 1935; application myapp { live on; #record keyframes; #record_path /tmp; #record_max_size 128K; #record_interval 30s; #record_suffix .this.is.flv; #on_publish http://localhost:8080/publish; #on_play http://localhost:8080/play; #on_record_done http://localhost:8080/record_done; } application hls { live on; hls on; hls_path /tmp/hls; hls_fragment 10s; #每個視頻切片的時長。 hls_playlist_length 60s; #總共可以回看的事件,這里設置的是1分鍾。 #hls_continuous on; #連續模式。 #hls_cleanup on; #對多余的切片進行刪除。 #hls_nested on; #嵌套模式。 } } } http { server { listen 8080; location /stat { rtmp_stat all; rtmp_stat_stylesheet stat.xsl; } location /stat.xsl { root /usr/local/src/nginx-rtmp-module-master/; } location /control { rtmp_control all; } location /rtmp-publisher { root /usr/local/src/nginx-rtmp-module-master/test; } location /hls { #server hls fragments types{ application/vnd.apple.mpegurl m3u8; video/mp2t ts; } #alias /tmp/app; root /tmp; expires -1; } location / { root /usr/local/src/nginx-rtmp-module-master/test/rtmp-publisher; } } } # /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf # netstat -ltn #查看端口的監聽情況
3、 安裝 ffmpeg
# ./configure --prefix=/usr/local/ffmpeg # make # make install
至於 ffmpeg 是啥?詳細介紹可以參考:《【經驗分享】音頻、視頻利器——FFmpeg》
模擬推流
- 先來看一個簡單的直播推流流程圖 :
- 用 flv 視頻文件模擬 RTMP 視頻流:
# ffmpeg -re -i test.flv -vcodec copy -acodec copy -f flv rtmp://ip:1935/myapp/mystream
注:RTMP(Real Time Messaging Protocol),實時消息傳輸協議,用於視頻直播協議,和 HLS 一樣都可以應用於視頻直播;
- 用 mp4 視頻文件模擬 HLS 視頻流:
ffmpeg -re -i test.mp4 -c copy -f flv rtmp://ip:1935/hls/mystream
注:HLS(HTTP Live Streaming), Apple 的動態碼率自適應技術,主要用於 PC 和 Apple 終端的音視頻服務;
- HLS 的請求流程:
H5 如何在頁面上播放視頻
<video autoplay webkit-playsinline>
<source src="http://ip/hls/mystream.m3u8" type="application/vnd.apple.mpegurl" /> <p class="warning">Your browser does not support HTML5 video.</p> </video>
總結
根據以上的流程,簡單的實現了一個視頻直播的流服務器來推送直播流,並且可以在 H5 頁面上播放視頻流。有興趣的小伙伴們也可以嘗試一下~