You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为node-media-server搭建的RTMP服务器实现直播回放回退功能

实现RTMP服务器的10秒流回退功能

我使用node-media-server库搭建了本地RTMP媒体服务器,该服务器接收来自Streamlabs的媒体流,通过localhost链接可正常访问且运行无异常。当前服务器配置代码如下:

const NodeMediaServer = require("node-media-server");

const config = {
  rtmp: {
    port: 1935,
    chunk_size: 60000,
    gop_cache: true,
    ping: 30,
    ping_timeout: 60,
  },
  http: {
    port: 8000,
    allow_origin: "*",
  },
};

var nms = new NodeMediaServer(config);
nms.run();

目前仅能观看实时流,无法回退10秒查看历史内容,因为媒体流未被存储,请问有哪些可行的解决方法?


可行解决方案

1. 利用node-media-server的录制功能实现本地缓存

node-media-server本身支持流录制,可配置自动录制传入的RTMP流,同时通过控制录制文件的时长或大小,保留最近10秒的内容。

修改配置添加record字段:

const config = {
  rtmp: {
    port: 1935,
    chunk_size: 60000,
    gop_cache: true,
    ping: 30,
    ping_timeout: 60,
  },
  http: {
    port: 8000,
    allow_origin: "*",
  },
  record: {
    root: './recordings', // 需提前创建存储目录
    record: true,
    split: 10, // 每10秒生成一个录制片段
    deleteDelay: 11, // 延迟11秒删除旧片段,确保保留最近10秒内容
    autoCleanup: true // 自动清理过期片段
  }
};

后续可通过HTTP服务访问录制片段,或在播放器中实现切换历史片段的逻辑。

2. 内存缓存GOP实现低延迟回退

RTMP流的关键帧(GOP)是解码基础,可在服务器端维护内存缓存池,存储最近若干个GOP包,总时长控制在10秒左右。

通过监听node-media-server的prePublish和raw事件处理流数据:

const cache = [];
const MAX_CACHE_DURATION = 10; // 目标缓存时长(秒)

nms.on('prePublish', (id, StreamPath, args) => {
  // 新流发布时清空缓存
  cache.length = 0;
});

nms.on('raw', (id, data) => {
  // 记录数据块的时间戳
  const timestamp = Date.now();
  cache.push({ data, timestamp });
  
  // 清理超过10秒的旧数据
  const cutoffTime = Date.now() - MAX_CACHE_DURATION * 1000;
  while (cache.length > 0 && cache[0].timestamp < cutoffTime) {
    cache.shift();
  }
});

这种方式适合低延迟场景,但需注意高码率流的内存占用,需合理控制缓存大小。

3. 结合HLS协议实现时移播放

将RTMP流转码为HLS格式,HLS本身支持时移功能。node-media-server可配置HLS输出,客户端通过HLS播放器即可实现回退播放。

修改配置添加hls字段:

const config = {
  rtmp: {
    port: 1935,
    chunk_size: 60000,
    gop_cache: true,
    ping: 30,
    ping_timeout: 60,
  },
  http: {
    port: 8000,
    allow_origin: "*",
  },
  hls: {
    port: 8001,
    allow_origin: "*",
    chunk_size: 102400,
    playlist_length: 5, // 保留5个切片(每个切片约2秒,总时长10秒)
    fmp4: true
  }
};

客户端访问http://localhost:8001/live/[stream-key].m3u8,使用video.js、hls.js等现代播放器即可实现10秒回退功能。


内容的提问来源于stack exchange,提问作者Ajit Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 22:55:28