有人说直接使用pipe不就行了, 没那么简单, 实践告诉你真相,比如下列代码

app_express.ws("/video", function(ws, req) {
    console.log("[server] coonected to ws video")
    ws.send("hello client ")
	ffmpeg("test.264").noAudio().videoCodec('libx264').format('flv')
        .on('error', function(error) {
            console.log("error ffmpeg", error);
        })
        .on('end', function() {
            console.log('exchanged end ffmpeg');
            // res.end();
        }).pipe(ws);
});

执行到上述代码时,报了以下错误

TypeError: dest.write is not a function at ReadStream.ondata (_stream_readable.js:666:20)

具体原因不明,个人猜测是ws没有write方法,只有send方法。
于是转变思路,总之是不能再保存为文件再发送,于是还是去官网api找答案,相信肯定会有,于是发现了这一句。
github地址: 传送门
在这里插入图片描述
意思大致是如果不给pipe方法传递任何参数,就将返回一个流对象,这不就有了吗!!于是

app_express.ws("/video", function(ws, req) {
    console.log("[server] coonected to ws video")
    ws.send("hello client ")
    var ffmpegStream = fmpeg("test.264").noAudio().videoCodec('libx264').format('flv')
        .on('error', function(error) {
            console.log("error ffmpeg", error);
        })
        .on('end', function() {
            console.log('exchanged end ffmpeg');
            // res.end();
        }).pipe();
    ffmpegStream.on('data', (chunk) => {
        console.log(chunk.length, chunk);
        ws.send(chunk);
    }).on('end', () => {
        console.log("ffmpeg pipe end");
    });
});

顺利执行,博客完!!!

附参考地址:

  1. github官网地址
  2. 腾讯云大神做的中文翻译地址

更多推荐