Nodejs + FFmpeg 直播推流小改三版

历史纪录

更新内容

  • 使用 concat 资源列表替代普通文件输入流,将多个视频合并到同个流中推送,防止断流。

注意事项

  • 要求同一个 concat 列表中的视频文件格式、编码、尺寸相同,否则视频间切换时虽然不断流但会出现奇怪的现象。
  • 本文代码继承上个版本特点,自动读取目标文件夹中的视频文件,然后顺序随机生成一个 concat.txt 列表文件,不需要手动编写列表。
  • 同样建议配合 pm2 进程守护使用。

Nodejs 代码

var fs = require('fs');
var sd = require('silly-datetime');
var ffmpeg = require('fluent-ffmpeg');
var D = './video2/';
var L = './pic/tips2.png';
var R = 'rtmp://txy.live-send.acg.tv/live-txy/';
var C = '?streamname=live_0000000_1111111&key=1f8a9f1h8j8q4h5x6i5s6f8n1z2i3dq7';
var O = '';

function showTime() {
 return sd.format(new Date(), 'YYYY-MM-DD HH:mm');
}

function randomV() { 
 return 0.5 - Math.random(); 
}

function liveON(inputPath) {
 var outputPath = (O == '' ? (R + C) : O);
 ffmpeg(inputPath)
   .inputOptions('-re')
    .inputOptions('-ac 2')
    .inputOptions('-f concat')
    .inputOptions('-safe 0')
    .addInput(L)
    .complexFilter([{
     filter: 'scale',
      options: [1280, -1],
      inputs: '[0:v]',
      outputs: 'video'
    }, {
      filter: 'scale',
      options: [220, -1],
     inputs: '[1:v]',
      outputs: 'logo'
   }, {
      filter: 'overlay',
      options: {
        x: 'main_w-overlay_w-15',
       y: 15
     },
      inputs: ['video', 'logo']
   }])
   .on('start', function(commandLine) {
      console.log('[' + showTime() + '] Vedio is Pushing !');
     console.log('[' + showTime() + '] Spawned Ffmpeg with command !');
      console.log('[' + showTime() + '] Command: ' + commandLine);
    })
    .on('error', function(err, stdout, stderr) {
      console.log('error: ' + err.message);
     console.log('stdout: ' + stdout);
     console.log('stderr: ' + stderr);
   })
    .on('end', function() {
     console.log('[' + showTime() + '] Vedio Pushing is Finished !');
    })
    .addOptions([
     '-vcodec libx264',
      '-preset veryfast',
     '-crf 22',
      '-maxrate 1000k',//1000k
      '-bufsize 3000k',
     '-acodec libmp3lame',
     '-ac 2',
      '-ar 44100',
      '-b:a 96k'
    ])
    .format('flv')
    .output(outputPath, {
     end: true
   })
    .run();
}

function start() {
  var V = fs.readdirSync(D).sort(randomV);
  var N = V.length;
 var concat = '';
  console.log('[' + showTime() + '] Find ' + N + ' Video Files !');
 for(var i = 0; i < N; i++) {
    concat += "file '" + D + V[i] + "'" + (i == N-1 ? "" : "\r\n");
 }
 fs.writeFile('concat.txt', concat, (err) => {
   if (err) throw err;
   liveON("concat.txt");
 });
}

start();

截至发文,该代码已在腾讯云不间断运行超过一个月 ---> http://live.bilibili.com/64285

标签: none

已有 33 条评论

  1. 香菇终于更新辣~

  2. N年前 还捣鼓过FFmpeg 不过CSDN上一个捣鼓FFmpeg 博主已经挂了~~

    1. 喔 第一篇里提到过

  3. Kay Kay

    沙发!

评论已关闭