FFmpeg音视频循环推流及多RTMP端点配置问题
问题解决:MP3循环失效+多RTMP推流优化
一、修复MP3循环播放问题
你的MP3仅播放一次就停止,核心原因是输入级的-stream_loop在多流同步场景下易失效,改用音频滤镜aloop强制循环更可靠,同时需确保每个输入都配置实时读取参数。
修正后的FFmpeg命令
ffmpeg -re -stream_loop -1 -i ./ad/promo.gif \ -re -stream_loop -1 -i ./mp3s/rel.mp3 \ -acodec aac -b:a 64k \ -vcodec libx264 -b:v 200k -filter:v scale=w=1920:h=1080:flags=fast_bilinear \ -g 15 -r 15 -pix_fmt yuv420p -preset ultrafast \ -af "aloop=-1:size=0" \ -f flv rtmp://your-first-endpoint
对应的fluent-ffmpeg代码
const command = ffmpeg() .input(gifPath) .inputOption('-re') .inputOption('-stream_loop -1') .input(mp3Path) .inputOption('-re') // 给音频输入添加实时读取参数,确保和视频流同步 .inputOption('-stream_loop -1') .audioCodec('aac') .withAudioBitrate('64k') .audioFilters('aloop=-1:size=0') // 强制音频无限循环 .withSize('1920x1080') .addOutputOption('-filter:v scale=w=1920:h=1080:flags=fast_bilinear') // 更快的缩放算法 .withVideoCodec('libx264') .videoBitrate('200k') .addOutputOptions('-g 15') .addOutputOptions('-r 15') .outputOptions('-pix_fmt yuv420p') .addOutputOptions('-preset ultrafast') .output(stream)
说明:
aloop=-1:size=0:-1表示无限循环,size=0指定以整个音频流为循环单元- 给音频输入加
-re:确保音频按实时速率读取,避免因流不同步导致循环中断
二、多RTMP端点推流+降低CPU占用
要同时推送到多个RTMP端点且最小化CPU消耗,使用FFmpeg的tee muxer是最优方案——仅编码一次,复制流到多个输出,比多次编码节省大量CPU资源。
1. 使用tee的FFmpeg命令示例
ffmpeg -re -stream_loop -1 -i ./ad/promo.gif \ -re -stream_loop -1 -i ./mp3s/rel.mp3 \ -acodec aac -b:a 64k \ -vcodec libx264 -b:v 200k -filter:v scale=w=1920:h=1080:flags=fast_bilinear \ -g 15 -r 15 -pix_fmt yuv420p -preset ultrafast \ -af "aloop=-1:size=0" \ -f tee "[f=flv]rtmp://endpoint1|[f=flv]rtmp://endpoint2|[f=flv]rtmp://endpoint3"
2. 对应的fluent-ffmpeg代码
const command = ffmpeg() .input(gifPath) .inputOption('-re') .inputOption('-stream_loop -1') .input(mp3Path) .inputOption('-re') .inputOption('-stream_loop -1') .audioCodec('aac') .withAudioBitrate('64k') .audioFilters('aloop=-1:size=0') .withSize('1920x1080') .addOutputOption('-filter:v scale=w=1920:h=1080:flags=fast_bilinear') .withVideoCodec('libx264') .videoBitrate('200k') .addOutputOptions('-g 15') .addOutputOptions('-r 15') .outputOptions('-pix_fmt yuv420p') .addOutputOptions('-preset ultrafast') .outputOption('-f tee') .output('[f=flv]rtmp://endpoint1|[f=flv]rtmp://endpoint2|[f=flv]rtmp://endpoint3')
3. 额外降CPU技巧
- 启用硬件加速编码:如果机器支持GPU,替换
libx264为对应硬件编码器,比如NVIDIA显卡用h264_nvenc,Intel核显用h264_vaapi,能大幅降低CPU负载 - 简化滤镜:若GIF本身已是1920x1080分辨率,直接移除
scale滤镜 - 降低帧率:业务允许的话,可将
-r 15改为-r 10,进一步减少编码压力 - 固定GOP大小:保持
-g值等于帧率即可(如帧率15则-g 15),无需设置更大值
内容的提问来源于stack exchange,提问作者pedroribeiro98
相关产品推荐
相关产品推荐

