需求背景
公司用到大华摄像头,大华提供了rtsp的视频流,目前浏览器已都不支持flash,所以转成rtmp流无法播放;转成m3u8格式虽然可以直接播放,但是延迟太高;最终决定将rtsp流通过ffmpeg+nginx-http-flv转成rtmp以及http-flv流,并通过flv.js在页面播放。
开发工具
- FFmpeg:FFmpeg是一套可以用来记录、转换数字音频、视频,并能将其转化为流的开源计算机程序,下载:http://www.ffmpeg.org/download.html;
- flv.js:Flv.js 是 HTML5 Flash 视频(FLV)播放器,纯原生 JavaScript 开发,没有用到Flash,由 bilibili 网站开源 https://www.oschina.net/p/flv-js?hmsr=aladdin1e1;
- VLC播放器(测视频使用)下载:https://www.videolan.org/;
- -nginx-http-flv:nginx集成nginx-http-flv-module这个模块,在发布rtmp的时候可以转化成支持HTTP方式的FLV 。下载nginx:https://nginx.org/download/nginx-1.16.1.tar.gz ;下载nginx-http-flv-module 模块包:https://github.com/winshining/nginx-http-flv-module;
- 编译好的-nginx-http-flv下载:https://download.csdn.net/download/weixin_43058421/18273744
配置nginx.conf
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#error_log logs/error.log debug;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
# 添加RTMP服务
rtmp {
server {
listen 1936; # 监听端口
chunk_size 4000;
application live {
live on;
gop_cache on;
}
}
}
# HTTP服务
http {
server {
listen 8085;
server_name localhost;
location /live {
flv_live on;
chunked_transfer_encoding on; #open 'Transfer-Encoding: chunked' response
add_header 'Access-Control-Allow-Credentials' 'true'; #add additional HTTP header
add_header 'Access-Control-Allow-Origin' '*'; #add additional HTTP header
add_header Access-Control-Allow-Headers X-Requested-With;
add_header Access-Control-Allow-Methods GET,POST,OPTIONS;
add_header 'Cache-Control' 'no-cache';
}
}
}
ffmpeg命令
(实时流):ffmpeg -i “rtsp://172.18.10.200:9090/dss/monitor/param?cameraid=1000298%240&substream=2” -vcodec copy -acodec copy -f flv “rtmp://127.0.0.1:1936/live/1000298”
rtmp播放地址:rtmp://127.0.0.1:1936/live/1000298
http-flv播放地址:http://127.0.0.1:8085/live?port=1936&app=live&stream=1000298
注意 :如果使用flv.js播放流,那么请保证发布的流被正确编码,因为flv.js只支持H.264编码的视频和AAC/MP3编码的音频
前端播放flv.js
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script src="https://cdn.bootcss.com/flv.js/1.4.0/flv.min.js"></script>
<video id="videoElement" style="width: 80%;" controls="controls"></video>
<script>
if (flvjs.isSupported()) {
var videoElement = document.getElementById('videoElement');
var flvPlayer = flvjs.createPlayer({
type: 'flv',
url:'http://127.0.0.1:8085/live?port=1936&app=live&stream=1000298'
});
flvPlayer.attachMediaElement(videoElement);
flvPlayer.load();
flvPlayer.play();
}
</script>
</body>
</html>