node.js用ffmpeg切rtsp实时视频流为mp4,并且在网页上播放
用express.js框架,这部分太简单了,省略
npm或者yarn安装fluent-ffmpeg
路由部分代码:
router.rtspTrackingHandle = function (req, res) {
logger.info('[tracking]: rtsp handle');
let url = req.query.url || '';
// let url = 'rtsp://admin:jeewey123@192.168.13.16:554/h264/ch1/main/av_stream';
logger.info('[tracking]: rtsp url: ' + url);
url = url.replace(/&/g, '%26'); // 大华摄像头的特殊符号转义
logger.info('[tracking]: rtsp params: ', JSON.stringify(req.params));
try {
ffmpeg(url)
.addInputOption('-rtsp_transport', 'tcp', '-buffer_size', '102400') // 这里可以添加一些 RTSP 优化的参数
.on('start', function () {
logger.info('[tracking]: Stream started.' + url);
})
.on('codecData', function () {
logger.info('[tracking]: Stream codecData.' + url);
// 摄像机在线处理
})
.on('error', function (err) {
logger.error('[tracking]: An error occured: ' + `[${url}]::` + `[${err}]`);
})
.on('end', function () {
logger.info('[tracking]: Stream end!' + url);
// 摄像机断线的处理
})
.outputOptions(['-movflags isml+frag_keyframe'])
.toFormat('mp4').noAudio().pipe(res, { end: true });
} catch (error) {
logger.error('[tracking]: ' + error.stack);
}
};
前端代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>video player</title>
</head>
<body>
<video autoplay="autoplay">
<source src="http://localhost:3002/live/tracking" type="video/mp4">
</video>
</body>
</html>