harmony 鸿蒙Using AVRecorder to Record Audio (C/C++)
Using AVRecorder to Record Audio (C/C++)
You can use the AVRecorder to develop the audio or video recording service. The AVRecorder supports audio capture, audio encoding, video encoding, audio encapsulation, and video encapsulation. It is applicable to simple audio/video recording scenarios and can be used to generate local media files directly.
In this topic, you will learn how to use the AVRecorder to complete the process of starting, pausing, resuming, and stopping audio recording.
During application development, you can use the state property of the AVRecorder to obtain the AVRecorder state or call OH_AVRecorder_SetStateCallback to listen for state changes. Your code must meet the state machine requirements. For example, OH_AVRecorder_Pause() is called only when the AVRecorder is in the started state, and OH_AVRecorder_Resume() is called only when it is in the paused state.
Figure 1 Recording state transition
For details about the states, see AVRecorderState.
Requesting Permissions
Before your development, configure the following permissions for your application. - To use the microphone, request the ohos.permission.MICROPHONE permission. For details about how to request user authorization, see Requesting User Authorization. - To read and save audio files, preferentially use AudioViewPicker.
NOTE
To clone, back up, or synchronize audio files in users’ public directory, request the ohos.permission.READ_AUDIO and ohos.permission.WRITE_AUDIO permissions for reading and writing audio files. For details, see Requesting Restricted Permissions.
How to Develop
NOTE
To record only audio, you do not need to set video-related parameters such as videoFrameWidth and videoFrameHeight. Similarly, to record only videos, you do not need to set audio-related parameters such as audioBitrate and audioChannels.
You can use C/C++ APIs related to video recording by including the header files avrecorder.h, avrecorder_base.h, and native_averrors.h.
Read AVRecorder for the API reference.
Link the dynamic library in the CMake script.
target_link_libraries(entry PUBLIC libavrecorder.so)
To use OH_AVFormat APIs, include the following header file:
#include <multimedia/player_framework/native_avformat.h>
In addition, link the following dynamic link library in the CMake script:
target_link_libraries(entry PUBLIC libnative_media_core.so)
To use system logging, include the following header file:
#include <hilog/log.h>
In addition, link the following dynamic link library in the CMake script:
target_link_libraries(entry PUBLIC libhilog_ndk.z.so)
- Create an AVRecorder instance. The AVRecorder is in the idle state.
#include <multimedia/player_framework/avrecorder.h>
#include <multimedia/player_framework/avrecorder_base.h>
static struct OH_AVRecorder *g_avRecorder = {};
g_avRecorder = OH_AVRecorder_Create();
- Set the events to listen for. |Event Type|Description| |——–|——–| |OnStateChange|Listens for AVRecorder state changes.| |OnError|Listens for AVRecorder errors.| |OnUri|Listens for media files generated by the AVRecorder.|
// Set a callback to respond to state changes.
void OnStateChange(OH_AVRecorder *recorder, OH_AVRecorder_State state,
OH_AVRecorder_StateChangeReason reason, void *userData) {
(void)recorder;
(void)userData;
// Convert reason into a string.
const char *reasonStr = (reason == AVRECORDER_USER) ? "USER" : (reason == AVRECORDER_BACKGROUND) ? "BACKGROUND" : "UNKNOWN";
if (state == AVRECORDER_IDLE) {
OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnStateChange IDLE, reason: %{public}s", reasonStr);
// Process the state change.
}
if (state == AVRECORDER_PREPARED) {
OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnStateChange PREPARED, reason: %{public}s", reasonStr);
// Process the state change.
}
if (state == AVRECORDER_STARTED) {
OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnStateChange STARTED, reason: %{public}s", reasonStr);
// Process the state change.
}
if (state == AVRECORDER_PAUSED) {
OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnStateChange PAUSED, reason: %{public}s", reasonStr);
// Process the state change.
}
if (state == AVRECORDER_STOPPED) {
OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnStateChange STOPPED, reason: %{public}s", reasonStr);
// Process the state change.
}
if (state == AVRECORDER_RELEASED) {
OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnStateChange RELEASED, reason: %{public}s", reasonStr);
// Process the state change.
}
if (state == AVRECORDER_ERROR) {
OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnStateChange ERROR, reason: %{public}s", reasonStr);
// Process the state change.
}
}
// Set an error callback.
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);
}
// Set a callback to listen for the generation of media files. (This operation is required when AUTO_CREATE is selected for fileGenerationMode.)
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; // Available video interfaces are provided by the media library.
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!");
}
- Set video recording parameters and call OH_AVRecorder_Prepare(). The AVRecorder enters the prepared state.
NOTE
Pay attention to the following when configuring parameters:
Before parameter configuration, ensure that you have gained the required permissions. For details, see Requesting Permissions.
In pure video recording scenarios, set only video-related parameters in OH_AVRecorder_Config of OH_AVRecorder_Prepare().
The recording output URL (URL in OH_AVRecorder_Config in the sample code) must be in the format of fd://xx (where xx indicates a file descriptor). You must call the basic file operation APIs to implement access to the application file. For details, see Accessing Application Files.
void SetConfig(OH_AVRecorder_Config &config)
{
config.audioSourceType = AVRECORDER_MIC;
// Set media properties.
config.profile.audioBitrate = 100000;
config.profile.audioChannels = 2;
config.profile.audioCodec = AVRECORDER_AUDIO_AAC;
config.profile.audioSampleRate = 48000;
config.profile.fileFormat = AVRECORDER_CFT_MPEG_4A;
config.fileGenerationMode = AVRECORDER_APP_CREATE;
config.metadata.location.latitude = 27.791863;
config.metadata.location.longitude = 64.574687;
}
// Prepare for recording.
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. Set the URL. (This operation is required when APP_CREATE is selected for fileGenerationMode.)
const std::string AVREORDER_ROOT = "/data/storage/el2/base/files/";
int32_t outputFd = open((AVREORDER_ROOT + "avrecorder01.mp3").c_str(), O_RDWR|O_CREAT, 0777); // Set the file name.
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. Set the callbacks.
// State callback.
OH_AVRecorder_SetStateCallback(g_avRecorder, OnStateChange, nullptr);
// Callback triggered when an error occurs.
OH_AVRecorder_SetErrorCallback(g_avRecorder, OnError, nullptr);
// Callback triggered when a media file is generated. (This operation is required when AUTO_CREATE is selected for fileGenerationMode.)
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. Call the prepare API.
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;
}
- Call OH_AVRecorder_Start() to start recording. The AVRecorder enters the started state.
OH_AVRecorder_Start(g_avRecorder);
- Call OH_AVRecorder_Pause() to pause recording. The AVRecorder enters the paused state. In addition, pause data input,
OH_AVRecorder_Pause(g_avRecorder);
- Call OH_AVRecorder_Resume() to resume recording. The AVRecorder enters the started state again.
OH_AVRecorder_Resume(g_avRecorder);
- Call OH_AVRecorder_Stop() to stop recording. The AVRecorder enters the stopped state.
OH_AVRecorder_Stop(g_avRecorder);
- Call OH_AVRecorder_Reset() to reset the resources. The AVRecorder enters the idle state. In this case, you can reconfigure the recording parameters.
OH_AVRecorder_Reset(g_avRecorder);
- Call OH_AVRecorder_Release() to switch the AVRecorder to the released state. Now your application exits the recording.
OH_AVRecorder_Release(g_avRecorder);
Development Example
Refer to the sample code below to complete the process of creating a recorder instance, preparing for, starting, pausing, resuming, and stopping recording, resetting the recording state, and releasing the recording resources.
#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 = {};
// Set a callback to respond to state changes.
void OnStateChange(OH_AVRecorder *recorder, OH_AVRecorder_State state,
OH_AVRecorder_StateChangeReason reason, void *userData) {
(void)recorder;
(void)userData;
// Convert reason into a string.
const char *reasonStr = (reason == AVRECORDER_USER) ? "USER" : (reason == AVRECORDER_BACKGROUND) ? "BACKGROUND" : "UNKNOWN";
if (state == AVRECORDER_IDLE) {
OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnStateChange IDLE, reason: %{public}s", reasonStr);
// Process the state change.
}
if (state == AVRECORDER_PREPARED) {
OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnStateChange PREPARED, reason: %{public}s", reasonStr);
// Process the state change.
}
if (state == AVRECORDER_STARTED) {
OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnStateChange STARTED, reason: %{public}s", reasonStr);
// Process the state change.
}
if (state == AVRECORDER_PAUSED) {
OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnStateChange PAUSED, reason: %{public}s", reasonStr);
// Process the state change.
}
if (state == AVRECORDER_STOPPED) {
OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnStateChange STOPPED, reason: %{public}s", reasonStr);
// Process the state change.
}
if (state == AVRECORDER_RELEASED) {
OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnStateChange RELEASED, reason: %{public}s", reasonStr);
// Process the state change.
}
if (state == AVRECORDER_ERROR) {
OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnStateChange ERROR, reason: %{public}s", reasonStr);
// Process the state change.
}
}
// Set an error callback.
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);
}
// Set a callback to listen for the generation of media files. (This operation is required when AUTO_CREATE is selected for fileGenerationMode.)
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; // Available video interfaces are provided by the media library.
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;
// Set media properties.
config.profile.audioBitrate = 96000;
config.profile.audioChannels = 2;
config.profile.audioCodec = AVRECORDER_AUDIO_AAC;
config.profile.audioSampleRate = 48000;
config.profile.fileFormat = AVRECORDER_CFT_MPEG_4;
config.fileGenerationMode = AVRECORDER_APP_CREATE;
config.metadata.location.latitude = 27.791863;
config.metadata.location.longitude = 64.574687;
}
// 1. Prepare for recording.
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 Set the URL. (This operation is required when APP_CREATE is selected for fileGenerationMode.)
const std::string AVREORDER_ROOT = "/data/storage/el2/base/files/";
int32_t outputFd = open((AVREORDER_ROOT + "avrecorder01.mp3").c_str(), O_RDWR|O_CREAT, 0777); // Set the file name.
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()));
// 1.2 Set the callbacks.
// State callback.
OH_AVRecorder_SetStateCallback(g_avRecorder, OnStateChange, nullptr);
// Callback triggered when an error occurs.
OH_AVRecorder_SetErrorCallback(g_avRecorder, OnError, nullptr);
// Callback triggered when a media file is generated. (This operation is required when AUTO_CREATE is selected for fileGenerationMode.)
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 Call the prepare API.
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. Start recording.
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. Pause recording.
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. Resume recording.
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. Stop recording.
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);
}
napi_value res;
napi_create_int32(env, result, &res);
return res;
}
// 6. Reset the recording state.
static napi_value ResetAVRecorder(napi_env env, napi_callback_info info)
{
(void)info;
// Check whether g_avRecorder is valid.
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. Release recording resources.
static napi_value ReleaseAVRecorder(napi_env env, napi_callback_info info)
{
(void)info;
// Check whether g_avRecorder is valid.
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; // After recording resources are released, the g_avRecorder pointer must be explicitly set to null.
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;
}
你可能感兴趣的鸿蒙文章
harmony 鸿蒙Using AVImageGenerator to Extract Video Images at a Specified Time (ArkTS)
harmony 鸿蒙Using AVMetadataExtractor to Extract Audio and Video Metadata (ArkTS)
harmony 鸿蒙FAQs About Transcoding
harmony 鸿蒙Creating an Asynchronous Thread for AVTranscoder Video Transcoding (ArkTS)
harmony 鸿蒙Introduction to Media Kit
harmony 鸿蒙Using AVPlayer to Set Playback URLs (ArkTS)
harmony 鸿蒙Using AVPlayer to Play Streaming Media (ArkTS)
- 所属分类: 后端技术
- 本文标签:
热门推荐
-
2、 - 优质文章
-
3、 gate.io
-
8、 golang
-
9、 openharmony
-
10、 Vue中input框自动聚焦