使用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/23/v3/PuJFs93yShmsMzISAnkqvg/zh-cn_image_0000002594828782.png?HW-CC-KV=V1&HW-CC-Date=20260612T073524Z&HW-CC-Expire=86400&HW-CC-Sign=587D06BBBE9139D68DB9DCD75F0383B4F983A607B5AE1E3F84587BFAB04A1CD3)

状态的详细说明请参考[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)。
*   当需要读取和保存音频文件时，请优先使用[AudioViewPicker音频选择器对象](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-file-picker#audioviewpicker)。

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

仅应用需要克隆、备份或同步用户公共目录的音频类文件时，可申请ohos.permission.READ\_AUDIO、ohos.permission.WRITE\_AUDIO权限来读写音频文件，申请方式请参考[申请受控权限](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_audio)的应用被允许申请受限权限。

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

选择只录音频时，与视频相关的所有参数（如videoFrameWidth和videoFrameHeight）均不需要配置。同理，选择只录视频不录音频时，与音频相关的所有参数（如audioBitrate和audioChannels）均不需要配置。

开发者通过引入[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::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!");
    }
    
3.  配置音频录制参数，调用OH\_AVRecorder\_Prepare()接口，此时进入prepared状态。
    
    ![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/de/v3/wd30i1WUQb2gMUpJTiifsg/note_3.0-zh-cn.png?HW-CC-KV=V1&HW-CC-Date=20260612T073524Z&HW-CC-Expire=86400&HW-CC-Sign=0A8FB5D96E750BEE246D8829FD527D24703C22636A483330DDDDA760812FB33F)
    
    配置参数需要注意：
    
    *   配置参数之前需要确保完成对应权限的申请，请参考[申请权限](#申请权限)。
        
    *   prepare接口的入参OH\_AVRecorder\_Config中设置音频相关的配置参数，如示例代码所示。
        
    *   录制输出的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.profile.audioBitrate = 100000;
        config.profile.audioChannels = 2;
        config.profile.audioCodec = AVRECORDER\_AUDIO\_AAC;
        config.profile.audioSampleRate = 48000;
     
        config.profile.fileFormat = AVRECORDER\_CFT\_MP3;
        config.fileGenerationMode = AVRECORDER\_APP\_CREATE;
     }
    
     // 准备录制。
     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.mp3").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\_LOG\_INFO(LOG\_APP, "==NDKDemo== OH\_AVRecorder\_SetUriCallback in!");
         OH\_AVErrCode ret = OH\_AVRecorder\_SetUriCallback(g\_avRecorder, OnUri, nullptr);
         OH\_LOG\_INFO(LOG\_APP, "==NDKDemo== OH\_AVRecorder\_SetUriCallback out!");
         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);
         }
    
         napi\_value res;
         napi\_create\_int32(env, result, &res);
         return res;
     }
    
4.  开始录制，调用OH\_AVRecorder\_Start()接口，此时AVRecorder进入started状态。
    
    OH\_AVRecorder\_Start(g\_avRecorder);
    
5.  暂停录制，调用OH\_AVRecorder\_Pause()接口，此时AVRecorder进入paused状态，同时暂停输入源输入数据。
    
    OH\_AVRecorder\_Pause(g\_avRecorder);
    
6.  恢复录制，调用OH\_AVRecorder\_Resume()接口，此时再次进入started状态。
    
    OH\_AVRecorder\_Resume(g\_avRecorder);
    
7.  停止录制，调用OH\_AVRecorder\_Stop()接口，此时进入stopped状态。
    
    OH\_AVRecorder\_Stop(g\_avRecorder);
    
8.  重置资源，调用OH\_AVRecorder\_Reset()重新进入idle状态，允许重新配置录制参数。
    
    OH\_AVRecorder\_Reset(g\_avRecorder);
    
9.  销毁实例，调用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.profile.audioBitrate = 96000;
   config.profile.audioChannels = 2;
   config.profile.audioCodec = AVRECORDER\_AUDIO\_AAC;
   config.profile.audioSampleRate = 48000;

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

   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.mp3").c\_str(), O\_RDWR | O\_CREAT, 0777); // 设置文件名。
   std::string fileUrl = "fd://" + std::to\_string(g\_outputFd);
   config->url = const\_cast<char \*>(fileUrl.c\_str());
   OH\_LOG\_INFO(LOG\_APP, "config.url is: %s", 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);
   }

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

// 2.开始录制。
static napi\_value StartAVRecorder(napi\_env env, napi\_callback\_info info)
{
   (void)info;
   OH\_LOG\_INFO(LOG\_APP, "==NDKDemo== g\_avRecorder start: %{public}p", g\_avRecorder);
   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;
}

// 3.暂停录制。
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;
}

// 4.恢复录制。
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;
}

// 5.停止录制。
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);
   }
   close(g\_outputFd);
   napi\_value res;
   napi\_create\_int32(env, result, &res);
   return res;
}

// 6.重置录制状态。
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;
}

// 7.释放录制资源。
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;
   }
   
   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;
}