1# Using OHAudio for Audio Playback (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 output at the native layer. 4 5OHAudio audio playback state transition 6 7 8 9## Prerequisites 10 11To use the playback 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 19### Adding Header Files 20 21To use APIs for audio playback, import <[native_audiostreambuilder.h](../../reference/apis-audio-kit/native__audiostreambuilder_8h.md)> and <[native_audiorenderer.h](../../reference/apis-audio-kit/native__audiorenderer_8h.md)>. 22 23```cpp 24#include <ohaudio/native_audiorenderer.h> 25#include <ohaudio/native_audiostreambuilder.h> 26``` 27 28## Building Audio Streams 29 30**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. 31 32**OH_AudioStream_Type** can be set to either of the following: 33 34- AUDIOSTREAM_TYPE_RENDERER 35- AUDIOSTREAM_TYPE_CAPTURER 36 37The 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: 38 39``` 40OH_AudioStreamBuilder* builder; 41OH_AudioStreamBuilder_Create(&builder, streamType); 42``` 43 44After the audio service is complete, call [OH_AudioStreamBuilder_Destroy](../../reference/apis-audio-kit/_o_h_audio.md#oh_audiostreambuilder_destroy) to destroy the builder. 45 46``` 47OH_AudioStreamBuilder_Destroy(builder); 48``` 49 50## How to Develop 51 52Read [OHAudio](../../reference/apis-audio-kit/_o_h_audio.md) for the API reference. 53 54The following walks you through how to implement simple playback: 55 561. Create an audio stream builder. 57 58 ```c++ 59 OH_AudioStreamBuilder* builder; 60 OH_AudioStreamBuilder_Create(&builder, AUDIOSTREAM_TYPE_RENDERER); 61 ``` 62 632. Set audio stream parameters. 64 65 After creating the builder for audio playback, set the parameters required. 66 67 ```c++ 68 // Set the audio sampling rate. 69 OH_AudioStreamBuilder_SetSamplingRate(builder, 48000); 70 // Set the number of audio channels. 71 OH_AudioStreamBuilder_SetChannelCount(builder, 2); 72 // Set the audio sampling format. 73 OH_AudioStreamBuilder_SetSampleFormat(builder, AUDIOSTREAM_SAMPLE_S16LE); 74 // Set the encoding type of the audio stream. 75 OH_AudioStreamBuilder_SetEncodingType(builder, AUDIOSTREAM_ENCODING_TYPE_RAW); 76 // Set the usage scenario of the audio renderer. 77 OH_AudioStreamBuilder_SetRendererInfo(builder, AUDIOSTREAM_USAGE_MUSIC); 78 ``` 79 80 Note that the audio data to play is written through callbacks. You must call **OH_AudioStreamBuilder_SetRendererCallback** to implement the callbacks. For details about the declaration of the callback functions, see [OH_AudioRenderer_Callbacks](../../reference/apis-audio-kit/_o_h_audio.md#oh_audiorenderer_callbacks). 81 82 833. Set the callback functions. 84 85 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. 86 87 ```c++ 88 // Customize a data writing function. 89 int32_t MyOnWriteData( 90 OH_AudioRenderer* renderer, 91 void* userData, 92 void* buffer, 93 int32_t length) 94 { 95 // Write the data to be played to the buffer by length. 96 return 0; 97 } 98 // Customize an audio stream event function. 99 int32_t MyOnStreamEvent( 100 OH_AudioRenderer* renderer, 101 void* userData, 102 OH_AudioStream_Event event) 103 { 104 // Update the player status and UI based on the audio stream event information indicated by the event. 105 return 0; 106 } 107 // Customize an audio interruption event function. 108 int32_t MyOnInterruptEvent( 109 OH_AudioRenderer* renderer, 110 void* userData, 111 OH_AudioInterrupt_ForceType type, 112 OH_AudioInterrupt_Hint hint) 113 { 114 // Update the player status and UI based on the audio interruption information indicated by type and hint. 115 return 0; 116 } 117 // Customize an exception callback function. 118 int32_t MyOnError( 119 OH_AudioRenderer* renderer, 120 void* userData, 121 OH_AudioStream_Result error) 122 { 123 // Perform operations based on the audio exception information indicated by error. 124 return 0; 125 } 126 127 OH_AudioRenderer_Callbacks callbacks; 128 // Set the callbacks. 129 callbacks.OH_AudioRenderer_OnWriteData = MyOnWriteData; 130 callbacks.OH_AudioRenderer_OnStreamEvent = MyOnStreamEvent; 131 callbacks.OH_AudioRenderer_OnInterruptEvent = MyOnInterruptEvent; 132 callbacks.OH_AudioRenderer_OnError = MyOnError; 133 134 // Set callbacks for the audio renderer. 135 OH_AudioStreamBuilder_SetRendererCallback(builder, callbacks, nullptr); 136 ``` 137 138 To avoid unexpected behavior, ensure that each callback of [OH_AudioRenderer_Callbacks](../../reference/apis-audio-kit/_o_h_audio.md#oh_audiorenderer_callbacks) is initialized by a custom callback method or null pointer when being set. 139 140 ```c++ 141 // Customize a data writing function. 142 int32_t MyOnWriteData( 143 OH_AudioRenderer* renderer, 144 void* userData, 145 void* buffer, 146 int32_t length) 147 { 148 // Write the data to be played to the buffer by length. 149 return 0; 150 } 151 // Customize an audio interruption event function. 152 int32_t MyOnInterruptEvent( 153 OH_AudioRenderer* renderer, 154 void* userData, 155 OH_AudioInterrupt_ForceType type, 156 OH_AudioInterrupt_Hint hint) 157 { 158 // Update the player status and UI based on the audio interruption information indicated by type and hint. 159 return 0; 160 } 161 OH_AudioRenderer_Callbacks callbacks; 162 163 // Configure a callback function. If listening is required, assign a value. 164 callbacks.OH_AudioRenderer_OnWriteData = MyOnWriteData; 165 callbacks.OH_AudioRenderer_OnInterruptEvent = MyOnInterruptEvent; 166 167 // (Mandatory) If listening is not required, use a null pointer for initialization. 168 callbacks.OH_AudioRenderer_OnStreamEvent = nullptr; 169 callbacks.OH_AudioRenderer_OnError = nullptr; 170 ``` 171 1724. Create an audio renderer instance. 173 174 ```c++ 175 OH_AudioRenderer* audioRenderer; 176 OH_AudioStreamBuilder_GenerateRenderer(builder, &audioRenderer); 177 ``` 178 1795. Use the audio renderer. 180 181 You can use the APIs listed below to control the audio streams. 182 183 | API | Description | 184 | ------------------------------------------------------------ | ------------ | 185 | OH_AudioStream_Result OH_AudioRenderer_Start(OH_AudioRenderer* renderer) | Starts the audio renderer. | 186 | OH_AudioStream_Result OH_AudioRenderer_Pause(OH_AudioRenderer* renderer) | Pauses the audio renderer. | 187 | OH_AudioStream_Result OH_AudioRenderer_Stop(OH_AudioRenderer* renderer) | Stops the audio renderer. | 188 | OH_AudioStream_Result OH_AudioRenderer_Flush(OH_AudioRenderer* renderer) | Flushes written audio data.| 189 | OH_AudioStream_Result OH_AudioRenderer_Release(OH_AudioRenderer* renderer) | Releases the audio renderer instance.| 190 1916. Destroy the audio stream builder. 192 193 When the builder is no longer used, release related resources. 194 195 ```c++ 196 OH_AudioStreamBuilder_Destroy(builder); 197 ``` 198 199## Setting the Low Latency Mode 200 201If the device supports the low-latency channel, you can use the low-latency mode to create a player for a higher-quality audio experience. 202 203The development process is similar to that in the common playback 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. 204 205The code snippet is as follows: 206 207```C 208OH_AudioStreamBuilder_SetLatencyMode(builder, AUDIOSTREAM_LATENCY_MODE_FAST); 209``` 210 211## Setting the Audio Channel Layout 212 213In the case of audio file playback, you can set the audio channel layout to specify the speaker position during rendering or playing for a better audio experience. 214 215The development process is similar to that in the common playback scenario. The only difference is that you need to set the audio channel layout by calling [OH_AudioStreamBuilder_SetChannelLayout()](../../reference/apis-audio-kit/_o_h_audio.md#oh_audiostreambuilder_setchannellayout) when creating an audio stream builder. 216 217If the audio channel layout does not match the number of audio channels, audio streams fail to be created. Therefore, you must ensure that the audio channel layout setting is correct. 218 219If you do not know the accurate audio channel layout or you want to use the default audio channel layout, do not call the API to set the audio channel layout. Alternatively, deliver **CH_LAYOUT_UNKNOWN** to use the default audio channel layout, which is specific to the number of audio channels. 220 221For audio in HOA format, to obtain the correct rendering and playback effect, you must specify the audio channel layout. 222 223The code snippet is as follows: 224 225```C 226OH_AudioStreamBuilder_SetChannelLayout(builder, CH_LAYOUT_STEREO); 227``` 228 229## Playing Audio Files in AudioVivid Format 230 231In the case of audio file playback in AudioVivid format, the callback function used for writing data is different from that in the common playback scenario. This callback function can write PCM data and metadata at the same time. 232 233The development process is similar to that in the common playback scenario. The only difference is that you need to call [OH_AudioStreamBuilder_SetWriteDataWithMetadataCallback()](../../reference/apis-audio-kit/_o_h_audio.md#oh_audiostreambuilder_setwritedatawithmetadatacallback) to set the callback function and call [OH_AudioStreamBuilder_SetEncodingType()](../../reference/apis-audio-kit/_o_h_audio.md#oh_audiostreambuilder_setencodingtype) to set the encoding type to **AUDIOSTREAM_ENCODING_TYPE_AUDIOVIVID** when creating an audio stream builder. 234 235When an audio file in AudioVivid format is played, the frame size is fixed. Therefore, do not call [OH_AudioStreamBuilder_SetFrameSizeInCallback()](../../reference/apis-audio-kit/_o_h_audio.md#oh_audiostreambuilder_setframesizeincallback) to set the frame size in the callback. In addition, when setting the number of audio channels and the audio channel layout, use the sum of the number of sound beds written into the audio source and the number of objects. 236 237The code snippet is as follows: 238 239```C 240// Customize a callback function for simultaneously writing PCM data and metadata. 241int32_t MyOnWriteDataWithMetadata( 242 OH_AudioRenderer* renderer, 243 void* userData, 244 void* audioData, 245 int32_t audioDataSize, 246 void* metadata, 247 int32_t metadataSize) 248{ 249 // Write the PCM data and metadata to be played to the buffer by audioDataSize and metadataSize, respectively. 250 return 0; 251} 252 253// Set the encoding type. 254OH_AudioStreamBuilder_SetEncodingType(builder, AUDIOSTREAM_ENCODING_TYPE_AUDIOVIVID); 255// Set the callbacks. 256OH_AudioRenderer_WriteDataWithMetadataCallback metadataCallback = MyOnWriteDataWithMetadata; 257// Set the callback function for writing both PCM data and metadata. 258OH_AudioStreamBuilder_SetWriteDataWithMetadataCallback(builder, metadataCallback, nullptr); 259``` 260 261<!--RP1--> 262<!--RP1End--> 263