HarmonyOS Audio Collection in Audio and Video Practice

HarmonyOS Audio Collection in Audio and Video Practice

Background

In the method of utility improvement, there are audio assortment necessities in lots of situations, such because the voice sending perform in chat options, real-time speech-to-text conversion perform, real-time voice calls, and real-time video calls. On the Android and iOS platforms, the system gives two varieties:

  • Real-time audio stream assortment
  • Audio file recording

The system additionally gives totally different types of APIs. For instance, on Android:

  • AudioRecorder Java interface
  • MediaRecorder Java interface
  • OpenSLES C++ interface
  • AAudio C++ interface

During the method of HarmonyOS adaptation, there’s additionally a necessity for audio assortment. In this text, we’ll implement the audio assortment perform step-by-step.

Introduction to Audio Recording Interfaces

HarmonyOS gives two kinds of audio assortment interfaces, specifically TS and C++:

  • AudioSeize
  • OHAudio

The APIs of those two languages shall be launched respectively.

AudioSeize

Using AudioCapturer to document audio entails creating an AudioCapturer occasion, configuring audio assortment parameters, beginning and stopping the gathering, and releasing assets. The following state diagram supplied by the official clearly marks the strategies and state transitions:

Image description

createAudioSeize

Creating a seize primarily entails parameter configuration:

import { audio } from '@package.AudioPackage';

let audioStreamInfo: audio.AudioStreamInfo = {
  samplingRate: audio.AudioSamplingCharge.SAMPLE_RATE_48000, // Sampling price
  channels: audio.AudioChannel.CHANNEL_2, // Number of channels
  patternFormat: audio.AudioPatternFormat.SAMPLE_FORMAT_S16LE, // Sampling format
  encodingType: audio.AudioEncodingSort.ENCODING_TYPE_RAW // Encoding format
};

let audioCapturerInfo: audio.AudioCapturerInfo = {
  supply: audio.SourceType.SOURCE_TYPE_MIC,
  capturerFlags: 0
};

let audioCapturerOptions: audio.AudioCapturerOptions = {
  streamInfo: audioStreamInfo,
  capturerInfo: audioCapturerInfo
};

audio.createAudioCapturer(audioCapturerOptions, (err, knowledge) => {
  if (err) {
  } else {
    let audioCapturer = knowledge;
  }
});

The parameters encompass two important components:

  • AudioStreamInfo: Audio format configuration info
    • samplingRate: Sampling price
    • channels: Number of channels
    • patternFormat: Sampling format
    • encodingType: Audio encoding kind. Currently, solely the ENCODING_TYPE_RAW configuration for PCM is supported.
  • AudioCapturerInfo: Collection configuration info
    • supply: Audio supply kind, together with:
      • SOURCE_TYPE_INVALID: Invalid audio supply
      • SOURCE_TYPE_MIC: Microphone audio supply
      • SOURCE_TYPE_VOICE_RECOGNITION: Voice recognition supply
      • SOURCE_TYPE_PLAYBACK_CAPTURE: Audio supply for recording the playback audio stream (inner recording)
      • SOURCE_TYPE_VOICE_COMMUNICATION: Audio supply for voice name situations
      • SOURCE_TYPE_VOICE_MESSAGE: Audio supply for brief voice messages
    • capturerFlags: Audio capturer flag. 0 represents the audio capturer.

on(‘readData’)

The on(‘readData’) technique is used to subscribe to and monitor the callback for studying audio knowledge:

let readDataCallback = (buffer: ArrayBuffer) => {
    // Process the audio stream
};
audioCapturer.on('readData', readDataCallback);

begin

The begin technique is used to start out recording:

import { BusinessError } from '@package.BasicServicesKit';
audioCapturer.begin((err: BusinessError) => {
  if (err) {
  } else {
  }
});

cease

The cease technique is used to cease recording:

import { BusinessError } from '@package.BasicServicesKit';
audioCapturer.cease((err: BusinessError) => {
  if (err) {
  } else {
  }
});

launch

The launch technique destroys the occasion and releases assets:

import { BusinessError } from '@package.BasicServicesKit';
audioCapturer.launch((err: BusinessError) => {
  if (err) {
  } else {
  }
});

OHAudio

OHAudio is a set of C APIs launched by the system in API model 10. This API is designed to be unified and helps each regular audio paths and low-latency paths. It solely helps the PCM format and is appropriate for situations the place audio enter capabilities are carried out on the Native layer. Many audio encoding libraries are carried out in C/C++. After migrating to the HarmonyOS platform, utilizing the OHAudio C++ interface on the gathering facet can scale back the consumption of information switch between the TS layer and the C++ layer and enhance effectivity.

OHAudio depends upon the libohaudio.so dynamic library. By introducing the <native_audiostreambuilder.h> and <native_audiocapturer.h> header information, you should utilize the APIs associated to audio recording.

Creating the Constructor

OH_AudioStreamBuilder* builder;
OH_AudioStreamBuilder_Create(&builder, AUDIOSTREAM_TYPE_CAPTURER);

Configuring Audio Stream Parameters

You can confer with the next instance:

// Set the audio sampling price
OH_AudioStreamBuilder_SetSamplingCharge(builder, 48000);
// Set the variety of audio channels
OH_AudioStreamBuilder_SetChannelCount(builder, 2);
// Set the audio sampling format
OH_AudioStreamBuilder_SetPatternFormat(builder, AUDIOSTREAM_SAMPLE_S16LE);
// Set the encoding kind of the audio stream
OH_AudioStreamBuilder_SetEncodingSort(builder, AUDIOSTREAM_ENCODING_TYPE_RAW);
// Set the working state of affairs of the enter audio stream
OH_AudioStreamBuilder_SetCapturerInfo(builder, AUDIOSTREAM_SOURCE_TYPE_MIC);

The roles of those parameters are just like these of AudioSeize.

Setting the Audio Callback Functions

// Custom write knowledge perform
int32_t MyOnReadData(
    OH_AudioCapturer* capturer,
    void* userData,
    void* buffer,
    int32_t size)
{
    // Take out the recording knowledge with the size from the buffer
    return 0;
}
// Custom audio stream occasion perform
int32_t MyOnStreamOccasion(
    OH_AudioCapturer* capturer,
    void* userData,
    OH_AudioStream_Event occasion)
{
    // Update the participant state and interface in response to the audio stream occasion info represented by occasion
    return 0;
}
// Custom audio interruption occasion perform
int32_t MyOnInterruptEvent(
    OH_AudioCapturer* capturer,
    void* userData,
    OH_AudioInterrupt_ForceType kind,
    OH_AudioInterrupt_Hint trace)
{
    // Update the recorder state and interface in response to the audio interruption info represented by kind and trace
    return 0;
}
// Custom exception callback perform
int32_t MyOnError(
    OH_AudioCapturer* capturer,
    void* userData,
    OH_AudioStream_Result error)
{
    // Make corresponding processing in response to the audio exception info represented by error
    return 0;
}

OH_AudioCapturer_Callbacks callbacks;
// Configure callback capabilities
callbacks.OH_AudioCapturer_OnReadData = MyOnReadData;
callbacks.OH_AudioCapturer_OnStreamOccasion = MyOnStreamOccasion;
callbacks.OH_AudioCapturer_OnInterruptEvent = MyOnInterruptEvent;
callbacks.OH_AudioCapturer_OnError = MyOnError;

// Set the callback for the audio enter stream
OH_AudioStreamBuilder_SetCapturerCallback(builder, callbacks, nullptr);

Configure the callback capabilities by way of the OH_AudioStreamBuilder_SetCapturerCallback perform.

Constructing the Recording Audio Stream

OH_AudioCapturer* audioCapturer;
OH_AudioStreamBuilder_GenerateCapturer(builder, &audioCapturer);

Using the Audio Stream

  • OH_AudioStream_Result OH_AudioCapturer_Start(OH_AudioCapturer* capturer): Start recording.
  • OH_AudioStream_Result OH_AudioCapturer_Pause(OH_AudioCapturer* capturer): Pause recording.
  • OH_AudioStream_Result OH_AudioCapturer_Stop(OH_AudioCapturer* capturer): Stop recording.
  • OH_AudioStream_Result OH_AudioCapturer_Flush(OH_AudioCapturer* capturer): Release cached knowledge.
  • OH_AudioStream_Result OH_AudioCapturer_Release(OH_AudioCapturer* capturer): Release the recording occasion.

Releasing the Constructor

OH_AudioStreamBuilder_Destroy(builder);

Audio Recording Best Practices

Let’s take recording MP3 for example to implement the complete course of follow of audio assortment.

Permission Application

Audio assortment requires dynamic permission utility. Declare the permissions in module.json5:

"requestPermissions": [ { "name": "ohos.permission.MICROPHONE", "reason": "$string:reason", "usedScene": { "abilities": [ "FormAbility" ], "when": "inuse" } } ],

Apply for permissions dynamically:

perform reqPermissionsFromUser(permissions: Array<Permissions>, context: frequent.UIAbilityContext): void {  
  let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();  
  // requestPermissionsFromUser will decide the authorization standing of permissions to determine whether or not to pop up a window 
  atManager.requestPermissionsFromUser(context, permissions).then((knowledge) => {  
    let grantStatus: Array<quantity> = knowledge.authResults;  
    let size: quantity = grantStatus.size;  
    for (let i = 0; i < size; i++) {  
      if (grantStatus[i] === 0) {  
        // User has approved, and you'll proceed to entry the goal operation 
      } else {  
        // User has refused authorization. Prompt the consumer that authorization is required to entry the capabilities on the present web page and information the consumer to open the corresponding permissions within the system settings. 
        return;  
      }  
    }    // Authorization is profitable 
  }).catch((err: BusinessError) => {  
    console.error(`Failed to request permissions from consumer. Code is ${err.code}, message is ${err.message}`);  
  })  
}

Call the permission utility technique in aboutToAppera and begin recording after the authorization is profitable:

const context: frequent.UIAbilityContext = getContext(this) as frequent.UIAbilityContext;  
reqPermissionsFromUser(permissions, context);  

Configuring the C++ Project

After making a C++ module, configure the dependence on the ohaudio dynamic library:

cmake_minimum_required(VERSION 3.5.0)  
venture(audiorecorderdemo)  

set(NATIVERENDER_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR})  

if(DEFINED PACKAGE_FIND_FILE)  
    embrace(${PACKAGE_FIND_FILE})  
endif()  

include_directories(${NATIVERENDER_ROOT_PATH}  
                    ${NATIVERENDER_ROOT_PATH}/embrace)  

add_library(seize SHARED napi_init.cpp)  
target_link_libraries(seize PUBLIC libace_napi.z.so)  
target_link_libraries(seize PUBLIC libohaudio.so)

Configure the napi technique:

static napi_value begin(napi_env env, napi_callback_info data)  
{  


    return nullptr;  

}  
static napi_value cease(napi_env env, napi_callback_info data)  
{  


    return nullptr;  

}  
EXTERN_C_START  
static napi_value Init(napi_env env, napi_value exports)  
{  
    napi_property_descriptor desc[] = {  
        { "begin", nullptr, begin, nullptr, nullptr, nullptr, napi_default, nullptr },  
        { "cease", nullptr, cease, nullptr, nullptr, nullptr, napi_default, nullptr }  
    };  
    napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);  
    return exports;  
}

Implementing the Start of Recording

// Custom write knowledge perform 
int32_t MyOnReadData(  
    OH_AudioCapturer* capturer,  
    void* userData,  
    void* buffer,  
    int32_t size)  
{  
    //TODO Take out the recording knowledge with the size from the buffer 
    return 0;  
}  
// Custom audio stream occasion perform 
int32_t MyOnStreamOccasion(  
    OH_AudioCapturer* capturer,  
    void* userData,  
    OH_AudioStream_Event occasion)  
{  
    //TODO Update the participant state and interface in response to the audio stream occasion info represented by occasion 
    return 0;  
}  
// Custom audio interruption occasion perform 
int32_t MyOnInterruptEvent(  
    OH_AudioCapturer* capturer,  
    void* userData,  
    OH_AudioInterrupt_ForceType kind,  
    OH_AudioInterrupt_Hint trace)  
{  
    //TODO Update the recorder state and interface in response to the audio interruption info represented by kind and trace 
    return 0;  
}  
// Custom exception callback perform 
int32_t MyOnError(  
    OH_AudioCapturer* capturer,  
    void* userData,  
    OH_AudioStream_Result error)  
{  
    //TODO Make corresponding processing in response to the audio exception info represented by error 
    return 0;  
}  
static napi_value begin(napi_env env, napi_callback_info data)  
{  
    OH_AudioStreamBuilder* builder;  
    OH_AudioStreamBuilder_Create(&builder, AUDIOSTREAM_TYPE_CAPTURER);  
    // Set the audio sampling price 
    OH_AudioStreamBuilder_SetSamplingCharge(builder, 48000);  
    // Set the audio声道 
    OH_AudioStreamBuilder_SetChannelCount(builder, 2);  
    // Set the audio sampling format 
    OH_AudioStreamBuilder_SetPatternFormat(builder, AUDIOSTREAM_SAMPLE_S16LE);  
    // Set the encoding kind of the audio stream 
    OH_AudioStreamBuilder_SetEncodingSort(builder, AUDIOSTREAM_ENCODING_TYPE_RAW);  
    // Set the working state of affairs of the enter audio stream 
    OH_AudioStreamBuilder_SetCapturerInfo(builder, AUDIOSTREAM_SOURCE_TYPE_MIC);  

OH_AudioCapturer_Callbacks callbacks;  
    // Configure callback capabilities 
    callbacks.OH_AudioCapturer_OnReadData = MyOnReadData;  
    callbacks.OH_AudioCapturer_OnStreamOccasion = MyOnStreamOccasion;  
    callbacks.OH_AudioCapturer_OnInterruptEvent = MyOnInterruptEvent;  
    callbacks.OH_AudioCapturer_OnError = MyOnError;  
    // Set the callback for the audio enter stream 
    OH_AudioStreamBuilder_SetCapturerCallback(builder, callbacks, nullptr);  
    OH_AudioCapturer* audioCapturer;  
    OH_AudioStreamBuilder_GenerateCapturer(builder, &audioCapturer);  
    return nullptr;  
}

Best Practice 1:
To keep away from sudden behaviors, when setting audio callback capabilities, please be sure that every callback in OH_AudioCapturer_Callbacks is initialized with a customized callback technique or a null pointer. For instance:

OH_AudioCapturer_Callbacks callbacks;

// Configure callback capabilities. If it's good to hear, assign values.
callbacks.OH_AudioCapturer_OnReadData = MyOnReadData;
callbacks.OH_AudioCapturer_OnInterruptEvent = MyOnInterruptEvent;

// (Required) If you needn't hear, initialize with a null pointer.
callbacks.OH_AudioCapturer_OnStreamOccasion = nullptr;
callbacks.OH_AudioCapturer_OnError = nullptr;

Best Practice 2:
For gadgets that help the low-latency mode, in situations with excessive latency necessities (comparable to voice calls), you should utilize the low-latency mode to create an audio recording constructor to acquire a higher-quality audio expertise:

OH_AudioStream_LatencyMode latencyMode = AUDIOSTREAM_LATENCY_MODE_FAST;
OH_AudioStreamBuilder_SetLatencyMode(builder, latencyMode);

Audio File Processing

In the audio callback, we will course of the audio knowledge. It will be handed over to ASR or immediately written to a file. In the following article, we’ll implement the follow of encoding it into MP3 and writing it to a file.

Stopping Playback and Destroying the Instance

OH_AudioCapturer_Stop(builder, &audioCapturer);
OH_AudioStreamBuilder_Destroy(builder);

Summary

This article launched two audio assortment strategies supplied by HarmonyOS: AudioSeize on the TS layer and OHAudio on the C++ layer, and carried out the real-time audio assortment perform utilizing the OHAudio interface.

HI-FI News

by way of DEV Community https://dev.to

December 25, 2024 at 07:49AM