Node.js安装:
参考这个
Nodejs安装教程
安装完成之后,记得修改一下npm源:
javascript
npm config set registry https://registry.npmmirror.com
下一步,安装node-media-server
javascript
npm install node-media-server
参考这个:安装ffmpeg
下一步:创建js脚本 app.js,内容如下:
javascript
const fs = require('fs');
const path = require('path');
const spawn = require('child_process').spawn;
const async = require('async');
const NodeMediaServer = require('node-media-server');
// 创建node-media-server实例
const nmsConfig = {
rtmp: {
port: 9999,
chunk_size: 60000,
gop_cache: true,
ping: 60,
ping_timeout: 30
},
http: {
port: 8000,
mediaroot: './media',
allow_origin: '*'
}
};
const nms = new NodeMediaServer(nmsConfig);
nms.run();
// 根据指定的目录和文件类型创建要推流的文件列表
const videoDir = 'E:\Build';
const allowedExtensions = ['.mp4', '.avi', '.mov'];
const fileList = [];
fs.readdirSync(videoDir).forEach(file => {
const fileExtension = path.extname(file);
if (allowedExtensions.includes(fileExtension)) {
fileList.push(path.join(videoDir, file));
}
});
if (!fileList.length) {
console.log('No video files found!');
process.exit(1);
}
// 配置FFmpeg推流命令行参数
const ffmpegCommand = `ffmpeg -re -stream_loop -1 -i "$input$" -c copy -f flv "$output$"`;
const ffmpegEscapeMap = { '$input$': '', '$output$': '' };
let index = 0;
const maxIndex = fileList.length - 1;
async.each(fileList, (videoPath, callback) => {
// 构建FFmpeg命令行参数
ffmpegEscapeMap['$input$'] = videoPath;
// node-media-server IP即可,无需填写端口默认端口1935 服务端获取的RTMP流也是这个地址
ffmpegEscapeMap['$output$'] = `rtmp://88.22.10.113:9999/live/test`;
const output = `rtmp:88.22.10.113:9999/live/test`;
const command = ffmpegCommand.replace(/\$\w+\$/g, m => ffmpegEscapeMap[m]);
console.log(`Starting streaming for file: ${videoPath}...`);
// 调用FFmpeg推流
const ffProcess = spawn("ffmpeg"
,['-re','-stream_loop','-1','-i',videoPath,'-c','copy','-f','flv',output]
, { detached: true });
// 捕捉事件
ffProcess.on('exit', () => {
console.log(`Stop streaming for file: ${videoPath}.`);
if (++index > maxIndex) {
index = 0; // 循环推流
}
});
ffProcess.on('close', code => {
console.log(`Process ${path.parse(videoPath).name} exited with code ${code}`);
if (++index > maxIndex) {
index = 0; // 循环推流
}
});
ffProcess.stderr.on('data', (data) => {
console.log(`${videoPath}: ${data.toString()}`);
});
callback();
})
console.log(`Started pushing ${fileList.length} stream(s) to node-media-server on rtmp://88.22.10.113:9999/live/.`);
,记得修改里面的videoDir以及ip地址。
最后node app.js,至此已经推流成功。
测试:安装vlc播放器,然后播放网络流,地址:rtmp://88.22.10.113:9999/live/test,记得修改IP
javascript
// 推送视频:xm0525$ ffmpeg -re -i 视频名称 -c copy -f flv rtmp://ip:1935/live/STREAM_NAME
// 推送摄像头:ffmpeg -f avfoundation -video_size 640x480 -framerate 30 -i 0:0 -vcodec libx264 -preset veryfast -f flv rtmp://ip:1935/live/STREAM_NAME
// 推送屏幕:ffmpeg -f avfoundation -i "1" -vcodec libx264 -preset ultrafast -acodec libfaac -f flv rtmp://ip:1935/live/STREAM_NAME