1# Using OHAudio for Audio Recording (C/C++) 2 3**OHAudio** is a set of native APIs introduced in API version 10. These APIs are normalized in design and support both common and low-latency audio channels. 4 5## Prerequisites 6 7To use the playback or recording capability of **OHAudio**, you must first import the corresponding header files. 8 9### Linking the Dynamic Library in the CMake Script 10 11``` cmake 12target_link_libraries(sample PUBLIC libohaudio.so) 13``` 14### Adding Header Files 15To use APIs for audio recording, import <[native_audiostreambuilder.h](../reference/native-apis/native__audiostreambuilder_8h.md)> and <[native_audiocapturer.h](../reference/native-apis/native__audiocapturer_8h.md)>. 16 17```cpp 18#include <ohaudio/native_audiocapturer.h> 19#include <ohaudio/native_audiostreambuilder.h> 20``` 21## Audio Stream Builder 22 23**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/native-apis/_o_h_audio.md#oh_audiostream_type) based on your service scenarios. 24 25**OH_AudioStream_Type** can be set to either of the following: 26 27- AUDIOSTREAM_TYPE_RENDERER 28- AUDIOSTREAM_TYPE_CAPTURER 29 30The following code snippet shows how to use [OH_AudioStreamBuilder_Create](../reference/native-apis/_o_h_audio.md#oh_audiostreambuilder_create) to create a builder: 31 32``` 33OH_AudioStreamBuilder* builder; 34OH_AudioStreamBuilder_Create(&builder, streamType); 35``` 36 37After the audio service is complete, call [OH_AudioStreamBuilder_Destroy](../reference/native-apis/_o_h_audio.md#oh_audiostreambuilder_destroy) to destroy the builder. 38 39``` 40OH_AudioStreamBuilder_Destroy(builder); 41``` 42 43## How to Develop 44 45Read [OHAudio](../reference/native-apis/_o_h_audio.md) for the API reference. 46 47The following walks you through how to implement simple recording: 48 49 501. Create an audio stream builder. 51 52 ```c++ 53 OH_AudioStreamBuilder* builder; 54 OH_AudioStreamBuilder_Create(&builder, AUDIOSTREAM_TYPE_CAPTURER); 55 ``` 56 572. Set audio stream parameters. 58 59 After creating the builder for audio recording, set the parameters required. 60 61 ```c++ 62 // Set the audio sampling rate. 63 OH_AudioStreamBuilder_SetSamplingRate(builder, 48000); 64 // Set the number of audio channels. 65 OH_AudioStreamBuilder_SetChannelCount(builder, 2); 66 // Set the audio sampling format. 67 OH_AudioStreamBuilder_SetSampleFormat(builder, (OH_AudioStream_SampleFormat)0); 68 // Set the encoding type of the audio stream. 69 OH_AudioStreamBuilder_SetEncodingType(builder, (OH_AudioStream_EncodingType)0); 70 // Set the usage scenario of the audio capturer. 71 OH_AudioStreamBuilder_SetCapturerInfo(builder, (OH_AudioStream_SourceType)0); 72 ``` 73 74 Note that the audio data to record is written 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/native-apis/_o_h_audio.md#oh_audiocapturer_callbacks). 75 763. Set the callback functions. 77 78 ```c++ 79 OH_AudioCapturer_Callbacks callbacks; 80 // Set callbacks for the audio renderer. 81 OH_AudioStreamBuilder_SetCapturerCallback(builder, callbacks, nullptr); 82 ``` 83 844. Create an audio capturer instance. 85 86 ```c++ 87 OH_AudioCapturer* audioCapturer; 88 OH_AudioStreamBuilder_GenerateCapturer(builder, &audioCapturer); 89 ``` 90 915. Use the audio capturer. 92 93 You can use the APIs listed below to control the audio streams. 94 95 | API | Description | 96 | ------------------------------------------------------------ | ------------ | 97 | OH_AudioStream_Result OH_AudioCapturer_Start(OH_AudioCapturer* capturer) | Starts the audio capturer. | 98 | OH_AudioStream_Result OH_AudioCapturer_Pause(OH_AudioCapturer* capturer) | Pauses the audio capturer. | 99 | OH_AudioStream_Result OH_AudioCapturer_Stop(OH_AudioCapturer* capturer) | Stops the audio capturer. | 100 | OH_AudioStream_Result OH_AudioCapturer_Flush(OH_AudioCapturer* capturer) | Flushes obtained audio data.| 101 | OH_AudioStream_Result OH_AudioCapturer_Release(OH_AudioCapturer* capturer) | Releases the audio capturer instance.| 102 1036. Destroy the audio stream builder. 104 105 When the builder is no longer used, release related resources. 106 107 ```c++ 108 OH_AudioStreamBuilder_Destroy(builder); 109 ``` 110## Sample Code 111 112```cpp 113#include <iostream> 114#include <cstdint> 115#include <cstdio> 116#include <cstring> 117#include <ohaudio/native_audiocapturer.h> 118#include <ohaudio/native_audiostreambuilder.h> 119#include <thread> 120#include <chrono> 121 122#ifdef __cplusplus 123extern "C" { 124#endif 125namespace AudioTestConstants { 126constexpr int32_t RECODER_TIME = 10000; 127constexpr int32_t COUNTDOWN_INTERVAL = 1000; 128constexpr int32_t CONVERT_RATE = 1000; 129} // namespace AudioTestConstants 130 131// Ensure that the file exists in the directory or the application has the permission to create files in the directory. 132std::string g_filePath = "/data/data/oh_test_audio.pcm"; 133FILE *g_file = nullptr; 134// Audio sampling rate. 135int32_t g_samplingRate = 48000; 136// Number of audio channels. 137int32_t g_channelCount = 2; 138// Audio scenario. The value 0 indicates the normal scenario, and 1 indicates the low-latency scenario. 139int32_t g_latencyMode = 0; 140// Audio sample format. 141int32_t g_sampleFormat = 1; 142 143// Callback, through which the recorded audio data will be written. 144static int32_t AudioCapturerOnReadData(OH_AudioCapturer *capturer, void *userData, void *buffer, int32_t bufferLen) { 145 size_t count = 1; 146 if (fwrite(buffer, bufferLen, count, g_file) != count) { 147 printf("buffer fwrite err"); 148 } 149 150 return 0; 151} 152 153void SleepWaitRecoder(bool *stop) { 154 std::this_thread::sleep_for(std::chrono::milliseconds(AudioTestConstants::RECODER_TIME)); 155 *stop = true; 156} 157 158void RecorderTest() { 159 OH_AudioStream_Result ret; 160 161 // 1. Create an audio stream builder. 162 OH_AudioStreamBuilder *builder; 163 OH_AudioStream_Type type = AUDIOSTREAM_TYPE_CAPTURER; 164 ret = OH_AudioStreamBuilder_Create(&builder, type); 165 166 // 2. Set the parameters required by the audio stream. 167 OH_AudioStreamBuilder_SetSamplingRate(builder, g_samplingRate); 168 OH_AudioStreamBuilder_SetChannelCount(builder, g_channelCount); 169 OH_AudioStreamBuilder_SetLatencyMode(builder, (OH_AudioStream_LatencyMode)g_latencyMode); 170 OH_AudioStreamBuilder_SetSampleFormat(builder, (OH_AudioStream_SampleFormat)g_sampleFormat); 171 172 // Set the callback, through which the recorded audio data will be written. 173 OH_AudioCapturer_Callbacks callbacks; 174 callbacks.OH_AudioCapturer_OnReadData = AudioCapturerOnReadData; 175 ret = OH_AudioStreamBuilder_SetCapturerCallback(builder, callbacks, nullptr); 176 177 // 3. Create an audio capturer instance. 178 OH_AudioCapturer *audioCapturer; 179 ret = OH_AudioStreamBuilder_GenerateCapturer(builder, &audioCapturer); 180 181 // 4. Start recording. 182 ret = OH_AudioCapturer_Start(audioCapturer); 183 184 bool stop = false; 185 std::thread stopthread(SleepWaitRecoder, &stop); 186 stopthread.detach(); 187 188 int timeLeft = AudioTestConstants::RECODER_TIME; 189 while (!stop) { 190 std::this_thread::sleep_for(std::chrono::milliseconds(AudioTestConstants::COUNTDOWN_INTERVAL)); 191 timeLeft = timeLeft - AudioTestConstants::COUNTDOWN_INTERVAL; 192 } 193 194 // 5. Stop recording. 195 ret = OH_AudioCapturer_Stop(audioCapturer); 196 // Release the audio capturer instance. 197 ret = OH_AudioCapturer_Release(audioCapturer); 198 199 // 6. Destroy the audio stream builder. 200 ret = OH_AudioStreamBuilder_Destroy(builder); 201} 202 203 204int main() { 205 // Open the file before recording. 206 g_file = fopen(g_filePath.c_str(), "wb"); 207 if (g_file == nullptr) { 208 printf("OHAudioCapturerTest: Unable to open file \n"); 209 return 0; 210 } 211 // Start recording. 212 RecorderTest(); 213 // Close the file after the recording is complete. 214 fclose(g_file); 215 g_file = nullptr; 216 return 0; 217} 218#ifdef __cplusplus 219} 220#endif 221``` 222 223## Setting the Low Latency Mode 224 225If 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. 226 227The 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/native-apis/_o_h_audio.md#oh_audiostreambuilder_setlatencymode) when creating an audio stream builder. 228 229The code snippet is as follows: 230 231```C 232OH_AudioStream_LatencyMode latencyMode = AUDIOSTREAM_LATENCY_MODE_FAST; 233OH_AudioStreamBuilder_SetLatencyMode(builder, latencyMode); 234``` 235