NodeJS 将 MKV 流式传输为 MP4 视频

问题描述 投票:0回答:1

我正在尝试将 MKV 视频即时流式传输为 MP4,而不保存转换后的文件

首先我尝试过没有转换:

public async streamById(req: Request, res: Response) {
    const movieId = req.params.id;
    const movie = await MovieModel.findById(movieId);
    if (!movie) {
      return res.status(404).send({ message: 'Movie not found' });
    }

    const filePath = movie.path;

    const stat = fs.statSync(filePath);
    const fileSize = stat.size;
    const range = req.headers.range;

    if (range) {
      const parts = range.replace(/bytes=/, '').split('-');
      const start = parseInt(parts[0], 10);
      const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;

      const chunksize = end - start + 1;
      const file = fs.createReadStream(filePath, { start, end });
      const head = {
        'Content-Range': `bytes ${start}-${end}/${fileSize}`,
        'Accept-Ranges': 'bytes',
        'Content-Length': chunksize,
        'Content-Type': 'video/mp4',
      };

      res.writeHead(206, head);
      file.pipe(res);
    } else {
      const head = {
        'Content-Length': fileSize,
        'Content-Type': 'video/mp4',
      };
      res.writeHead(200, head);
      fs.createReadStream(filePath).pipe(res);
    }
  }

正在运行,但没有音频

使用 ffmpeg 我收到错误:“转换期间出错:输出流已关闭”

const command = ffmpeg(file)
    .format('mp4')
    .audioCodec('aac')
    .videoCodec('libx264')
    .outputOptions('-movflags frag_keyframe+empty_moov')
    .outputOptions('-preset veryfast')
    .on('error', (err: any) => {
      console.error('Error during conversion:', err.message);
      res.end();
    })
    .on('end', () => {
      console.log('Conversion complete ');
      res.end();
    });

  // Pipe ffmpeg output directly to the response
  command.pipe(res, { end: true });
node.js ffmpeg mp4 mkv
1个回答
0
投票

首先我尝试过没有转换

是的,好吧,那是行不通的。 MP4/ISOBMFF 与 WebM/MKV/Matroska 完全不同。

正在运行,但没有音频

它并不是“有效”,而是浏览器忽略了您的

Content-Type
并“嗅探”了格式本身。那么,为什么视频效果不佳呢?浏览器可能不支持 MKV 文件中使用的任何编解码器。

即使您可以使用这种静态托管方法,您也可能不想为此使用 Node.js。任何普通的网络服务器(例如 Nginx)都可以很好地处理它。

使用 ffmpeg 我收到错误:“转换期间出错:输出流已关闭”

没有足够的代码来尝试重现您的问题...但首先,尝试将 MP4 输出传输到文件,看看是否可以做到这一点,以缩小问题范围。

如果这有效,那么需要记住的一件事是,如果浏览器认为可以提前获取 MOOV 或其他什么,它通常会发出多个媒体流请求。确保您使用常规分块传输编码,而不是指定大小。

© www.soinside.com 2019 - 2024. All rights reserved.