最近开发了基于C#的推流器一直不大理想,终于在不懈努力以后研究了一点成果,这边作个笔记;本文着重在于讲解下如何使用ffmpeg进行简单的推流,看似简单几行代码没有官方的文档很吃力。并获取流的源代码:以下→服务器
#region RTMP推流(**已成功推流至服务器**) Network.Create() .WithSource(inputPath)//inputPath能够改为获取设备的视频流 .WithDest("rtmp://192.168.61.128/live/livestream")//能够根据本身的需求更新RTMP服务器地址 .WithFilter(new X264Filter { ConstantQuantizer = 20 }) .WithFilter(new ResizeFilter(Resolution.X720P)) .Push(); #endregion
Network.Create() .WithSource("rtmp://192.168.61.128/live/livestream")//inputPath能够改为获取设备的视频流 .WithDest(inputPath)//这个路径能够自由更改,若是是直播就不须要使用这个路径,直接读取流至播放器播放实时接收便可。 .WithFilter(new X264Filter { ConstantQuantizer = 20 }) .WithFilter(new ResizeFilter(Resolution.X720P)) .Pull();
以上分别是推流和获取流保存在本地的核心代码。spa
1:首先创建服务器与客户端的链接;3d
2:初始化服务器地址;code
3:初始化路径;orm
4:视频属性设定;视频
5:推/拉流操做;server
/// <summary> /// 推流到RTMP服务器 /// </summary> public void Push() { Validate(); if (_destType != TargetType.Live) { throw new ApplicationException("当推流到RTMP服务器的时候,源类型必须是'RtmpType.Live'类型."); } //参数为false的时候则为推流 var @params = GetParams(false); Processor.FFmpeg(@params); }
/// <summary> /// 把流从RTMP服务器拉取--读取视频数据 ==pull a stream from rtmp server /// </summary> public void Pull() { Validate(); if (!TestRtmpServer(_source, true)) throw new ApplicationException("RTMP服务器发送错误."); if (_sourceType != TargetType.Live) { throw new ApplicationException("必须是RTMP服务器."); } //参数为true的时候则为读取视频流 var @params = GetParams(false); Processor.FFmpeg(@params); }
/// <summary> /// 检测输出输入源以及过滤器 /// </summary> private void Validate() { if (_sourceType == TargetType.Default) throw new ApplicationException("源错误.请输入源!"); if (_destType == TargetType.Default) throw new ApplicationException("dest错误.请输入一个dest"); var supportFilters = new[] { "Resize", "Segment", "X264", "AudioRate", "AudioBitrate" }; if (_filters.Any(x => !supportFilters.Contains(x.Name))) { throw new ApplicationException(string.Format("过滤器不支持,过滤器只支持:{0} 类型", supportFilters.Aggregate(string.Empty, (current, filter) => current + (filter + ",")).TrimEnd(new[] { ',' }))); } }
这是推流所使用的方法,Validate()→这个方法主要用于:检测输出输入源以及过滤器;其次检测输入流的状态是否为文件(File仍是Live);最后调用ffmpeg进行处理输入的参数方法进行处理。blog
同理,获取流也是如此。开发
接下来演示下效果:(推流成功以后就会有以下图所示的效果,能够自行调用Directshow等第三方播放器或者自带的ffplay进行播放)文档
接下来是这个拉取流的效果:图中未完成读取的时候是下图
值得注意的是,接收是从你开始接收的位置开始的,视频推流是根据一帧一帧推送的,而咱们接收流的方式也是一帧一帧的接收,因此图中显示的实际上是已经播放到末尾的视频,这样防止了视频重复上传,重复下载。
备注:【思路仅供参考】