使用AVRecorder录制视频(C/C++)
=======================

AVRecorder支持开发音视频录制，集成了音频捕获，音频编码，视频编码，音视频封装功能，适用于实现简单视频录制并直接得到本地媒体文件的场景。

本开发指导将以“开始录制-暂停录制-恢复录制-停止录制”的一次流程为示例，向开发者讲解如何使用AVRecorder进行视频录制。

在进行应用开发的过程中，开发者可以通过AVRecorder的state属性主动获取当前状态，或使用OH\_AVRecorder\_SetStateCallback方法注册回调监听状态变化。开发过程中应严格遵循状态机要求，例如只能在started状态下调用pause()接口，只能在paused状态下调用resume()接口。

**图1** 录制状态变化示意图

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/6d/v3/G5nOazrKRBCKQpB5uhvx4A/zh-cn_image_0000002594668872.png?HW-CC-KV=V1&HW-CC-Date=20260612T073524Z&HW-CC-Expire=86400&HW-CC-Sign=FCFBE7DFEF9A7B128FA802061DCEC70367209F413DB4D924D6DC85BC34DE8365)

状态的详细说明请参考[AVRecorderState](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/arkts-apis-media-t#avrecorderstate9)。

#### 申请权限

在开发此功能前，开发者应根据实际需求申请相关权限：

*   当需要使用麦克风时，需要申请**ohos.permission.MICROPHONE**麦克风权限。申请方式请参考：[向用户申请授权](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/request-user-authorization)。
*   当需要使用相机拍摄时，需要申请**ohos.permission.CAMERA**相机权限。申请方式请参考：[向用户申请授权](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/request-user-authorization)。
*   当需要从图库读取图片或视频文件时，请优先使用媒体库[Picker选择媒体资源](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/photoaccesshelper-photoviewpicker)。
*   当需要保存图片或视频文件至图库时，请优先使用[安全控件保存媒体资源](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/photoaccesshelper-savebutton)。

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/22/v3/hONL_MRJSCeX9obssYiIZA/note_3.0-zh-cn.png?HW-CC-KV=V1&HW-CC-Date=20260612T073524Z&HW-CC-Expire=86400&HW-CC-Sign=BE3AB6A95867FD73F375AA0C62F11AC074658954D3E8A6713DEA2F3284218500)

仅应用需要克隆、备份或同步用户公共目录的图片、视频类文件时，可申请ohos.permission.READ\_IMAGEVIDEO、ohos.permission.WRITE\_IMAGEVIDEO权限来读写音视频文件，申请方式请参考[申请受控权限](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/declare-permissions-in-acl)，通过AGC审核后才能使用。为避免应用的上架申请被驳回，开发者应优先使用Picker/控件等替代方案，仅少量符合[特殊场景](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/restricted-permissions#ohospermissionread_imagevideo)的应用被允许申请受限权限。

#### 开发步骤及注意事项

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/51/v3/VjtDVohGQoCulyxxyifexA/note_3.0-zh-cn.png?HW-CC-KV=V1&HW-CC-Date=20260612T073524Z&HW-CC-Expire=86400&HW-CC-Sign=9E3B11DFD56AF69CB2C8FC2C474C71C5879A9755EE259E68387A3B2ECDDBED48)

AVRecorder只负责视频数据的处理，需要与视频数据采集模块配合才能完成视频录制。视频数据采集模块需要通过Surface将视频数据传递给AVRecorder进行数据处理。当前常用的数据采集模块为相机模块，具体请参考[相机-录像](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/native-camera-recording)。

文件的创建与存储，请参考[应用文件访问与管理](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/app-file-access)，默认存储在应用的沙箱路径之下，如需存储至图库，请使用[安全控件保存媒体资源](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/photoaccesshelper-savebutton)对沙箱内文件进行存储。

开发者通过引入[avrecorder.h](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/capi-avrecorder-h)、[avrecorder\_base.h](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/capi-avrecorder-base-h)和[native\_averrors.h](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/capi-native-averrors-h)头文件，使用视频录制相关API。

AVRecorder详细的API说明请参考[AVRecorder API参考](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/capi-avrecorder)。

在CMake脚本中链接动态库。

target\_link\_libraries(entry PUBLIC libavrecorder.so)

使用[native\_avformat.h](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/capi-native-avformat-h)相关接口时，需引入如下头文件。

#include <multimedia/player\_framework/native\_avformat.h>

并在CMake脚本中链接如下动态库。

target\_link\_libraries(entry PUBLIC libnative\_media\_core.so)

开发者使用系统日志能力时，需引入如下头文件。

#include <hilog/log.h>

并需要在CMake脚本中链接如下动态库。

target\_link\_libraries(entry PUBLIC libhilog\_ndk.z.so)

1.  创建AVRecorder实例，实例创建完成进入idle状态。
    
    #include <multimedia/player\_framework/avrecorder.h>
    #include <multimedia/player\_framework/avrecorder\_base.h>
    
    static struct OH\_AVRecorder \*g\_avRecorder = nullptr;
    g\_avRecorder = OH\_AVRecorder\_Create();
    
2.  设置业务需要的监听事件，监听状态变化及错误上报。
    
    | 事件类型 | 说明 |
    | :-- | :-- |
    | OnStateChange | 监听AVRecorder的状态改变。 |
    | OnError | 监听AVRecorder的错误信息。 |
    | OnUri | 监听AVRecorder生成媒体文件。 |
    
    // 设置状态回调。
    void OnStateChange(OH\_AVRecorder \*recorder, OH\_AVRecorder\_State state,
        OH\_AVRecorder\_StateChangeReason reason, void \*userData) {
        (void)recorder;
        (void)userData;
    
        // 将reason转换为字符串表示。
        const char \*reasonStr = (reason == OH\_AVRecorder\_StateChangeReason::AVRECORDER\_USER) ? "USER" :
                                (reason == OH\_AVRecorder\_StateChangeReason::AVRECORDER\_BACKGROUND) ? "BACKGROUND" : "UNKNOWN";
    
        if (state == OH\_AVRecorder\_State::AVRECORDER\_IDLE) {
            OH\_LOG\_INFO(LOG\_APP, "==NDKDemo== Recorder OnStateChange IDLE, reason: %{public}s", reasonStr);
            // 处理状态变更。
        }
        if (state == OH\_AVRecorder\_State::PREPARED) {
            OH\_LOG\_INFO(LOG\_APP, "==NDKDemo== Recorder OnStateChange PREPARED, reason: %{public}s", reasonStr);
            // 处理状态变更。
        }
        if (state == OH\_AVRecorder\_State::STARTED) {
            OH\_LOG\_INFO(LOG\_APP, "==NDKDemo== Recorder OnStateChange STARTED, reason: %{public}s", reasonStr);
            // 处理状态变更。
        }
        if (state == OH\_AVRecorder\_State::PAUSED) {
            OH\_LOG\_INFO(LOG\_APP, "==NDKDemo== Recorder OnStateChange PAUSED, reason: %{public}s", reasonStr);
            // 处理状态变更。
        }
        if (state == OH\_AVRecorder\_State::STOPPED) {
            OH\_LOG\_INFO(LOG\_APP, "==NDKDemo== Recorder OnStateChange STOPPED, reason: %{public}s", reasonStr);
            // 处理状态变更。
        }
        if (state == OH\_AVRecorder\_State::RELEASED) {
            OH\_LOG\_INFO(LOG\_APP, "==NDKDemo== Recorder OnStateChange RELEASED, reason: %{public}s", reasonStr);
            // 处理状态变更。
        }
        if (state == OH\_AVRecorder\_State::ERROR) {
            OH\_LOG\_ERROR(LOG\_APP, "==NDKDemo== Recorder OnStateChange ERROR, reason: %{public}s", reasonStr);
            // 处理状态变更。
        }
    }
    
    // 设置错误回调。
    void OnError(OH\_AVRecorder \*recorder, int32\_t errorCode, const char \*errorMsg, void \*userData) {
        (void)recorder;
        (void)userData;
        OH\_LOG\_INFO(LOG\_APP, "==NDKDemo== Recorder OnError errorCode: %{public}d, error message: %{public}s",
            errorCode, errorMsg);
    }
    
    // 设置生成媒体文件回调（fileGenerationMode选择AUTO\_CREATE时设置）。
    void OnUri(OH\_AVRecorder \*recorder, OH\_MediaAsset \*asset, void \*userData) {
        (void)recorder;
        (void)userData;
        if (asset != nullptr) {
            auto changeRequest = OH\_MediaAssetChangeRequest\_Create(asset);
            if (changeRequest == nullptr) {
                OH\_LOG\_ERROR(LOG\_APP, "==NDKDemo== changeRequest is null!");
                return;
            }
            MediaLibrary\_ImageFileType imageFileType = MEDIA\_LIBRARY\_IMAGE\_JPEG; // 待媒体库提供可用的VIDEO接口。
            uint32\_t result = OH\_MediaAssetChangeRequest\_SaveCameraPhoto(changeRequest, imageFileType);
            OH\_LOG\_INFO(LOG\_APP, "result of OH\_MediaAssetChangeRequest\_SaveCameraPhoto: %d", result);
    
            uint32\_t resultChange = OH\_MediaAccessHelper\_ApplyChanges(changeRequest);
            OH\_LOG\_INFO(LOG\_APP, "result of OH\_MediaAccessHelper\_ApplyChanges: %d", resultChange);
    
            OH\_MediaAsset\_Release(asset);
            OH\_MediaAssetChangeRequest\_Release(changeRequest);
        } else {
            OH\_LOG\_ERROR(LOG\_APP, "Received null media asset!");
        }
    }
    
3.  配置视频录制参数，调用OH\_AVRecorder\_Prepare()接口，此时进入prepared状态。
    
    ![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/75/v3/oHVhgpFbSo27kwdg05moSA/note_3.0-zh-cn.png?HW-CC-KV=V1&HW-CC-Date=20260612T073524Z&HW-CC-Expire=86400&HW-CC-Sign=D1D01EDD6D6FB55EB50CA92CFA94A98914F3A0ECDB68C03CFE0570BECAFA07F2)
    
    配置参数需要注意：
    
    *   配置参数之前需要确保完成对应权限的申请，请参考[申请权限](#申请权限)。
        
    *   prepare接口的入参OH\_AVRecorder\_Config中设置的音视频相关的配置参数，如示例代码所示。
        
    *   需要使用支持的[录制规格](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/media-kit-intro#支持的格式)，视频比特率、分辨率、帧率以实际硬件设备支持的范围为准。
        
    *   录制输出的url地址（即示例里avConfig中的url），形式为fd://xx (fd number)。需要调用基础文件操作接口实现应用文件访问能力，获取方式参考[应用文件访问与管理](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/native-fileio-guidelines)。
        
    
    void SetConfig(OH\_AVRecorder\_Config &config)
    {
        config.audioSourceType = AVRECORDER\_MIC;
        config.videoSourceType = AVRECORDER\_SURFACE\_ES;
    
        // 设置媒体属性。
        config.profile.audioBitrate = 96000;
        config.profile.audioChannels = 2;
        config.profile.audioCodec = AVRECORDER\_AUDIO\_AAC;
        config.profile.audioSampleRate = 48000;
    
        config.profile.videoBitrate = 2000000;
        config.profile.videoFrameWidth = 1280;
        config.profile.videoFrameHeight = 720;
        config.profile.videoFrameRate = 30;
        config.profile.videoCodec = AVRECORDER\_VIDEO\_AVC;
        config.profile.isHdr = false;
        config.profile.enableTemporalScale = false;
     
        config.profile.fileFormat = AVRECORDER\_CFT\_MPEG\_4;
        config.fileGenerationMode = AVRECORDER\_APP\_CREATE;
    
        config.metadata.videoOrientation = new char\[2\]; // 开发者需要自行释放申请的内存。
        if (config.metadata.videoOrientation != nullptr) {
            strcpy(config.metadata.videoOrientation, "0"); // 视频旋转角度，支持0、90、180、270。
        }
        OH\_LOG\_INFO(LOG\_APP, "==NDKDemo== videoOrientation: %{public}s", config.metadata.videoOrientation);
    
        config.metadata.location.latitude = 27.791863;
        config.metadata.location.longitude = 64.574687;
     }
    
     // 准备录制。
     static napi\_value PrepareAVRecorder(napi\_env env, napi\_callback\_info info)
     {
         (void)info;
         OH\_LOG\_INFO(LOG\_APP, "==NDKDemo== PrepareAVRecorder in!");
         g\_avRecorder = OH\_AVRecorder\_Create();
         OH\_LOG\_INFO(LOG\_APP, "==NDKDemo== AVRecorder Create ok! g\_avRecorder: %{public}p", g\_avRecorder);
         if (g\_avRecorder == nullptr) {
             OH\_LOG\_ERROR(LOG\_APP, "==NDKDemo== AVRecorder Create failed!");
         }
         OH\_AVRecorder\_Config \*config = new OH\_AVRecorder\_Config(); // 开发者需要自行释放申请的内存。
         
         SetConfig(\*config);
     
         // 1.设置URL（fileGenerationMode选择APP\_CREATE时设置）。
         const std::string AVRECORDER\_ROOT = "/data/storage/el2/base/files/";
         int32\_t outputFd = open((AVRECORDER\_ROOT + "avrecorder01.mp4").c\_str(), O\_RDWR | O\_CREAT, 0777); // 设置文件名。
         std::string fileUrl = "fd://" + std::to\_string(outputFd);
         config->url = const\_cast<char \*>(fileUrl.c\_str());
         OH\_LOG\_INFO(LOG\_APP, "config.url is: %s", const\_cast<char \*>(fileUrl.c\_str()));
     
         // 2.设置回调。
         // 状态回调。
         OH\_AVRecorder\_SetStateCallback(g\_avRecorder, OnStateChange, nullptr);
    
         // 错误回调。
         OH\_AVRecorder\_SetErrorCallback(g\_avRecorder, OnError, nullptr);
    
         // 生成媒体文件回调（fileGenerationMode选择AUTO\_CREATE时设置）。
         OH\_AVErrCode ret = OH\_AVRecorder\_SetUriCallback(g\_avRecorder, OnUri, nullptr);
         if (ret == AV\_ERR\_OK) {
             OH\_LOG\_INFO(LOG\_APP, "==NDKDemo==  OH\_AVRecorder\_SetUriCallback succeed!");
         } else {
             OH\_LOG\_ERROR(LOG\_APP, "==NDKDemo==  Failed to set URI callback, error code: %d", ret);
         }
         
         // 3.调用prepare接口。
         int result = OH\_AVRecorder\_Prepare(g\_avRecorder, config);
         if (result != AV\_ERR\_OK) {
             OH\_LOG\_ERROR(LOG\_APP, "==NDKDemo== AVRecorder Prepare failed %{public}d", result);
         }
       
         // 4.释放内存。
         delete config->metadata.videoOrientation;
         delete config;
         config = nullptr;
       
         napi\_value res;
         napi\_create\_int32(env, result, &res);
         return res;
     }
    
4.  获取视频录制需要的SurfaceID，初始化视频数据输入源。该步骤需要在输入源模块完成，以相机为例，需要创建录像输出流，包括创建Camera对象、获取相机列表、创建相机输入流等，相机详细步骤请参考[相机-录像方案](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/native-camera-recording)。
    
    调用getInputSurface()接口，接口的返回值SurfaceID用于传递给视频数据输入源模块。常用的输入源模块为相机，以下示例代码中，仅展示获取SurfaceID的步骤。
    
    输入源模块通过SurfaceID可以获取到Surface，通过Surface可以将视频数据流传递给AVRecorder，由AVRecorder再进行视频数据的处理。
    
    // 获取surfaceID。
    OHNativeWindow \*window = nullptr;
    int resultCode = OH\_AVRecorder\_GetInputSurface(g\_avRecorder, &window);
    uint64\_t surfaceId = 0;
    if (resultCode == AV\_ERR\_OK && window != nullptr) {
       OH\_NativeWindow\_GetSurfaceId(window, &surfaceId);
    }
    
5.  初始化视频数据输入源。该步骤需要在输入源模块完成，以相机为例，需要创建录像输出流，包括创建Camera对象、获取相机列表、创建相机输入流等，相机详细步骤请参考[相机-录像方案](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/native-camera-recording)。
    
6.  开始录制，启动输入源输入视频数据，例如相机模块调用OH\_VideoOutput\_Start()接口启动相机录制。然后调用OH\_AVRecorder\_Start()接口，此时AVRecorder进入started状态。
    
    OH\_AVRecorder\_Start(g\_avRecorder);
    
7.  暂停录制，调用OH\_AVRecorder\_Pause()接口，此时AVRecorder进入paused状态，同时暂停输入源输入数据。例如相机模块调用OH\_VideoOutput\_Stop()停止相机视频数据输入。
    
    OH\_AVRecorder\_Pause(g\_avRecorder);
    
8.  恢复录制，调用OH\_AVRecorder\_Resume()接口，此时再次进入started状态。
    
    OH\_AVRecorder\_Resume(g\_avRecorder);
    
9.  停止录制，调用OH\_AVRecorder\_Stop()接口，此时进入stopped状态，同时停止相机录制。
    
    OH\_AVRecorder\_Stop(g\_avRecorder);
    
10.  重置资源，调用OH\_AVRecorder\_Reset()重新进入idle状态，允许重新配置录制参数。
     
     OH\_AVRecorder\_Reset(g\_avRecorder);
     
11.  销毁实例，调用OH\_AVRecorder\_Release()进入released状态，退出录制，释放视频数据输入源相关资源，例如相机资源。
     
     OH\_AVRecorder\_Release(g\_avRecorder);
     

#### 完整示例

参考以下示例，包括“创建录制实例-准备录制-开始录制-暂停录制-恢复录制-停止录制-重置录制状态-释放录制资源”的完整流程。

#include <unistd.h>
#include <fcntl.h>
#include "hilog/log.h"
#include <multimedia/player\_framework/avrecorder.h>
#include <multimedia/player\_framework/avrecorder\_base.h>
#include <multimedia/media\_library/media\_asset\_change\_request\_capi.h>
#include <multimedia/media\_library/media\_access\_helper\_capi.h>
#include <multimedia/media\_library/media\_asset\_capi.h>

static struct OH\_AVRecorder \*g\_avRecorder = nullptr;
static int32\_t g\_outputFd;

// 设置状态回调。
void OnStateChange(OH\_AVRecorder \*recorder, OH\_AVRecorder\_State state,
                   OH\_AVRecorder\_StateChangeReason reason, void \*userData)
{
   (void)recorder;
   (void)userData;

   // 将reason转换为字符串表示。
   const char \*reasonStr = (reason == OH\_AVRecorder\_StateChangeReason::AVRECORDER\_USER) ? "USER" :
                           (reason == OH\_AVRecorder\_StateChangeReason::AVRECORDER\_BACKGROUND) ? "BACKGROUND" : "UNKNOWN";

   if (state == OH\_AVRecorder\_State::AVRECORDER\_IDLE) {
      OH\_LOG\_INFO(LOG\_APP, "==NDKDemo== Recorder OnStateChange IDLE, reason: %{public}s", reasonStr);
      // 处理状态变更。
   }
   if (state == OH\_AVRecorder\_State::AVRECORDER\_PREPARED) {
      OH\_LOG\_INFO(LOG\_APP, "==NDKDemo== Recorder OnStateChange PREPARED, reason: %{public}s", reasonStr);
      // 处理状态变更。
   }
   if (state == OH\_AVRecorder\_State::AVRECORDER\_STARTED) {
      OH\_LOG\_INFO(LOG\_APP, "==NDKDemo== Recorder OnStateChange STARTED, reason: %{public}s", reasonStr);
      // 处理状态变更。
   }
   if (state == OH\_AVRecorder\_State::AVRECORDER\_PAUSED) {
      OH\_LOG\_INFO(LOG\_APP, "==NDKDemo== Recorder OnStateChange PAUSED, reason: %{public}s", reasonStr);
      // 处理状态变更。
   }
   if (state == OH\_AVRecorder\_State::AVRECORDER\_STOPPED) {
      OH\_LOG\_INFO(LOG\_APP, "==NDKDemo== Recorder OnStateChange STOPPED, reason: %{public}s", reasonStr);
      // 处理状态变更。
   }
   if (state == OH\_AVRecorder\_State::AVRECORDER\_RELEASED) {
      OH\_LOG\_INFO(LOG\_APP, "==NDKDemo== Recorder OnStateChange RELEASED, reason: %{public}s", reasonStr);
      // 处理状态变更。
   }
   if (state == OH\_AVRecorder\_State::AVRECORDER\_ERROR) {
      OH\_LOG\_INFO(LOG\_APP, "==NDKDemo== Recorder OnStateChange ERROR, reason: %{public}s", reasonStr);
      // 处理状态变更。
   }
}

// 设置错误回调。
void OnError(OH\_AVRecorder \*recorder, int32\_t errorCode, const char \*errorMsg, void \*userData)
{
   (void)recorder;
   (void)userData;
   OH\_LOG\_INFO(LOG\_APP, "==NDKDemo== Recorder OnError errorCode: %{public}d, error message: %{public}s",
               errorCode, errorMsg);
}

// 设置生成媒体文件回调（fileGenerationMode选择AUTO\_CREATE时设置）。
void OnUri(OH\_AVRecorder \*recorder, OH\_MediaAsset \*asset, void \*userData)
{
   (void)recorder;
   (void)userData;
   OH\_LOG\_INFO(LOG\_APP, "==NDKDemo== OnUri in!");
   if (asset != nullptr) {
      auto changeRequest = OH\_MediaAssetChangeRequest\_Create(asset);
      if (changeRequest == nullptr) {
         OH\_LOG\_ERROR(LOG\_APP, "==NDKDemo== changeRequest is null!");
         return;
      }
      MediaLibrary\_ImageFileType imageFileType = MEDIA\_LIBRARY\_IMAGE\_JPEG; // 待媒体库提供可用的VIDEO接口。
      uint32\_t result = OH\_MediaAssetChangeRequest\_SaveCameraPhoto(changeRequest, imageFileType);
      OH\_LOG\_INFO(LOG\_APP, "result of OH\_MediaAssetChangeRequest\_SaveCameraPhoto: %d", result);

      uint32\_t resultChange = OH\_MediaAccessHelper\_ApplyChanges(changeRequest);
      OH\_LOG\_INFO(LOG\_APP, "result of OH\_MediaAccessHelper\_ApplyChanges: %d", resultChange);

      OH\_MediaAsset\_Release(asset);
      OH\_MediaAssetChangeRequest\_Release(changeRequest);
   } else {
      OH\_LOG\_ERROR(LOG\_APP, "Received null media asset!");
   }
   OH\_LOG\_INFO(LOG\_APP, "==NDKDemo== OnUri out!");
}

void SetConfig(OH\_AVRecorder\_Config &config)
{
   config.audioSourceType = AVRECORDER\_MIC;
   config.videoSourceType = AVRECORDER\_SURFACE\_ES;

   // 设置媒体属性。
   config.profile.audioBitrate = 96000;
   config.profile.audioChannels = 2;
   config.profile.audioCodec = AVRECORDER\_AUDIO\_AAC;
   config.profile.audioSampleRate = 48000;

   config.profile.videoBitrate = 2000000;
   config.profile.videoFrameWidth = 1280;
   config.profile.videoFrameHeight = 720;
   config.profile.videoFrameRate = 30;
   config.profile.videoCodec = AVRECORDER\_VIDEO\_AVC;
   config.profile.isHdr = false;
   config.profile.enableTemporalScale = false;

   config.profile.fileFormat = AVRECORDER\_CFT\_MPEG\_4;
   config.fileGenerationMode = AVRECORDER\_APP\_CREATE;

   config.metadata.videoOrientation = new char\[2\]; // 开发者需要自行释放申请的内存。
   if (config.metadata.videoOrientation != nullptr) {
      strcpy(config.metadata.videoOrientation, "0"); // 视频旋转角度，支持0、90、180、270。
   }
   OH\_LOG\_INFO(LOG\_APP, "==NDKDemo== videoOrientation: %{public}s", config.metadata.videoOrientation);

   config.metadata.location.latitude = 27.791863;
   config.metadata.location.longitude = 64.574687;
}

// 1.准备录制。
static napi\_value PrepareAVRecorder(napi\_env env, napi\_callback\_info info)
{
   (void)info;
   OH\_LOG\_INFO(LOG\_APP, "==NDKDemo== PrepareAVRecorder in!");
   g\_avRecorder = OH\_AVRecorder\_Create();
   OH\_LOG\_INFO(LOG\_APP, "==NDKDemo== AVRecorder Create ok! g\_avRecorder: %{public}p", g\_avRecorder);
   if (g\_avRecorder == nullptr) {
      OH\_LOG\_ERROR(LOG\_APP, "==NDKDemo== AVRecorder Create failed!");
   }
   OH\_AVRecorder\_Config \*config = new OH\_AVRecorder\_Config(); // 开发者需要自行释放申请的内存。

   SetConfig(\*config);

   // 1.1设置URL（fileGenerationMode选择APP\_CREATE时设置）。
   const std::string AVRECORDER\_ROOT = "/data/storage/el2/base/files/";
   g\_outputFd = open((AVRECORDER\_ROOT + "avrecorder01.mp4").c\_str(), O\_RDWR | O\_CREAT, 0777); // 设置文件名。
   std::string fileUrl = "fd://" + std::to\_string(g\_outputFd);
   config->url = const\_cast<char \*>(fileUrl.c\_str());

   // 1.2设置回调。
   // 状态回调。
   OH\_AVRecorder\_SetStateCallback(g\_avRecorder, OnStateChange, nullptr);

   // 错误回调。
   OH\_AVRecorder\_SetErrorCallback(g\_avRecorder, OnError, nullptr);

   // 生成媒体文件回调（fileGenerationMode选择AUTO\_CREATE时设置）。
   OH\_AVErrCode ret = OH\_AVRecorder\_SetUriCallback(g\_avRecorder, OnUri, nullptr);
   if (ret == AV\_ERR\_OK) {
      OH\_LOG\_INFO(LOG\_APP, "==NDKDemo==  OH\_AVRecorder\_SetUriCallback succeed!");
   } else {
      OH\_LOG\_ERROR(LOG\_APP, "==NDKDemo==  Failed to set URI callback, error code: %d", ret);
   }

   // 1.3调用prepare接口。
   int result = OH\_AVRecorder\_Prepare(g\_avRecorder, config);
   if (result != AV\_ERR\_OK) {
      OH\_LOG\_ERROR(LOG\_APP, "==NDKDemo== AVRecorder Prepare failed %{public}d", result);
   }
   
   // 1.4释放内存。
   delete config->metadata.videoOrientation;
   delete config;
   config = nullptr;

   napi\_value res;
   napi\_create\_int32(env, result, &res);
   return res;
}

// 2.启动相机。
static napi\_value PrepareCamera(napi\_env env, napi\_callback\_info info)
{
   OH\_LOG\_INFO(LOG\_APP, "==NDKDemo== AVRecorder PrepareCamera");
   (void)info;

   OHNativeWindow \*window = nullptr;
   int resultCode = OH\_AVRecorder\_GetInputSurface(g\_avRecorder, &window);
   if (resultCode != AV\_ERR\_OK || window == nullptr) {
       OH\_LOG\_INFO(LOG\_APP, "==NDKDemo== AVRecorder OH\_AVRecorder\_GetInputSurface failed!");
       napi\_value errorResult;
       napi\_create\_int32(env, -1, &errorResult); // -1表示错误
       return errorResult;
   }
   uint64\_t surfaceId = 0;
   OH\_NativeWindow\_GetSurfaceId(window, &surfaceId);

   // 将surfaceId传入数据采集模块，具体请参考相机模块。

   int result = 0;
   napi\_value res;
   napi\_create\_int32(env, result, &res);
   return res;
}

// 3.开始录制。
static napi\_value StartAVRecorder(napi\_env env, napi\_callback\_info info)
{
   (void)info;
   int result = OH\_AVRecorder\_Start(g\_avRecorder);
   if (result != AV\_ERR\_OK) {
      OH\_LOG\_ERROR(LOG\_APP, "==NDKDemo== AVRecorder Start failed %{public}d", result);
   }
   napi\_value res;
   napi\_create\_int32(env, result, &res);
   return res;
}

// 4.暂停录制。
static napi\_value PauseAVRecorder(napi\_env env, napi\_callback\_info info)
{
   (void)info;
   int result = OH\_AVRecorder\_Pause(g\_avRecorder);
   if (result != AV\_ERR\_OK) {
      OH\_LOG\_ERROR(LOG\_APP, "==NDKDemo== AVRecorder Pause failed %{public}d", result);
   }
   napi\_value res;
   napi\_create\_int32(env, result, &res);
   return res;
}

// 5.恢复录制。
static napi\_value ResumeAVRecorder(napi\_env env, napi\_callback\_info info)
{
   (void)info;
   int result = OH\_AVRecorder\_Resume(g\_avRecorder);
   if (result != AV\_ERR\_OK) {
      OH\_LOG\_ERROR(LOG\_APP, "==NDKDemo== AVRecorder Resume failed %{public}d", result);
   }
   napi\_value res;
   napi\_create\_int32(env, result, &res);
   return res;
}

// 6.停止录制。
static napi\_value StopAVRecorder(napi\_env env, napi\_callback\_info info)
{
   (void)info;
   int result = OH\_AVRecorder\_Stop(g\_avRecorder);
   if (result != AV\_ERR\_OK) {
      OH\_LOG\_ERROR(LOG\_APP, "==NDKDemo== AVRecorder Stop failed %{public}d", result);
   }
   if (g\_outputFd > 0) {
      close(g\_outputFd);
   }
   
   napi\_value res;
   napi\_create\_int32(env, result, &res);
   return res;
}

// 7.重置录制状态。
static napi\_value ResetAVRecorder(napi\_env env, napi\_callback\_info info)
{
   (void)info;
   // 检查g\_avRecorder是否有效。
   if (g\_avRecorder == nullptr) {
      OH\_LOG\_ERROR(LOG\_APP, "==NDKDemo== g\_avRecorder is nullptr!");
      napi\_value res;
      napi\_create\_int32(env, AV\_ERR\_INVALID\_VAL, &res);
      return res;
   }

   int result = OH\_AVRecorder\_Reset(g\_avRecorder);
   if (result != AV\_ERR\_OK) {
      OH\_LOG\_ERROR(LOG\_APP, "==NDKDemo== AVRecorder Reset failed %{public}d", result);
   }
   napi\_value res;
   napi\_create\_int32(env, result, &res);
   return res;
}

// 8.释放录制资源。
static napi\_value ReleaseAVRecorder(napi\_env env, napi\_callback\_info info)
{
   (void)info;
   // 检查g\_avRecorder是否有效。
   if (g\_avRecorder == nullptr) {
      OH\_LOG\_ERROR(LOG\_APP, "==NDKDemo== g\_avRecorder is nullptr!");
      napi\_value res;
      napi\_create\_int32(env, AV\_ERR\_INVALID\_VAL, &res);
      return res;
   }
   if (g\_outputFd > 0) {
      close(g\_outputFd);
      g\_outputFd = -1;
   }
   int result = OH\_AVRecorder\_Release(g\_avRecorder);
   g\_avRecorder = nullptr;   // 释放录制资源后，需要显式地将g\_avRecorder指针置空。

   if (result != AV\_ERR\_OK) {
      OH\_LOG\_ERROR(LOG\_APP, "==NDKDemo== AVRecorder Release failed %{public}d", result);
   }
   napi\_value res;
   napi\_create\_int32(env, result, &res);
   return res;
}