1# Using OHAudio for Audio Recording (C/C++)
2
3**OHAudio** 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 recording 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
19To use APIs for audio recording, import <[native_audiostreambuilder.h](../../reference/apis-audio-kit/native__audiostreambuilder_8h.md)> and <[native_audiocapturer.h](../../reference/apis-audio-kit/native__audiocapturer_8h.md)>.
20
21```cpp
22#include <ohaudio/native_audiocapturer.h>
23#include <ohaudio/native_audiostreambuilder.h>
24```
25## Audio Stream Builder
26
27**OHAudio** 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/_o_h_audio.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/_o_h_audio.md#oh_audiostreambuilder_create) to create a builder:
35
36```
37OH_AudioStreamBuilder* builder;
38OH_AudioStreamBuilder_Create(&builder, streamType);
39```
40
41After the audio service is complete, call [OH_AudioStreamBuilder_Destroy](../../reference/apis-audio-kit/_o_h_audio.md#oh_audiostreambuilder_destroy) to destroy the builder.
42
43```
44OH_AudioStreamBuilder_Destroy(builder);
45```
46
47## How to Develop
48
49Read [OHAudio](../../reference/apis-audio-kit/_o_h_audio.md) for the API reference.
50
51The following walks you through how to implement simple recording:
52
53
541. Create an audio stream builder.
55
56    ```c++
57    OH_AudioStreamBuilder* builder;
58    OH_AudioStreamBuilder_Create(&builder, AUDIOSTREAM_TYPE_CAPTURER);
59    ```
60
612. Set audio stream parameters.
62
63    After creating the builder for audio recording, set the parameters required.
64
65    ```c++
66    // Set the audio sampling rate.
67    OH_AudioStreamBuilder_SetSamplingRate(builder, 48000);
68    // Set the number of audio channels.
69    OH_AudioStreamBuilder_SetChannelCount(builder, 2);
70    // Set the audio sampling format.
71    OH_AudioStreamBuilder_SetSampleFormat(builder, AUDIOSTREAM_SAMPLE_S16LE);
72    // Set the encoding type of the audio stream.
73    OH_AudioStreamBuilder_SetEncodingType(builder, AUDIOSTREAM_ENCODING_TYPE_RAW);
74    // Set the usage scenario of the audio capturer.
75    OH_AudioStreamBuilder_SetCapturerInfo(builder, AUDIOSTREAM_SOURCE_TYPE_MIC);
76    ```
77
78    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/_o_h_audio.md#oh_audiocapturer_callbacks).
79
803. Set the callback functions.
81
82    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.
83
84    ```c++
85    // Customize a data reading function.
86    int32_t MyOnReadData(
87        OH_AudioCapturer* capturer,
88        void* userData,
89        void* buffer,
90        int32_t length)
91    {
92        // Obtain the recording data of the specified length from the buffer.
93        return 0;
94    }
95    // Customize an audio stream event function.
96    int32_t MyOnStreamEvent(
97        OH_AudioCapturer* capturer,
98        void* userData,
99        OH_AudioStream_Event event)
100    {
101        // Update the player status and UI based on the audio stream event information indicated by the event.
102        return 0;
103    }
104    // Customize an audio interruption event function.
105    int32_t MyOnInterruptEvent(
106        OH_AudioCapturer* capturer,
107        void* userData,
108        OH_AudioInterrupt_ForceType type,
109        OH_AudioInterrupt_Hint hint)
110    {
111        // Update the capturer status and UI based on the audio interruption information indicated by type and hint.
112        return 0;
113    }
114    // Customize an exception callback function.
115    int32_t MyOnError(
116        OH_AudioCapturer* capturer,
117        void* userData,
118        OH_AudioStream_Result error)
119    {
120        // Perform operations based on the audio exception information indicated by error.
121        return 0;
122    }
123
124    OH_AudioCapturer_Callbacks callbacks;
125
126    // Set the callbacks.
127    callbacks.OH_AudioCapturer_OnReadData = MyOnReadData;
128    callbacks.OH_AudioCapturer_OnStreamEvent = MyOnStreamEvent;
129    callbacks.OH_AudioCapturer_OnInterruptEvent = MyOnInterruptEvent;
130    callbacks.OH_AudioCapturer_OnError = MyOnError;
131
132    // Set the callbacks for audio input streams.
133    OH_AudioStreamBuilder_SetCapturerCallback(builder, callbacks, nullptr);
134    ```
135
136    To avoid unexpected behavior, you can set the audio callback functions in either of the following ways:
137
138    - Initialize each callback in [OH_AudioCapturer_Callbacks](../../reference/apis-audio-kit/_o_h_audio.md#oh_audiocapturer_callbacks) by a custom callback method or a null pointer.
139
140      ```c++
141      // Customize a data reading function.
142      int32_t MyOnReadData(
143          OH_AudioCapturer* capturer,
144          void* userData,
145          void* buffer,
146          int32_t length)
147      {
148          // Obtain the recording data of the specified length from the buffer.
149          return 0;
150      }
151      // Customize an audio interruption event function.
152      int32_t MyOnInterruptEvent(
153          OH_AudioCapturer* capturer,
154          void* userData,
155          OH_AudioInterrupt_ForceType type,
156          OH_AudioInterrupt_Hint hint)
157      {
158          // Update the capturer status and UI based on the audio interruption information indicated by type and hint.
159          return 0;
160      }
161      OH_AudioCapturer_Callbacks callbacks;
162
163      // Configure a callback function. If listening is required, assign a value.
164      callbacks.OH_AudioCapturer_OnReadData = MyOnReadData;
165      callbacks.OH_AudioCapturer_OnInterruptEvent = MyOnInterruptEvent;
166
167      // (Mandatory) If listening is not required, use a null pointer for initialization.
168      callbacks.OH_AudioCapturer_OnStreamEvent = nullptr;
169      callbacks.OH_AudioCapturer_OnError = nullptr;
170      ```
171
172    - Initialize and clear the struct before using it.
173
174      ```c++
175      // Customize a data reading function.
176      int32_t MyOnReadData(
177          OH_AudioCapturer* capturer,
178          void* userData,
179          void* buffer,
180          int32_t length)
181      {
182          // Obtain the recording data of the specified length from the buffer.
183          return 0;
184      }
185      // Customize an audio interruption event function.
186      int32_t MyOnInterruptEvent(
187          OH_AudioCapturer* capturer,
188          void* userData,
189          OH_AudioInterrupt_ForceType type,
190          OH_AudioInterrupt_Hint hint)
191      {
192          // Update the capturer status and UI based on the audio interruption information indicated by type and hint.
193          return 0;
194      }
195      OH_AudioCapturer_Callbacks callbacks;
196
197      // Initialize and clear the struct before using it.
198      memset(&callbacks, 0, sizeof(OH_AudioCapturer_Callbacks));
199
200      // Configure the required callback functions.
201      callbacks.OH_AudioCapturer_OnReadData = MyOnReadData;
202      callbacks.OH_AudioCapturer_OnInterruptEvent = MyOnInterruptEvent;
203      ```
204
2054. Create an audio capturer instance.
206
207    ```c++
208    OH_AudioCapturer* audioCapturer;
209    OH_AudioStreamBuilder_GenerateCapturer(builder, &audioCapturer);
210    ```
211
2125. Use the audio capturer.
213
214    You can use the APIs listed below to control the audio streams.
215
216    | API                                                        | Description        |
217    | ------------------------------------------------------------ | ------------ |
218    | OH_AudioStream_Result OH_AudioCapturer_Start(OH_AudioCapturer* capturer) | Starts the audio capturer.    |
219    | OH_AudioStream_Result OH_AudioCapturer_Pause(OH_AudioCapturer* capturer) | Pauses the audio capturer.    |
220    | OH_AudioStream_Result OH_AudioCapturer_Stop(OH_AudioCapturer* capturer) | Stops the audio capturer.    |
221    | OH_AudioStream_Result OH_AudioCapturer_Flush(OH_AudioCapturer* capturer) | Flushes obtained audio data.|
222    | OH_AudioStream_Result OH_AudioCapturer_Release(OH_AudioCapturer* capturer) | Releases the audio capturer instance.|
223
2246. Destroy the audio stream builder.
225
226    When the builder is no longer used, release related resources.
227
228    ```c++
229    OH_AudioStreamBuilder_Destroy(builder);
230    ```
231
232## Setting the Low Latency Mode
233
234If 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.
235
236The development process is similar to that in the common recording scenario. The only difference is that you need to set the low delay mode by calling [OH_AudioStreamBuilder_SetLatencyMode()](../../reference/apis-audio-kit/_o_h_audio.md#oh_audiostreambuilder_setlatencymode) when creating an audio stream builder.
237
238> **NOTE**
239>
240> In audio recording scenarios, if [OH_AudioStream_SourceType](../../reference/apis-audio-kit/_o_h_audio.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.
241
242Code snippet:
243
244```C
245OH_AudioStream_LatencyMode latencyMode = AUDIOSTREAM_LATENCY_MODE_FAST;
246OH_AudioStreamBuilder_SetLatencyMode(builder, latencyMode);
247```
248<!--RP1-->
249<!--RP1End-->
250