当前位置: 首页 > news >正文

C++与C#实战:FFmpeg屏幕录制开发指南

基于FFmpeg使用C#和C++开发

以下是一些基于FFmpeg使用C#和C++开发的简单屏幕录制软件示例,涵盖不同平台和功能需求。这些示例可作为学习或项目开发的起点。

使用C++开发FFmpeg屏幕录制

基础屏幕录制(Windows)
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libswscale/swscale.h>
#include <Windows.h>int main() {AVFormatContext* formatContext = nullptr;avformat_alloc_output_context2(&formatContext, nullptr, "flv", "output.flv");// 配置视频流(使用GDI抓屏)AVStream* stream = avformat_new_stream(formatContext, nullptr);stream->codecpar->codec_id = AV_CODEC_ID_H264;stream->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;stream->codecpar->width = GetSystemMetrics(SM_CXSCREEN);stream->codecpar->height = GetSystemMetrics(SM_CYSCREEN);stream->codecpar->format = AV_PIX_FMT_BGR0;avio_open(&formatContext->pb, formatContext->filename, AVIO_FLAG_WRITE);avformat_write_header(formatContext, nullptr);// 模拟抓帧(实际需用GDI/DXGI)AVPacket pkt;av_new_packet(&pkt, 0);av_write_frame(formatContext, &pkt);av_write_trailer(formatContext);avio_closep(&formatContext->pb);
}

使用DXGI抓屏(高性能)
#include <dxgi.h>
#include <d3d11.h>
// 需结合FFmpeg的硬件加速编码(如h264_nvenc)
Linux X11屏幕录制
#include <X11/Xlib.h>
// 使用XGetImage抓屏后通过FFmpeg编码

使用C#开发FFmpeg屏幕录制

通过Process调用FFmpeg
using System.Diagnostics;Process.Start("ffmpeg", "-f gdigrab -i desktop -c:v libx264 output.mp4");
使用FFmpeg.AutoGen(原生封装)
using FFmpeg.AutoGen;public unsafe class Recorder {public void Start() {AVFormatContext* fmtCtx = null;ffmpeg.avformat_alloc_output_context2(&fmtCtx, null, "mp4", "output.mp4");// 配置视频流参数AVStream* stream = ffmpeg.avformat_new_stream(fmtCtx, null);AVCodecParameters* codecpar = stream->codecpar;codecpar->codec_id = AVCodecID.AV_CODEC_ID_H264;codecpar->width = 1920;codecpar->height = 1080;}
}
结合AForge.NET抓屏
using AForge.Video.DirectShow;
// 通过ScreenCaptureStream获取帧后传给FFmpeg编码

功能扩展示例

录制系统音频
ffmpeg -f dshow -i audio="麦克风" -f gdigrab -i desktop output.mkv
区域录制
Process.Start("ffmpeg", "-f gdigrab -offset_x 100 -offset_y 200 -video_size 1280x720 -i desktop -c:v libx264 region.mp4");
硬件加速录制(NVIDIA)
av_dict_set(&opts, "preset", "fast", 0);
av_dict_set(&opts, "c:v", "h264_nvenc", 0);

其他语言/平台示例

Python调用FFmpeg
import subprocess
subprocess.run(["ffmpeg", "-f", "avfoundation", "-i", "1", "output.mov"])  # macOS
Electron桌面应用
const { exec } = require('child_process');
exec('ffmpeg -f x11grab -i :0.0 output.mp4');

关键注意事项

  • 分辨率设置:需与显示器实际分辨率匹配
  • 帧率控制:通过-r参数指定(如-r 30
  • 编码选择
    • 软件编码:libx264(CPU)
    • 硬件编码:h264_nvenc(NVIDIA)、h264_amf(AMD)
  • 内存管理:C++示例需手动释放FFmpeg资源

完整项目建议参考:

  • ScreenRecorderLib(C#库)
  • QtFFmpegScreenRecorder(C++/Qt实现)
  • OBS Studio开源代码(高级参考)

基于C++和FFmpeg的移动端开发实例

以下是一些基于C++和FFmpeg的移动端开发实例,涵盖音视频处理、编解码、流媒体等常见场景。所有示例均适配Android/iOS平台,代码结构简洁,适合快速实现功能集成。

音视频基础处理

解码本地视频文件
使用avformat_open_inputavcodec_send_packet实现视频解码,输出YUV帧数据:

AVFormatContext* fmt_ctx = nullptr;
avformat_open_input(&fmt_ctx, input_path, nullptr, nullptr);
AVCodecContext* codec_ctx = avcodec_alloc_context3(decoder);
avcodec_parameters_to_context(codec_ctx, fmt_ctx->streams[video_index]->codecpar);
avcodec_open2(codec_ctx, decoder, nullptr);

提取音频PCM数据
通过swr_convert将音频重采样为PCM格式:

SwrContext* swr = swr_alloc_set_opts(nullptr, out_ch_layout, out_sample_fmt, out_sample_rate,in_ch_layout, in_sample_fmt, in_sample_rate, 0, nullptr);
swr_convert(swr, &out_buffer, out_samples, (const uint8_t**)in_buffer, in_samples);

高级功能实现

视频实时滤镜
应用FFmpeg滤镜链实现色彩调整(需链接libavfilter):

AVFilterContext* buffersrc = avfilter_graph_alloc_filter(graph, buffersrc_c, "src");
avfilter_graph_create_filter(&buffersink, buffersink_c, "sink", nullptr, nullptr, graph);
AVFilterInOut* outputs = avfilter_inout_alloc();
outputs->name = av_strdup("in");
outputs->filter_ctx = buffersrc;

硬件加速解码
Android上使用MediaCodec硬解(NDK集成):

AVBufferRef* hw_device_ctx = nullptr;
av_hwdevice_ctx_create(&hw_device_ctx, AV_HWDEVICE_TYPE_MEDIACODEC, nullptr, nullptr, 0);
codec_ctx->hw_device_ctx = av_buffer_ref(hw_device_ctx);

流媒体与网络

RTMP直播推流
配置输出流并发送数据包:

AVOutputFormat* ofmt = av_guess_format("flv", nullptr, nullptr);
avformat_alloc_output_context2(&out_fmt_ctx, ofmt, nullptr, rtmp_url);
avio_open(&out_fmt_ctx->pb, out_fmt_ctx->filename, AVIO_FLAG_WRITE);
avformat_write_header(out_fmt_ctx, nullptr);
av_interleaved_write_frame(out_fmt_ctx, &pkt);

HLS切片生成
设置分段参数并生成m3u8文件:

AVDictionary* opts = nullptr;
av_dict_set(&opts, "hls_time", "10", 0);
av_dict_set(&opts, "hls_list_size", "6", 0
http://www.dtcms.com/a/304295.html

相关文章:

  • 2025年KBS顶刊新算法-向光优化算法Phototropic growth algorithm-附Matlab免费代码
  • 从线下挂号到全流程智能问诊:智慧医院APP源码开发指南
  • MATLAB弹塑性固体有限元计算程序
  • 【LGR-234-Div.3】洛谷网校 7 月 CSP-J 模拟月赛 Cfz Round 6 「Cfz Round 6」Imaichi
  • 【PHP】通过IP获取IP所在地理位置(免费API接口)
  • Kruskal算法
  • gTest测试框架的安装与配置
  • HammerDB:一款免费开源的数据库基准测试工具
  • YOLOv11.pt 模型转换为 TFLite 和 NCNN 模型
  • PDF转Word免费工具!批量处理PDF压缩,合并, OCR识别, 去水印, 签名等全功能详解
  • CodeRush AI 助手进驻 Visual Studio:AiGen/AiFind 亮相(三)
  • Visual Studio的妙用
  • [极客大挑战 2019]FinalSQL
  • 如何查询并访问路由器的默认网关(IP地址)?
  • 大规模矩阵构建与高级算法应用
  • Unity 编辑器开发 之 Excel导表工具
  • Python爬虫01_Requests第一血获取响应数据
  • 香橙派One安装OctoPrint 实现控制3D打印机
  • WebRTC 2025全解析:从技术原理到商业落地
  • 容器技术原理(一):从根本上认识容器镜像
  • Linux boot 目录损坏如何修复:从救援模式到系统恢复
  • APK重打包流程
  • K8s集群两者不同的对外暴露服务的方式
  • 如何迁移gitlab到另一台服务器
  • Makefile 快速入门指南
  • LangChain和LangGraph 里面的 `create_react_agent`有什么不同
  • 机器学习—逻辑回归
  • VitePress学习-自定义主题
  • 使用 Django REST Framework 构建强大的 API
  • 在依赖关系正确的情况下,执行 mvn install 提示找不到软件包