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
© 版权声明
THE END
如果内容对您有所帮助,就支持一下吧!
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容