使用 Node Media Server 和 FFmpeg 创建直播流,推送本地视频

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
相关推荐
cuijiecheng20183 小时前
音视频入门基础:AAC专题(4)——ADTS格式的AAC裸流实例分析
音视频·aac
wly47692308312 小时前
ChatGPT 有什么新奇的使用方式?
人工智能·gpt·chatgpt·ai作画·区块链·音视频
0点51 胜13 小时前
[ffmpeg] 音视频编码
ffmpeg·音视频
DisonTangor14 小时前
DepthCrafter:为开放世界视频生成一致的长深度序列
人工智能·计算机视觉·音视频
0点51 胜15 小时前
[ffmpeg]音频格式转换
开发语言·c++·ffmpeg
中式代码美式咖啡20 小时前
记录开发一个英语听力训练网站
java·spring boot·bootstrap·音视频·语音识别
神一样的老师1 天前
使用卷积神经网络进行人类活动识别的特征学习:惯性测量单元和音频数据的案例研究
学习·cnn·音视频
Kuekua-seu1 天前
文生视频算法
算法·音视频
PlumCarefree1 天前
基于鸿蒙API10的RTSP播放器(五:拖动底部视频滑轨实现跳转)
华为·ffmpeg·音视频
LuckyInn1 天前
从安装ffmpeg开始,把一个视频按照每秒30帧fps剪切为图片
ffmpeg·音视频