使用ffmpeg转码视频时遇到问题,我这样写代码不知道哪里出了问题
发布于 4 年前 作者 gzdx-feige 1607 次浏览 来自 问答

每个url第一次进来时都是可以的,第二次就直接触发close事件了,是在write(chunk)之后触发的,但是相同的url同一时间进来又没有这个问题,播放视频使用的是flv.js

const ffmpeg = require("fluent-ffmpeg");
const moment = require("moment");
const colors = require("colors-console");
const md5 = require("md5-node");

let streamObj = {};

module.exports = function createRTMPStream(url, res) {
    let url_md5 = md5(url);

    if (streamObj[url_md5]) {
      streamObj[url_md5].connects.push(res);
    } else {
      let startTime = +new Date();
      const command = new ffmpeg(url)
        .inputOptions([
          "-fflags nobuffer",
          // "-probesize 50000",
          "-analyzeduration 500000"
        ])
        .outputOptions(["-c:a copy", "-c:v copy", "-f flv"])
        .on("codecData", function (data) {
          console.log(new Date() - startTime);
          let timestr = colors(
            "green",
            "[" + moment().format("YYYY/MM/DD HH:mm:ss") + "]"
          );
          console.log(`${timestr} Start ${url}`);
        })
        .on("error", function (err) {
          let timestr = colors(
            "green",
            "[" + moment().format("YYYY/MM/DD HH:mm:ss") + "]"
          );
          console.log(`${timestr} Closed ${url} at ${err.message}`);
        });

      let ffstream = command.pipe();

      streamObj[url_md5] = {
        ffstream: ffstream,
        connects: [res]
      };

      ffstream.on("data", function (chunk) {
        streamObj[url_md5].connects.forEach(item => {
          item.write(chunk);
        });
      });
    }

    res.on("close", function () {
      let index = streamObj[url_md5].connects.indexOf(res);
      if (index > -1) {
        streamObj[url_md5].connects.splice(index, 1);
        console.log("closed", streamObj[url_md5].connects.length);
      }

      if (!streamObj[url_md5].connects.length) {
        streamObj[url_md5].ffstream.destroy();
        streamObj[url_md5] = null;
      }
    });
  };
回到顶部