鸿蒙(API 12 Beta3版)【使用AVScreenCapture录屏取原始码流(C/C++)】视频播放与录制

屏幕录制主要为主屏幕录屏功能。

开发者可以调用录屏(AVScreenCapture)模块的C API接口,完成屏幕录制,采集设备内、麦克风等的音视频源数据。当开发直播、办公等应用时,可以调用录屏模块获取音视频原始码流,然后通过流的方式流转到其他模块处理,达成直播时共享桌面的场景。

录屏模块和窗口(Window)、图形(Graphic)等模块协同完成整个视频采集的流程。

当前在进行屏幕录制时默认使用主屏,图形默认根据主屏生产录屏帧数据到显示数据缓冲队列,录屏框架从显示数据缓冲队列获取数据进行相应处理。

使用AVScreenCapture录制屏幕涉及到AVScreenCapture实例的创建、音视频采集参数的配置、采集的开始与停止、资源的释放等。

开始屏幕录制时正在通话中或者屏幕录制过程中来电,录屏将自动停止。因通话中断的录屏会上报OH_SCREEN_CAPTURE_STATE_STOPPED_BY_CALL状态。

本开发指导将以完成一次屏幕数据录制的过程为例,向开发者讲解如何使用AVScreenCapture进行屏幕录制。

如果配置了采集麦克风音频数据,需对应配置麦克风权限ohos.permission.MICROPHONE和申请长时任务,配置方式请参见[向用户申请权限]、[申请长时任务]。

开发步骤及注意事项

使用AVScreenCapture时要明确其状态的变化,在创建实例后,调用对应的方法可以进入指定的状态实现对应的行为。

在确定的状态下执行不合适的方法会导致AVScreenCapture发生错误,开发者需要在调用状态转换的方法前进行状态检查,避免程序运行异常。

在 CMake 脚本中链接动态库

target_link_libraries(entry PUBLIC libnative_avscreen_capture.so libnative_buffer.so libnative_media_core.so)
  1. 添加头文件。
#include "napi/native_api.h"
#include <multimedia/player_framework/native_avscreen_capture.h>
#include <multimedia/player_framework/native_avscreen_capture_base.h>
#include <multimedia/player_framework/native_avscreen_capture_errors.h>
#include <native_buffer/native_buffer.h>
#include <fcntl.h>
#include "string"
#include "unistd.h"
  1. 创建AVScreenCapture实例capture。

    OH_AVScreenCapture* capture = OH_AVScreenCapture_Create();
    
  2. 配置屏幕录制参数。

    创建AVScreenCapture实例capture后,可以设置屏幕录制所需要的参数。

OH_AudioCaptureInfo miccapinfo = {
    .audioSampleRate = 16000,
    .audioChannels = 2,
    .audioSource = OH_MIC
};

OH_VideoCaptureInfo videocapinfo = {
    .videoFrameWidth = 720,
    .videoFrameHeight = 1080,
    .videoSource = OH_VIDEO_SOURCE_SURFACE_RGBA
};

OH_AudioInfo audioinfo = {
    .micCapInfo = miccapinfo,
};

OH_VideoInfo videoinfo = {
    .videoCapInfo = videocapinfo
};

OH_AVScreenCaptureConfig config = {
    .captureMode = OH_CAPTURE_HOME_SCREEN,
    .dataType = OH_ORIGINAL_STREAM,
    .audioInfo = audioinfo,
    .videoInfo = videoinfo
};

OH_AVScreenCapture_Init(capture, config);
  1. 设置麦克风开关。
bool isMic = true;
OH_AVScreenCapture_SetMicrophoneEnabled(capture, isMic);
  1. 回调函数的设置,主要监听录屏过程中的错误事件的发生,音频流和视频流数据的产生事件。
OH_AVScreenCapture_SetErrorCallback(capture, OnError, userData);
OH_AVScreenCapture_SetStateCallback(capture, OnStateChange, userData);
OH_AVScreenCapture_SetDataCallback(capture, OnBufferAvailable, userData);
  1. 调用StartScreenCapture()方法开始进行屏幕录制。

    OH_AVScreenCapture_StartScreenCapture(capture);
    

    或调用StartScreenCaptureWithSurface方法以Surface模式进行屏幕录制。

    OH_AVScreenCapture_StartScreenCaptureWithSurface(capture, window);
    
  2. 调用StopScreenCapture()方法停止录制。

    OH_AVScreenCapture_StopScreenCapture(capture);
    
  3. 在回调OnBufferAvailable()中获取并处理音频视频原始码流数据.

OnBufferAvailable(OH_AVScreenCapture *capture, OH_AVBuffer *buffer,
    OH_AVScreenCaptureBufferType bufferType, int64_t timestamp, void *userData)
  1. 调用Release()方法销毁实例,释放资源。

    OH_AVScreenCapture_Release(capture);
    

完整示例

下面展示了使用AVScreenCapture屏幕录制的完整示例代码。

目前阶段流程结束后返回的buffer为原始码流,针对原始码流可以进行编码并以mp4等文件格式保存以供播放。

说明

编码格式当前阶段仅作预留,待后续版本实现。

#include "napi/native_api.h"
#include <multimedia/player_framework/native_avscreen_capture.h>
#include <multimedia/player_framework/native_avscreen_capture_base.h>
#include <multimedia/player_framework/native_avscreen_capture_errors.h>
#include <multimedia/player_framework/native_avbuffer.h>
#include <native_buffer/native_buffer.h>
#include <fcntl.h>
#include "string"
#include "unistd.h"

void OnError(OH_AVScreenCapture *capture, int32_t errorCode, void *userData) {
    (void)capture;
    (void)errorCode;
    (void)userData;
}

void OnStateChange(struct OH_AVScreenCapture *capture, OH_AVScreenCaptureStateCode stateCode, void *userData) {
    (void)capture;
    
    if (stateCode == OH_SCREEN_CAPTURE_STATE_STARTED) {
        // 处理状态变更
    }
    if (stateCode == OH_SCREEN_CAPTURE_STATE_STOPPED_BY_CALL) {
        // 通话中断状态处理
    }
    if (stateCode == OH_SCREEN_CAPTURE_STATE_INTERRUPTED_BY_OTHER) {
        // 处理状态变更
    }
    (void)userData;
}

void OnBufferAvailable(OH_AVScreenCapture *capture, OH_AVBuffer *buffer,
    OH_AVScreenCaptureBufferType bufferType, int64_t timestamp, void *userData) {
    // 获取解码后信息 可以参考编解码接口
    int bufferLen = OH_AVBuffer_GetCapacity(buffer);
    OH_NativeBuffer *nativeBuffer = OH_AVBuffer_GetNativeBuffer(buffer);
    OH_NativeBuffer_Config config;
    OH_NativeBuffer_GetConfig(nativeBuffer, &config);
    int32_t videoSize= config.height * config.width * 4;
    uint8_t *buf = OH_AVBuffer_GetAddr(buffer);
    if (bufferType == OH_SCREEN_CAPTURE_BUFFERTYPE_VIDEO) {
        // 处理视频buffer
    } else if (bufferType == OH_SCREEN_CAPTURE_BUFFERTYPE_AUDIO_INNER) {
        // 处理内录buffer
    } else if (bufferType == OH_SCREEN_CAPTURE_BUFFERTYPE_AUDIO_MIC) {
        // 处理麦克风buffer
    }
}

struct OH_AVScreenCapture *capture;
static napi_value Screencapture(napi_env env, napi_callback_info info) {
    // 从js端获取窗口id number[]
    std::vector<int> windowIdsExclude = {};
    size_t argc = 1;
    napi_value args[1] = {nullptr};
    // 获取参数
    napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
    // 获取数组长度
    uint32_t array_length;
    napi_get_array_length(env, args[0], &array_length);
    // 读初窗口id
    for (int32_t i = 0; i < array_length; i++) {
        napi_value temp;
        napi_get_element(env, args[0], i, &temp);
        uint32_t tempValue;
        napi_get_value_uint32(env, temp, &tempValue);
        windowIdsExclude.push_back(tempValue);
     }
    // 实例化ScreenCapture
    capture = OH_AVScreenCapture_Create();
    
    // 设置回调 
    OH_AVScreenCapture_SetErrorCallback(capture, OnError, nullptr);
    OH_AVScreenCapture_SetStateCallback(capture, OnStateChange, nullptr);
    OH_AVScreenCapture_SetDataCallback(capture, OnBufferAvailable, nullptr);

    // 可选 配置录屏旋转,此接口在感知到手机屏幕旋转时调用,如果手机的屏幕实际上没有发生旋转,调用接口是无效的。
    OH_AVScreenCapture_SetCanvasRotation(capture, true);
    // 可选 [过滤音频]
    OH_AVScreenCapture_ContentFilter *contentFilter= OH_AVScreenCapture_CreateContentFilter();
    // 添加过滤通知音
    OH_AVScreenCapture_ContentFilter_AddAudioContent(contentFilter, OH_SCREEN_CAPTURE_NOTIFICATION_AUDIO);
    // 排除指定窗口id
    OH_AVScreenCapture_ContentFilter_AddWindowContent(contentFilter, &windowIdsExclude[0],
                                                      static_cast<int32_t>(windowIdsExclude.size()));

    OH_AVScreenCapture_ExcludeContent(capture, contentFilter);

    // 初始化录屏,传入配置信息OH_AVScreenRecorderConfig
    OH_AudioCaptureInfo miccapinfo = {.audioSampleRate = 16000, .audioChannels = 2, .audioSource = OH_MIC};
    OH_VideoCaptureInfo videocapinfo = {
        .videoFrameWidth = 720, .videoFrameHeight = 1080, .videoSource = OH_VIDEO_SOURCE_SURFACE_RGBA};
    OH_AudioInfo audioinfo = {
        .micCapInfo = miccapinfo,
    };
    OH_VideoInfo videoinfo = {.videoCapInfo = videocapinfo};
    OH_AVScreenCaptureConfig config = {.captureMode = OH_CAPTURE_HOME_SCREEN,
                                       .dataType = OH_ORIGINAL_STREAM,
                                       .audioInfo = audioinfo,
                                       .videoInfo = videoinfo};
    OH_AVScreenCapture_Init(capture, config);

    // 可选 [Surface模式]
    // 通过 MIME TYPE 创建编码器,系统会根据MIME创建最合适的编码器。
    // OH_AVCodec *codec = OH_VideoEncoder_CreateByMime(OH_AVCODEC_MIMETYPE_VIDEO_AVC);    
    // 从视频编码器获取输入Surface
    // OH_AVErrCode OH_VideoEncoder_GetSurface(codec, window);
    // 启动编码器
    // int32_t retEnc = OH_VideoEncoder_Start(codec);
    // 指定surface开始录屏
    // int32_t retStart = OH_AVScreenCapture_StartScreenCaptureWithSurface(capture, window); 

    // 开始录屏
    OH_AVScreenCapture_StartScreenCapture(capture);

    // mic开关设置
    OH_AVScreenCapture_SetMicrophoneEnabled(capture, true);

    sleep(10); // 录制10s
    // 结束录屏
    OH_AVScreenCapture_StopScreenCapture(capture);
    // 释放ScreenCapture
    OH_AVScreenCapture_Release(capture);
    // 返回调用结果,示例仅返回随意值
    napi_value sum;
    napi_create_double(env, 5, &sum);

    return sum;
}

最后呢

很多开发朋友不知道需要学习那些鸿蒙技术?鸿蒙开发岗位需要掌握那些核心技术点?为此鸿蒙的开发学习必须要系统性的进行。

而网上有关鸿蒙的开发资料非常的少,假如你想学好鸿蒙的应用开发与系统底层开发。你可以参考这份资料,少走很多弯路,节省没必要的麻烦。由两位前阿里高级研发工程师联合打造的《鸿蒙NEXT星河版OpenHarmony开发文档》里面内容包含了(ArkTS、ArkUI开发组件、Stage模型、多端部署、分布式应用开发、音频、视频、WebGL、OpenHarmony多媒体技术、Napi组件、OpenHarmony内核、Harmony南向开发、鸿蒙项目实战等等)鸿蒙(Harmony NEXT)技术知识点

如果你是一名Android、Java、前端等等开发人员,想要转入鸿蒙方向发展。可以直接领取这份资料辅助你的学习。下面是鸿蒙开发的学习路线图。

在这里插入图片描述

针对鸿蒙成长路线打造的鸿蒙学习文档。话不多说,我们直接看详细鸿蒙(OpenHarmony )手册(共计1236页)与鸿蒙(OpenHarmony )开发入门视频,帮助大家在技术的道路上更进一步。

  • 《鸿蒙 (OpenHarmony)开发学习视频》
  • 《鸿蒙生态应用开发V2.0白皮书》
  • 《鸿蒙 (OpenHarmony)开发基础到实战手册》
  • OpenHarmony北向、南向开发环境搭建
  • 《鸿蒙开发基础》
  • 《鸿蒙开发进阶》
  • 《鸿蒙开发实战》

在这里插入图片描述

总结

鸿蒙—作为国家主力推送的国产操作系统。部分的高校已经取消了安卓课程,从而开设鸿蒙课程;企业纷纷跟进启动了鸿蒙研发。

并且鸿蒙是完全具备无与伦比的机遇和潜力的;预计到年底将有 5,000 款的应用完成原生鸿蒙开发,未来将会支持 50 万款的应用。那么这么多的应用需要开发,也就意味着需要有更多的鸿蒙人才。鸿蒙开发工程师也将会迎来爆发式的增长,学习鸿蒙势在必行! 自↓↓↓拿
1

  • 16
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用ffmpeg 6.0录制屏幕并推流到RTMP服务器的C++示例代码: ``` #include <iostream> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <math.h> #include <sys/time.h> #ifdef __cplusplus extern "C" { #endif #include <libavcodec/avcodec.h> #include <libavformat/avformat.h> #include <libavutil/opt.h> #include <libavutil/imgutils.h> #include <libswscale/swscale.h> #ifdef __cplusplus } #endif #define SCREEN_WIDTH 1280 #define SCREEN_HEIGHT 720 #define STREAM_URL "rtmp://your_streaming_server_url" int main(int argc, char* argv[]) { AVFormatContext* output_format_ctx = NULL; AVOutputFormat* output_format = NULL; AVStream* output_stream = NULL; AVCodec* output_codec = NULL; AVCodecContext* output_codec_ctx = NULL; AVFrame* frame = NULL; uint8_t* frame_buffer = NULL; int ret = 0; int frame_count = 0; struct timeval last_time, current_time; int64_t last_pts = 0, current_pts = 0; int framerate = 30; // initialize ffmpeg av_register_all(); avformat_network_init(); // open output format context ret = avformat_alloc_output_context2(&output_format_ctx, NULL, "flv", STREAM_URL); if (ret < 0) { std::cerr << "Failed to allocate output format context" << std::endl; return -1; } output_format = output_format_ctx->oformat; // open output codec output_codec = avcodec_find_encoder_by_name("libx264"); if (!output_codec) { std::cerr << "Failed to find codec" << std::endl; return -1; } output_stream = avformat_new_stream(output_format_ctx, output_codec); if (!output_stream) { std::cerr << "Failed to allocate output stream" << std::endl; return -1; } output_codec_ctx = avcodec_alloc_context3(output_codec); if (!output_codec_ctx) { std::cerr << "Failed to allocate codec context" << std::endl; return -1; } output_codec_ctx->codec_id = output_format->video_codec; output_codec_ctx->codec_type = AVMEDIA_TYPE_VIDEO; output_codec_ctx->width = SCREEN_WIDTH; output_codec_ctx->height = SCREEN_HEIGHT; output_codec_ctx->time_base = (AVRational){1, framerate}; output_codec_ctx->framerate = (AVRational){framerate, 1}; output_codec_ctx->gop_size = framerate; output_codec_ctx->pix_fmt = AV_PIX_FMT_YUV420P; av_opt_set(output_codec_ctx->priv_data, "preset", "ultrafast", 0); if (output_format->flags & AVFMT_GLOBALHEADER) { output_codec_ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; } ret = avcodec_open2(output_codec_ctx, output_codec, NULL); if (ret < 0) { std::cerr << "Failed to open codec" << std::endl; return -1; } ret = avcodec_parameters_from_context(output_stream->codecpar, output_codec_ctx); if (ret < 0) { std::cerr << "Failed to copy codec parameters to stream" << std::endl; return -1; } // open output file ret = avio_open(&output_format_ctx->pb, STREAM_URL, AVIO_FLAG_WRITE); if (ret < 0) { std::cerr << "Failed to open output file" << std::endl; return -1; } ret = avformat_write_header(output_format_ctx, NULL); if (ret < 0) { std::cerr << "Failed to write header" << std::endl; return -1; } // allocate frame buffer frame = av_frame_alloc(); if (!frame) { std::cerr << "Failed to allocate frame" << std::endl; return -1; } frame_buffer = (uint8_t*)av_malloc(av_image_get_buffer_size(output_codec_ctx->pix_fmt, output_codec_ctx->width, output_codec_ctx->height, 1)); av_image_fill_arrays(frame->data, frame->linesize, frame_buffer, output_codec_ctx->pix_fmt, output_codec_ctx->width, output_codec_ctx->height, 1); // initialize time gettimeofday(&last_time, NULL); last_pts = 0; // main loop while (true) { // read screen data AVFrame* raw_frame = av_frame_alloc(); if (!raw_frame) { std::cerr << "Failed to allocate raw frame" << std::endl; return -1; } raw_frame->format = AV_PIX_FMT_BGR0; raw_frame->width = SCREEN_WIDTH; raw_frame->height = SCREEN_HEIGHT; ret = av_frame_get_buffer(raw_frame, 32); if (ret < 0) { std::cerr << "Failed to allocate raw frame buffer" << std::endl; return -1; } ret = av_read_frame(raw_frame, NULL); if (ret < 0) { std::cerr << "Failed to read screen data" << std::endl; return -1; } // convert color space SwsContext* sws_ctx = sws_getContext(raw_frame->width, raw_frame->height, (AVPixelFormat)raw_frame->format, output_codec_ctx->width, output_codec_ctx->height, output_codec_ctx->pix_fmt, SWS_BILINEAR, NULL, NULL, NULL); if (!sws_ctx) { std::cerr << "Failed to initialize color space conversion" << std::endl; return -1; } ret = sws_scale(sws_ctx, raw_frame->data, raw_frame->linesize, 0, raw_frame->height, frame->data, frame->linesize); if (ret < 0) { std::cerr << "Failed to convert color space" << std::endl; return -1; } // set pts and dts gettimeofday(&current_time, NULL); current_pts = (int64_t)round((double)current_time.tv_sec * 1000000.0 + (double)current_time.tv_usec); if (frame_count == 0) { last_pts = current_pts; } frame->pts = (int64_t)(round((double)(current_pts - last_pts) / 1000000.0 * framerate)); frame->pkt_dts = frame->pts; // encode and write frame AVPacket pkt = {0}; av_init_packet(&pkt); int got_packet = 0; ret = avcodec_encode_video2(output_codec_ctx, &pkt, frame, &got_packet); if (ret < 0) { std::cerr << "Failed to encode frame" << std::endl; return -1; } if (got_packet) { pkt.stream_index = output_stream->index; pkt.pts = av_rescale_q(frame->pts, output_codec_ctx->time_base, output_stream->time_base); pkt.dts = av_rescale_q(frame->pkt_dts, output_codec_ctx->time_base, output_stream->time_base); pkt.duration = av_rescale_q(frame->pkt_duration, output_codec_ctx->time_base, output_stream->time_base); ret = av_interleaved_write_frame(output_format_ctx, &pkt); if (ret < 0) { std::cerr << "Failed to write frame" << std::endl; return -1; } } av_packet_unref(&pkt); // update frame count and last time frame_count++; last_time = current_time; // release resources sws_freeContext(sws_ctx); av_frame_free(&raw_frame); // sleep to control frame rate usleep((int)(1000000.0 / framerate)); } // close output file ret = av_write_trailer(output_format_ctx); if (ret < 0) { std::cerr << "Failed to write trailer" << std::endl; return -1; } avcodec_free_context(&output_codec_ctx); avio_close(output_format_ctx->pb); avformat_free_context(output_format_ctx); av_frame_free(&frame); av_free(frame_buffer); return 0; } ``` 在代码中,我们使用libx264编码器将屏幕数据编码为H.264格式,并将其推流到RTMP服务器。请注意,由于屏幕数据的帧率非常高,我们需要使用usleep函数来限制帧速率,以避免推流过程中出现缓冲区溢出等问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值