• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Using OHAudio for Audio Recording (C/C++)
2
3OHAudio is a set of C APIs introduced in API version 10. These APIs are normalized in design and support both common and low-latency audio channels. They support the PCM format only. They are suitable for playback applications that implement audio input at the native layer.
4
5OHAudio audio capturer state transition
6
7![OHAudioCapturer status change](figures/ohaudiocapturer-status-change.png)
8
9## Prerequisites
10
11To use the recording capability of OHAudio, you must first import the corresponding header files.
12
13### Linking the Dynamic Library in the CMake Script
14
15``` cmake
16target_link_libraries(sample PUBLIC libohaudio.so)
17```
18### Adding Header Files
19Include the <[native_audiostreambuilder.h](../../reference/apis-audio-kit/capi-native-audiostreambuilder-h.md)> and <[native_audiocapturer.h](../../reference/apis-audio-kit/capi-native-audiocapturer-h.md)> header files so that the application can use the functions related to audio recording.
20
21```cpp
22#include <ohaudio/native_audiocapturer.h>
23#include <ohaudio/native_audiostreambuilder.h>
24```
25## Audio Stream Builder
26
27OHAudio provides the **OH_AudioStreamBuilder** class, which complies with the builder design pattern and is used to build audio streams. You need to specify [OH_AudioStream_Type](../../reference/apis-audio-kit/capi-native-audiostream-base-h.md#oh_audiostream_type) based on your service scenarios.
28
29**OH_AudioStream_Type** can be set to either of the following:
30
31- AUDIOSTREAM_TYPE_RENDERER
32- AUDIOSTREAM_TYPE_CAPTURER
33
34The following code snippet shows how to use [OH_AudioStreamBuilder_Create](../../reference/apis-audio-kit/capi-native-audiostreambuilder-h.md#oh_audiostreambuilder_create) to create a builder:
35
36```cpp
37OH_AudioStreamBuilder* builder;
38OH_AudioStreamBuilder_Create(&builder, streamType);
39```
40
41After the audio service is complete, call [OH_AudioStreamBuilder_Destroy](../../reference/apis-audio-kit/capi-native-audiostreambuilder-h.md#oh_audiostreambuilder_destroy) to destroy the builder.
42
43```cpp
44OH_AudioStreamBuilder_Destroy(builder);
45```
46
47## How to Develop
48
49Read [OHAudio](../../reference/apis-audio-kit/capi-ohaudio.md) for the API reference.
50
51The following walks you through how to implement simple recording:
52
531. Create an audio stream builder.
54
55    ```cpp
56    OH_AudioStreamBuilder* builder;
57    OH_AudioStreamBuilder_Create(&builder, AUDIOSTREAM_TYPE_CAPTURER);
58    ```
59
602. Set audio stream parameters.
61
62    After creating the builder for audio recording, set the parameters required.
63
64    ```cpp
65    // Set the audio sampling rate.
66    OH_AudioStreamBuilder_SetSamplingRate(builder, 48000);
67    // Set the number of audio channels.
68    OH_AudioStreamBuilder_SetChannelCount(builder, 2);
69    // Set the audio sampling format.
70    OH_AudioStreamBuilder_SetSampleFormat(builder, AUDIOSTREAM_SAMPLE_S16LE);
71    // Set the encoding type of the audio stream.
72    OH_AudioStreamBuilder_SetEncodingType(builder, AUDIOSTREAM_ENCODING_TYPE_RAW);
73    // Set the usage scenario of the audio capturer.
74    OH_AudioStreamBuilder_SetCapturerInfo(builder, AUDIOSTREAM_SOURCE_TYPE_MIC);
75    ```
76
77    Note that the audio data captured is read through callbacks. You must call **OH_AudioStreamBuilder_SetCapturerCallback** to implement the callbacks. For details about the declaration of the callback functions, see [OH_AudioCapturer_Callbacks](../../reference/apis-audio-kit/capi-ohaudio-oh-audiocapturer-callbacks-struct.md).
78
793. Set the callback functions.
80
81    For details about concurrent processing of multiple audio streams, see [Processing Audio Interruption Events](audio-playback-concurrency.md). The procedure is similar, and the only difference is the API programming language in use.
82
83    ```cpp
84    // Customize a data reading function.
85    int32_t MyOnReadData(
86        OH_AudioCapturer* capturer,
87        void* userData,
88        void* buffer,
89        int32_t length)
90    {
91        // Obtain the recording data of the specified length from the buffer.
92        return 0;
93    }
94    // Customize an audio stream event function.
95    int32_t MyOnStreamEvent(
96        OH_AudioCapturer* capturer,
97        void* userData,
98        OH_AudioStream_Event event)
99    {
100        // Update the player status and UI based on the audio stream event information indicated by the event.
101        return 0;
102    }
103    // Customize an audio interruption event function.
104    int32_t MyOnInterruptEvent(
105        OH_AudioCapturer* capturer,
106        void* userData,
107        OH_AudioInterrupt_ForceType type,
108        OH_AudioInterrupt_Hint hint)
109    {
110        // Update the capturer status and UI based on the audio interruption information indicated by type and hint.
111        return 0;
112    }
113    // Customize an exception callback function.
114    int32_t MyOnError(
115        OH_AudioCapturer* capturer,
116        void* userData,
117        OH_AudioStream_Result error)
118    {
119        // Perform operations based on the audio exception information indicated by error.
120        return 0;
121    }
122
123    OH_AudioCapturer_Callbacks callbacks;
124
125    // Set the callbacks.
126    callbacks.OH_AudioCapturer_OnReadData = MyOnReadData;
127    callbacks.OH_AudioCapturer_OnStreamEvent = MyOnStreamEvent;
128    callbacks.OH_AudioCapturer_OnInterruptEvent = MyOnInterruptEvent;
129    callbacks.OH_AudioCapturer_OnError = MyOnError;
130
131    // Set the callbacks for audio input streams.
132    OH_AudioStreamBuilder_SetCapturerCallback(builder, callbacks, nullptr);
133    ```
134
135    To avoid unexpected behavior, you can set the audio callback functions in either of the following ways:
136
137    - Initialize each callback in [OH_AudioCapturer_Callbacks](../../reference/apis-audio-kit/capi-ohaudio-oh-audiocapturer-callbacks-struct.md) by a custom callback method or a null pointer.
138
139      ```cpp
140      // Customize a data reading function.
141      int32_t MyOnReadData(
142          OH_AudioCapturer* capturer,
143          void* userData,
144          void* buffer,
145          int32_t length)
146      {
147          // Obtain the recording data of the specified length from the buffer.
148          return 0;
149      }
150      // Customize an audio interruption event function.
151      int32_t MyOnInterruptEvent(
152          OH_AudioCapturer* capturer,
153          void* userData,
154          OH_AudioInterrupt_ForceType type,
155          OH_AudioInterrupt_Hint hint)
156      {
157          // Update the capturer status and UI based on the audio interruption information indicated by type and hint.
158          return 0;
159      }
160      OH_AudioCapturer_Callbacks callbacks;
161
162      // Configure a callback function. If listening is required, assign a value.
163      callbacks.OH_AudioCapturer_OnReadData = MyOnReadData;
164      callbacks.OH_AudioCapturer_OnInterruptEvent = MyOnInterruptEvent;
165
166      // (Mandatory) If listening is not required, use a null pointer for initialization.
167      callbacks.OH_AudioCapturer_OnStreamEvent = nullptr;
168      callbacks.OH_AudioCapturer_OnError = nullptr;
169      ```
170
171    - Initialize and clear the struct before using it.
172
173      ```cpp
174      // Customize a data reading function.
175      int32_t MyOnReadData(
176          OH_AudioCapturer* capturer,
177          void* userData,
178          void* buffer,
179          int32_t length)
180      {
181          // Obtain the recording data of the specified length from the buffer.
182          return 0;
183      }
184      // Customize an audio interruption event function.
185      int32_t MyOnInterruptEvent(
186          OH_AudioCapturer* capturer,
187          void* userData,
188          OH_AudioInterrupt_ForceType type,
189          OH_AudioInterrupt_Hint hint)
190      {
191          // Update the capturer status and UI based on the audio interruption information indicated by type and hint.
192          return 0;
193      }
194      OH_AudioCapturer_Callbacks callbacks;
195
196      // Initialize and clear the struct before using it.
197      memset(&callbacks, 0, sizeof(OH_AudioCapturer_Callbacks));
198
199      // Configure the required callback functions.
200      callbacks.OH_AudioCapturer_OnReadData = MyOnReadData;
201      callbacks.OH_AudioCapturer_OnInterruptEvent = MyOnInterruptEvent;
202      ```
203
2044. Create an audio capturer instance.
205
206    ```cpp
207    OH_AudioCapturer* audioCapturer;
208    OH_AudioStreamBuilder_GenerateCapturer(builder, &audioCapturer);
209    ```
210
2115. Use the audio capturer.
212
213    You can use the APIs listed below to control the audio streams.
214
215    | API                                                        | Description        |
216    | ------------------------------------------------------------ | ------------ |
217    | OH_AudioStream_Result OH_AudioCapturer_Start(OH_AudioCapturer* capturer) | Starts the audio capturer.   |
218    | OH_AudioStream_Result OH_AudioCapturer_Pause(OH_AudioCapturer* capturer) | Pauses the audio capturer.    |
219    | OH_AudioStream_Result OH_AudioCapturer_Stop(OH_AudioCapturer* capturer) | Stops the audio capturer.    |
220    | OH_AudioStream_Result OH_AudioCapturer_Flush(OH_AudioCapturer* capturer) | Flushes obtained audio data.|
221    | OH_AudioStream_Result OH_AudioCapturer_Release(OH_AudioCapturer* capturer) | Releases the audio capturer instance.|
222
2236. Destroy the audio stream builder.
224
225    When the builder is no longer used, release related resources.
226
227    ```cpp
228    OH_AudioStreamBuilder_Destroy(builder);
229    ```
230
231## Setting the Low Latency Mode
232
233If the device supports the low-latency channel, you can use the low-latency mode to create an audio capturer for a higher-quality audio experience.
234
235The development process is similar to that in the common recording scenario. The only difference is that you need to set the low-latency mode by calling [OH_AudioStreamBuilder_SetLatencyMode()](../../reference/apis-audio-kit/capi-native-audiostreambuilder-h.md#oh_audiostreambuilder_setlatencymode) when creating an audio stream builder.
236
237> **NOTE**
238>
239> In audio recording scenarios, if [OH_AudioStream_SourceType](../../reference/apis-audio-kit/capi-native-audiostream-base-h.md#oh_audiostream_sourcetype) is set to **AUDIOSTREAM_SOURCE_TYPE_VOICE_COMMUNICATION**, the low-latency mode cannot be set. The system determines the output audio channel based on the device capability.
240
241Code snippet:
242
243```cpp
244OH_AudioStream_LatencyMode latencyMode = AUDIOSTREAM_LATENCY_MODE_FAST;
245OH_AudioStreamBuilder_SetLatencyMode(builder, latencyMode);
246```
247
248## Setting the Mute Interruption Mode
249To ensure that the recording is not interrupted by the system's focus concurrency rules, a feature is introduced to change the interruption strategy from stopping the recording to simply muting it. You can control this behavior by calling [OH_AudioStreamBuilder_SetCapturerWillMuteWhenInterrupted](../../reference/apis-audio-kit/capi-native-audiostreambuilder-h.md#oh_audiostreambuilder_setcapturerwillmutewheninterrupted) when creating an audio stream builder. By default, this mode is disabled, and the audio focus strategy manages the order of concurrent audio streams. When enabled, if the recording is interrupted by another application, it will go into a muted state instead of stopping or pausing. In this state, the audio captured is silent.
250
251<!--RP1-->
252<!--RP1End-->
253