1# @ohos.multimedia.audio (Audio Management) 2 3The module provides basic audio control capabilities, including volume adjustment, device management, data collection, and rendering. 4 5This module provides the following common audio-related functions: 6 7- [AudioManager](#audiomanager): audio manager. 8- [AudioRenderer](#audiorenderer8): audio renderer, used to play Pulse Code Modulation (PCM) audio data. 9- [AudioCapturer](#audiocapturer8): audio capturer, used to record PCM audio data. 10 11> **NOTE** 12> 13> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. 14 15## Modules to Import 16 17```ts 18import { audio } from '@kit.AudioKit'; 19``` 20 21## Constants 22 23| Name | Type | Readable | Writable| Description | 24| --------------------------------------- | ----------| ---- | ---- | ------------------ | 25| DEFAULT_VOLUME_GROUP_ID<sup>9+</sup> | number | Yes | No | Default volume group ID.<br> **System capability**: SystemCapability.Multimedia.Audio.Volume | 26| DEFAULT_INTERRUPT_GROUP_ID<sup>9+</sup> | number | Yes | No | Default audio interruption group ID.<br> **System capability**: SystemCapability.Multimedia.Audio.Interrupt | 27 28**Example** 29 30```ts 31import { audio } from '@kit.AudioKit'; 32 33const defaultVolumeGroupId = audio.DEFAULT_VOLUME_GROUP_ID; 34const defaultInterruptGroupId = audio.DEFAULT_INTERRUPT_GROUP_ID; 35``` 36 37## audio.getAudioManager 38 39getAudioManager(): AudioManager 40 41Obtains an AudioManager instance. 42 43**System capability**: SystemCapability.Multimedia.Audio.Core 44 45**Return value** 46 47| Type | Description | 48| ----------------------------- | ------------ | 49| [AudioManager](#audiomanager) | AudioManager instance.| 50 51**Example** 52```ts 53import { audio } from '@kit.AudioKit'; 54 55let audioManager = audio.getAudioManager(); 56``` 57 58## audio.createAudioRenderer<sup>8+</sup> 59 60createAudioRenderer(options: AudioRendererOptions, callback: AsyncCallback\<AudioRenderer>): void 61 62Creates an AudioRenderer instance. This API uses an asynchronous callback to return the result. 63 64**System capability**: SystemCapability.Multimedia.Audio.Renderer 65 66**Parameters** 67 68| Name | Type | Mandatory| Description | 69| -------- | ----------------------------------------------- | ---- | ---------------- | 70| options | [AudioRendererOptions](#audiorendereroptions8) | Yes | Renderer configurations. | 71| callback | AsyncCallback<[AudioRenderer](#audiorenderer8)> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the AudioRenderer instance obtained; otherwise, **err** is an error object.| 72 73**Example** 74 75```ts 76import { audio } from '@kit.AudioKit'; 77 78let audioStreamInfo: audio.AudioStreamInfo = { 79 samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000, // Sampling rate. 80 channels: audio.AudioChannel.CHANNEL_2, // Channel. 81 sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, // Sampling format. 82 encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW // Encoding format. 83}; 84 85let audioRendererInfo: audio.AudioRendererInfo = { 86 usage: audio.StreamUsage.STREAM_USAGE_MUSIC, // Audio stream usage type: music. Set this parameter based on the service scenario. 87 rendererFlags: 0 // AudioRenderer flag. 88}; 89 90let audioRendererOptions: audio.AudioRendererOptions = { 91 streamInfo: audioStreamInfo, 92 rendererInfo: audioRendererInfo 93}; 94 95audio.createAudioRenderer(audioRendererOptions,(err, data) => { 96 if (err) { 97 console.error(`AudioRenderer Created: Error: ${err}`); 98 } else { 99 console.info('AudioRenderer Created: Success: SUCCESS'); 100 let audioRenderer = data; 101 } 102}); 103``` 104 105## audio.createAudioRenderer<sup>8+</sup> 106 107createAudioRenderer(options: AudioRendererOptions): Promise<AudioRenderer\> 108 109Creates an AudioRenderer instance. This API uses a promise to return the result. 110 111**System capability**: SystemCapability.Multimedia.Audio.Renderer 112 113**Parameters** 114 115| Name | Type | Mandatory| Description | 116| :------ | :--------------------------------------------- | :--- | :----------- | 117| options | [AudioRendererOptions](#audiorendereroptions8) | Yes | Renderer configurations.| 118 119**Return value** 120 121| Type | Description | 122| ----------------------------------------- | ---------------- | 123| Promise<[AudioRenderer](#audiorenderer8)> | Promise used to return the AudioRenderer instance.| 124 125**Example** 126 127```ts 128import { audio } from '@kit.AudioKit'; 129import { BusinessError } from '@kit.BasicServicesKit'; 130 131let audioStreamInfo: audio.AudioStreamInfo = { 132 samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000, // Sampling rate. 133 channels: audio.AudioChannel.CHANNEL_2, // Channel. 134 sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, // Sampling format. 135 encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW // Encoding format. 136}; 137 138let audioRendererInfo: audio.AudioRendererInfo = { 139 usage: audio.StreamUsage.STREAM_USAGE_MUSIC, // Audio stream usage type: music. Set this parameter based on the service scenario. 140 rendererFlags: 0 // AudioRenderer flag. 141}; 142 143let audioRendererOptions: audio.AudioRendererOptions = { 144 streamInfo: audioStreamInfo, 145 rendererInfo: audioRendererInfo 146}; 147 148let audioRenderer: audio.AudioRenderer; 149 150audio.createAudioRenderer(audioRendererOptions).then((data) => { 151 audioRenderer = data; 152 console.info('AudioFrameworkRenderLog: AudioRenderer Created : Success : Stream Type: SUCCESS'); 153}).catch((err: BusinessError) => { 154 console.error(`AudioFrameworkRenderLog: AudioRenderer Created : ERROR : ${err}`); 155}); 156``` 157 158## audio.createAudioCapturer<sup>8+</sup> 159 160createAudioCapturer(options: AudioCapturerOptions, callback: AsyncCallback<AudioCapturer\>): void 161 162Creates an AudioCapturer instance. This API uses an asynchronous callback to return the result. 163 164**System capability**: SystemCapability.Multimedia.Audio.Capturer 165 166**Required permissions**: ohos.permission.MICROPHONE 167 168This permission is required when [SourceType](#sourcetype8) is set to **SOURCE_TYPE_MIC**, **SOURCE_TYPE_VOICE_RECOGNITION**, **SOURCE_TYPE_VOICE_COMMUNICATION**, **SOURCE_TYPE_VOICE_MESSAGE**, or **SOURCE_TYPE_CAMCORDER**. 169 170**Parameters** 171 172| Name | Type | Mandatory| Description | 173| :------- | :---------------------------------------------- | :--- | :--------------- | 174| options | [AudioCapturerOptions](#audiocaptureroptions8) | Yes | Capturer configurations.| 175| callback | AsyncCallback<[AudioCapturer](#audiocapturer8)> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the AudioCapturer instance obtained; otherwise, **err** is an error object. If the operation fails, an error object with one of the following error codes is returned:<br>Error code 6800301: indicates a parameter verification exception, permission verification exception, or system processing exception. For details, see system logs.<br>Error code 6800101: indicates that a mandatory parameter is null or the parameter type is incorrect.| 176 177**Example** 178 179```ts 180import { audio } from '@kit.AudioKit'; 181 182let audioStreamInfo: audio.AudioStreamInfo = { 183 samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000, // Sampling rate. 184 channels: audio.AudioChannel.CHANNEL_2, // Channel. 185 sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, // Sampling format. 186 encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW // Encoding format. 187}; 188 189let audioCapturerInfo: audio.AudioCapturerInfo = { 190 source: audio.SourceType.SOURCE_TYPE_MIC, // Audio source type: microphone. Set this parameter based on the service scenario. 191 capturerFlags: 0 // AudioCapturer flag. 192}; 193 194let audioCapturerOptions: audio.AudioCapturerOptions = { 195 streamInfo: audioStreamInfo, 196 capturerInfo: audioCapturerInfo 197}; 198 199audio.createAudioCapturer(audioCapturerOptions, (err, data) => { 200 if (err) { 201 console.error(`AudioCapturer Created : Error: ${err}`); 202 } else { 203 console.info('AudioCapturer Created : Success : SUCCESS'); 204 let audioCapturer = data; 205 } 206}); 207``` 208 209## audio.createAudioCapturer<sup>8+</sup> 210 211createAudioCapturer(options: AudioCapturerOptions): Promise<AudioCapturer\> 212 213Creates an AudioCapturer instance. This API uses a promise to return the result. 214 215**System capability**: SystemCapability.Multimedia.Audio.Capturer 216 217**Required permissions**: ohos.permission.MICROPHONE 218 219This permission is required when [SourceType](#sourcetype8) is set to **SOURCE_TYPE_MIC**, **SOURCE_TYPE_VOICE_RECOGNITION**, **SOURCE_TYPE_VOICE_COMMUNICATION**, **SOURCE_TYPE_VOICE_MESSAGE**, or **SOURCE_TYPE_CAMCORDER**. 220 221**Parameters** 222 223| Name | Type | Mandatory| Description | 224| :------ | :--------------------------------------------- | :--- | :--------------- | 225| options | [AudioCapturerOptions](#audiocaptureroptions8) | Yes | Capturer configurations.| 226 227**Return value** 228 229| Type | Description | 230| ----------------------------------------- |----------------------| 231| Promise<[AudioCapturer](#audiocapturer8)> | Promise used to return the result. If the operation is successful, an AudioCapturer instance is returned; otherwise, an error object with either of the following error codes is returned:<br>Error code 6800301: indicates a parameter verification exception, permission verification exception, or system processing exception. For details, see system logs.<br>Error code 6800101: indicates that a mandatory parameter is null or the parameter type is incorrect.| 232 233**Example** 234 235```ts 236import { audio } from '@kit.AudioKit'; 237import { BusinessError } from '@kit.BasicServicesKit'; 238 239let audioStreamInfo: audio.AudioStreamInfo = { 240 samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000, // Sampling rate. 241 channels: audio.AudioChannel.CHANNEL_2, // Channel. 242 sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, // Sampling format. 243 encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW // Encoding format. 244}; 245 246let audioCapturerInfo: audio.AudioCapturerInfo = { 247 source: audio.SourceType.SOURCE_TYPE_MIC, // Audio source type: microphone. Set this parameter based on the service scenario. 248 capturerFlags: 0 // AudioCapturer flag. 249}; 250 251let audioCapturerOptions:audio.AudioCapturerOptions = { 252 streamInfo: audioStreamInfo, 253 capturerInfo: audioCapturerInfo 254}; 255 256let audioCapturer: audio.AudioCapturer; 257 258audio.createAudioCapturer(audioCapturerOptions).then((data) => { 259 audioCapturer = data; 260 console.info('AudioCapturer Created : Success : Stream Type: SUCCESS'); 261}).catch((err: BusinessError) => { 262 console.error(`AudioCapturer Created : ERROR : ${err}`); 263}); 264``` 265 266## AudioVolumeType 267 268Enumerates the audio stream types. 269 270**System capability**: SystemCapability.Multimedia.Audio.Volume 271 272| Name | Value | Description | 273| ---------------------------- | ------ | ---------- | 274| VOICE_CALL<sup>8+</sup> | 0 | Audio stream for voice calls.| 275| RINGTONE | 2 | Audio stream for ringtones. | 276| MEDIA | 3 | Audio stream for media purpose. | 277| ALARM<sup>10+</sup> | 4 | Audio stream for alarming. | 278| ACCESSIBILITY<sup>10+</sup> | 5 | Audio stream for accessibility. | 279| VOICE_ASSISTANT<sup>8+</sup> | 9 | Audio stream for voice assistant.| 280 281## InterruptMode<sup>9+</sup> 282 283Enumerates the audio interruption modes. 284 285**Atomic service API**: This API can be used in atomic services since API version 12. 286 287**System capability**: SystemCapability.Multimedia.Audio.Interrupt 288 289| Name | Value | Description | 290| ---------------------------- | ------ | ---------- | 291| SHARE_MODE | 0 | Shared mode.| 292| INDEPENDENT_MODE | 1 | Independent mode.| 293 294## DeviceFlag 295 296Enumerates the audio device flags. 297 298**System capability**: SystemCapability.Multimedia.Audio.Device 299 300| Name | Value | Description | 301| ------------------------------- | ------ |---------------------------| 302| OUTPUT_DEVICES_FLAG | 1 | Output device. | 303| INPUT_DEVICES_FLAG | 2 | Input device. | 304| ALL_DEVICES_FLAG | 3 | All devices. | 305 306## DeviceUsage<sup>12+</sup> 307 308Enumerates the audio device types by usage. 309 310**System capability**: SystemCapability.Multimedia.Audio.Device 311 312| Name | Value | Description | 313| ------------------------------- | ------ |---------------------------| 314| MEDIA_OUTPUT_DEVICES | 1 | Media output device.| 315| MEDIA_INPUT_DEVICES | 2 | Media input device.| 316| ALL_MEDIA_DEVICES | 3 | All media devices.| 317| CALL_OUTPUT_DEVICES | 4 | Call output device.| 318| CALL_INPUT_DEVICES | 8 | Call input device.| 319| ALL_CALL_DEVICES | 12 | All call devices.| 320 321## DeviceRole 322 323Enumerates the device roles. 324 325**Atomic service API**: This API can be used in atomic services since API version 12. 326 327**System capability**: SystemCapability.Multimedia.Audio.Device 328 329| Name | Value | Description | 330| ------------- | ------ | -------------- | 331| INPUT_DEVICE | 1 | Input role.| 332| OUTPUT_DEVICE | 2 | Output role.| 333 334## DeviceType 335 336Enumerates the device types. 337 338**System capability**: SystemCapability.Multimedia.Audio.Device 339 340| Name | Value | Description | 341| ---------------------| ------ | --------------------------------------------------------- | 342| INVALID | 0 | Invalid device.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 343| EARPIECE | 1 | Earpiece.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 344| SPEAKER | 2 | Speaker.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 345| WIRED_HEADSET | 3 | Wired headset with a microphone.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 346| WIRED_HEADPHONES | 4 | Wired headset without a microphone.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 347| BLUETOOTH_SCO | 7 | Bluetooth device using Synchronous Connection Oriented (SCO) links.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 348| BLUETOOTH_A2DP | 8 | Bluetooth device using Advanced Audio Distribution Profile (A2DP) links.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 349| MIC | 15 | Microphone.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 350| USB_HEADSET | 22 | USB Type-C headset.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 351| DISPLAY_PORT<sup>12+</sup> | 23 | Display port (DP), which is used to connect to external devices.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 352| REMOTE_CAST<sup>12+</sup> | 24 | Remote cast device.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 353| USB_DEVICE<sup>18+</sup> | 25 | USB device (excluding USB headsets). | 354| HDMI<sup>19+</sup> | 27 | HDMI device (such as HDMI, ARC, and eARC). | 355| LINE_DIGITAL<sup>19+</sup> | 28 | Wired digital device (such as S/PDIF) | 356| REMOTE_DAUDIO<sup>18+</sup> | 29 | Distributed device.<br>**Atomic service API**: This API can be used in atomic services since API version 18.| 357| DEFAULT<sup>9+</sup> | 1000 | Default device type.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 358 359## CommunicationDeviceType<sup>9+</sup> 360 361Enumerates the device types used for communication. 362 363**System capability**: SystemCapability.Multimedia.Audio.Communication 364 365| Name | Value | Description | 366| ------------- | ------ | -------------| 367| SPEAKER | 2 | Speaker. | 368 369## AudioRingMode 370 371Enumerates the audio ring modes. 372 373**System capability**: SystemCapability.Multimedia.Audio.Communication 374 375| Name | Value | Description | 376| ------------------- | ------ | ---------- | 377| RINGER_MODE_SILENT | 0 | Silent mode.| 378| RINGER_MODE_VIBRATE | 1 | Vibration mode.| 379| RINGER_MODE_NORMAL | 2 | Normal mode.| 380 381## AudioSampleFormat<sup>8+</sup> 382 383Enumerates the audio sample formats. 384 385**System capability**: SystemCapability.Multimedia.Audio.Core 386 387| Name | Value | Description | 388| ---------------------------------- | ------ | -------------------------- | 389| SAMPLE_FORMAT_INVALID | -1 | Invalid format. | 390| SAMPLE_FORMAT_U8 | 0 | Unsigned 8-bit integer. | 391| SAMPLE_FORMAT_S16LE | 1 | Signed 16-bit integer, little endian.| 392| SAMPLE_FORMAT_S24LE | 2 | Signed 24-bit integer, little endian.<br>Due to system restrictions, only some devices support this sampling format.| 393| SAMPLE_FORMAT_S32LE | 3 | Signed 32-bit integer, little endian.<br>Due to system restrictions, only some devices support this sampling format.| 394| SAMPLE_FORMAT_F32LE<sup>9+</sup> | 4 | Signed 32-bit floating point number, little endian.<br>Due to system restrictions, only some devices support this sampling format.| 395 396## AudioErrors<sup>9+</sup> 397 398Enumerates the error codes available for audio management. 399 400**System capability**: SystemCapability.Multimedia.Audio.Core 401 402| Name | Value | Description | 403| ---------------------| --------| ----------------- | 404| ERROR_INVALID_PARAM | 6800101 | Invalid parameter. | 405| ERROR_NO_MEMORY | 6800102 | Memory allocation failure. | 406| ERROR_ILLEGAL_STATE | 6800103 | Unsupported state. | 407| ERROR_UNSUPPORTED | 6800104 | Unsupported parameter value. | 408| ERROR_TIMEOUT | 6800105 | Processing timeout. | 409| ERROR_STREAM_LIMIT | 6800201 | Too many audio streams.| 410| ERROR_SYSTEM | 6800301 | System error. | 411 412## AudioChannel<sup>8+</sup> 413 414Enumerates the audio channels. 415 416**System capability**: SystemCapability.Multimedia.Audio.Core 417 418| Name | Value | Description | 419| --------- | -------- |------| 420| CHANNEL_1 | 1 | One audio channel (mono).| 421| CHANNEL_2 | 2 | Two audio channels (stereo).| 422| CHANNEL_3<sup>11+</sup> | 3 | Three audio channels.| 423| CHANNEL_4<sup>11+</sup> | 4 | Four audio channels.| 424| CHANNEL_5<sup>11+</sup> | 5 | Five audio channels.| 425| CHANNEL_6<sup>11+</sup> | 6 | Six audio channels.| 426| CHANNEL_7<sup>11+</sup> | 7 | Seven audio channels.| 427| CHANNEL_8<sup>11+</sup> | 8 | Eight audio channels.| 428| CHANNEL_9<sup>11+</sup> | 9 | Nine audio channels.| 429| CHANNEL_10<sup>11+</sup> | 10 | Ten audio channels.| 430| CHANNEL_12<sup>11+</sup> | 12 | Twelve audio channels.| 431| CHANNEL_14<sup>11+</sup> | 14 | Fourteen audio channels.| 432| CHANNEL_16<sup>11+</sup> | 16 | Sixteen audio channels.| 433 434## AudioSamplingRate<sup>8+</sup> 435 436Enumerates the audio sampling rates. The sampling rates supported vary according to the device in use. 437 438**System capability**: SystemCapability.Multimedia.Audio.Core 439 440| Name | Value | Description | 441| ----------------- | ------ | --------------- | 442| SAMPLE_RATE_8000 | 8000 | The sampling rate is 8000. | 443| SAMPLE_RATE_11025 | 11025 | The sampling rate is 11025.| 444| SAMPLE_RATE_12000 | 12000 | The sampling rate is 12000.| 445| SAMPLE_RATE_16000 | 16000 | The sampling rate is 16000.| 446| SAMPLE_RATE_22050 | 22050 | The sampling rate is 22050.| 447| SAMPLE_RATE_24000 | 24000 | The sampling rate is 24000.| 448| SAMPLE_RATE_32000 | 32000 | The sampling rate is 32000.| 449| SAMPLE_RATE_44100 | 44100 | The sampling rate is 44100.| 450| SAMPLE_RATE_48000 | 48000 | The sampling rate is 48000.| 451| SAMPLE_RATE_64000 | 64000 | The sampling rate is 64000.| 452| SAMPLE_RATE_88200<sup>12+</sup> | 88200 | The sampling rate is 88200.| 453| SAMPLE_RATE_96000 | 96000 | The sampling rate is 96000.| 454| SAMPLE_RATE_176400<sup>12+</sup> | 176400 | The sampling rate is 176400.| 455| SAMPLE_RATE_192000<sup>12+</sup> | 192000 | The sampling rate is 192000.| 456 457## AudioEncodingType<sup>8+</sup> 458 459Enumerates the audio encoding types. 460 461**Atomic service API**: This API can be used in atomic services since API version 12. 462 463**System capability**: SystemCapability.Multimedia.Audio.Core 464 465| Name | Value | Description | 466| --------------------- | ------ | --------- | 467| ENCODING_TYPE_INVALID | -1 | Invalid. | 468| ENCODING_TYPE_RAW | 0 | PCM encoding.| 469 470## AudioChannelLayout<sup>11+</sup> 471 472Enumerates the audio channel layouts of audio files. 473 474**System capability**: SystemCapability.Multimedia.Audio.Core 475 476| Name | Value | Description | 477| ------------------------------ | ---------------- | --------------------------------------------- | 478| CH_LAYOUT_UNKNOWN | 0x0 | Unknown. | 479| CH_LAYOUT_MONO | 0x4 | Mono. | 480| CH_LAYOUT_STEREO | 0x3 | Stereo. | 481| CH_LAYOUT_STEREO_DOWNMIX | 0x60000000 | Stereo downmix. | 482| CH_LAYOUT_2POINT1 | 0xB | 2.1. | 483| CH_LAYOUT_3POINT0 | 0x103 | 3.0. | 484| CH_LAYOUT_SURROUND | 0x7 | Surround. | 485| CH_LAYOUT_3POINT1 | 0xF | 3.1. | 486| CH_LAYOUT_4POINT0 | 0x107 | 4.0. | 487| CH_LAYOUT_QUAD | 0x33 | Quad. | 488| CH_LAYOUT_QUAD_SIDE | 0x603 | Quad side. | 489| CH_LAYOUT_2POINT0POINT2 | 0x3000000003 | 2.0.2. | 490| CH_LAYOUT_AMB_ORDER1_ACN_N3D | 0x100000000001 | First-order FOA file in ACN_N3D (ITU standards). | 491| CH_LAYOUT_AMB_ORDER1_ACN_SN3D | 0x100000001001 | First-order FOA file in ACN_SN3D (ITU standards).| 492| CH_LAYOUT_AMB_ORDER1_FUMA | 0x100000000101 | First-order FOA file in FUMA (ITU standards). | 493| CH_LAYOUT_4POINT1 | 0x10F | 4.1. | 494| CH_LAYOUT_5POINT0 | 0x607 | 5.0. | 495| CH_LAYOUT_5POINT0_BACK | 0x37 | 5.0 back. | 496| CH_LAYOUT_2POINT1POINT2 | 0x300000000B | 2.1.2. | 497| CH_LAYOUT_3POINT0POINT2 | 0x3000000007 | 3.0.2. | 498| CH_LAYOUT_5POINT1 | 0x60F | 5.1. | 499| CH_LAYOUT_5POINT1_BACK | 0x3F | 5.1 back. | 500| CH_LAYOUT_6POINT0 | 0x707 | 6.0. | 501| CH_LAYOUT_HEXAGONAL | 0x137 | Hexagonal. | 502| CH_LAYOUT_3POINT1POINT2 | 0x500F | 3.1.2. | 503| CH_LAYOUT_6POINT0_FRONT | 0x6C3 | 6.0 front. | 504| CH_LAYOUT_6POINT1 | 0x70F | 6.1. | 505| CH_LAYOUT_6POINT1_BACK | 0x13F | 6.1 back. | 506| CH_LAYOUT_6POINT1_FRONT | 0x6CB | 6.1 front. | 507| CH_LAYOUT_7POINT0 | 0x637 | 7.0. | 508| CH_LAYOUT_7POINT0_FRONT | 0x6C7 | 7.0 front. | 509| CH_LAYOUT_7POINT1 | 0x63F | 7.1. | 510| CH_LAYOUT_OCTAGONAL | 0x737 | Octagonal. | 511| CH_LAYOUT_5POINT1POINT2 | 0x300000060F | 5.1.2. | 512| CH_LAYOUT_7POINT1_WIDE | 0x6CF | 7.1 wide. | 513| CH_LAYOUT_7POINT1_WIDE_BACK | 0xFF | 7.1 wide back. | 514| CH_LAYOUT_AMB_ORDER2_ACN_N3D | 0x100000000002 | Second-order HOA file in ACN_N3D (ITU standards). | 515| CH_LAYOUT_AMB_ORDER2_ACN_SN3D | 0x100000001002 | Second-order HOA file in ACN_SN3D (ITU standards).| 516| CH_LAYOUT_AMB_ORDER2_FUMA | 0x100000000102 | Second-order HOA file in FUMA (ITU standards). | 517| CH_LAYOUT_5POINT1POINT4 | 0x2D60F | 5.1.4. | 518| CH_LAYOUT_7POINT1POINT2 | 0x300000063F | 7.1.2. | 519| CH_LAYOUT_7POINT1POINT4 | 0x2D63F | 7.1.4. | 520| CH_LAYOUT_10POINT2 | 0x180005737 | 10.2. | 521| CH_LAYOUT_9POINT1POINT4 | 0x18002D63F | 9.1.4. | 522| CH_LAYOUT_9POINT1POINT6 | 0x318002D63F | 9.1.6. | 523| CH_LAYOUT_HEXADECAGONAL | 0x18003F737 | Hexadecagonal. | 524| CH_LAYOUT_AMB_ORDER3_ACN_N3D | 0x100000000003 | Third-order HOA file in ACN_N3D (ITU standards). | 525| CH_LAYOUT_AMB_ORDER3_ACN_SN3D | 0x100000001003 | Third-order HOA file in ACN_SN3D (ITU standards).| 526| CH_LAYOUT_AMB_ORDER3_FUMA | 0x100000000103 | Third-order HOA file in FUMA (ITU standards). | 527 528## ContentType<sup>(deprecated)</sup> 529 530Enumerates the audio content types. 531 532> **NOTE** 533> This API is supported since API version 7 and deprecated since API version 10. You are advised to use [StreamUsage](#streamusage) instead. 534 535**System capability**: SystemCapability.Multimedia.Audio.Core 536 537| Name | Value | Description | 538| ---------------------------------- | ------ | ---------- | 539| CONTENT_TYPE_UNKNOWN | 0 | Unknown content.| 540| CONTENT_TYPE_SPEECH | 1 | Speech. | 541| CONTENT_TYPE_MUSIC | 2 | Music. | 542| CONTENT_TYPE_MOVIE | 3 | Movie. | 543| CONTENT_TYPE_SONIFICATION | 4 | Notification tone. | 544| CONTENT_TYPE_RINGTONE<sup>8+</sup> | 5 | Ringtone. | 545 546## StreamUsage 547 548Enumerates the audio stream usage types. 549 550**System capability**: SystemCapability.Multimedia.Audio.Core 551 552| Name | Value | Description | 553| ------------------------------------------| ------ |--------------------------------------------------------------------------------| 554| STREAM_USAGE_UNKNOWN | 0 | Unknown content.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 555| STREAM_USAGE_MEDIA<sup>(deprecated)</sup> | 1 | Media.<br> This enumerated value is supported since API version 7 and deprecated since API version 10. You are advised to use **STREAM_USAGE_MUSIC**, **STREAM_USAGE_MOVIE**, **STREAM_USAGE_GAME**, or **STREAM_USAGE_AUDIOBOOK** instead.| 556| STREAM_USAGE_MUSIC<sup>10+</sup> | 1 | Music.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 557| STREAM_USAGE_VOICE_COMMUNICATION | 2 | VoIP voice call.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 558| STREAM_USAGE_VOICE_ASSISTANT<sup>9+</sup> | 3 | Voice assistant.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 559| STREAM_USAGE_ALARM<sup>10+</sup> | 4 | Audio stream for alarming.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 560| STREAM_USAGE_VOICE_MESSAGE<sup>10+</sup> | 5 | Voice message.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 561| STREAM_USAGE_NOTIFICATION_RINGTONE<sup>(deprecated)</sup> | 6 | Notification tone.<br> This enumerated value is supported since API version 7 and deprecated since API version 10. You are advised to use **STREAM_USAGE_RINGTONE** instead.| 562| STREAM_USAGE_RINGTONE<sup>10+</sup> | 6 | Ringtone.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 563| STREAM_USAGE_NOTIFICATION<sup>10+</sup> | 7 | Notification.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 564| STREAM_USAGE_ACCESSIBILITY<sup>10+</sup> | 8 | Accessibility.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 565| STREAM_USAGE_MOVIE<sup>10+</sup> | 10 | Movie or video.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 566| STREAM_USAGE_GAME<sup>10+</sup> | 11 | Gaming.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 567| STREAM_USAGE_AUDIOBOOK<sup>10+</sup> | 12 | Audiobooks (including crosstalks and storytelling), news radio, and podcasts.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 568| STREAM_USAGE_NAVIGATION<sup>10+</sup> | 13 | Navigation.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 569| STREAM_USAGE_VIDEO_COMMUNICATION<sup>12+</sup> | 17 | VoIP video call.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 570 571## AudioState<sup>8+</sup> 572 573Enumerates the audio states. 574 575**System capability**: SystemCapability.Multimedia.Audio.Core 576 577| Name | Value | Description | 578| -------------- | ------ | ---------------- | 579| STATE_INVALID | -1 | Invalid state. | 580| STATE_NEW | 0 | Creating instance state.| 581| STATE_PREPARED | 1 | Prepared. | 582| STATE_RUNNING | 2 | Running.| 583| STATE_STOPPED | 3 | Stopped. | 584| STATE_RELEASED | 4 | Released. | 585| STATE_PAUSED | 5 | Paused. | 586 587## AudioEffectMode<sup>10+</sup> 588 589Enumerates the audio effect modes. 590 591**Atomic service API**: This API can be used in atomic services since API version 12. 592 593**System capability**: SystemCapability.Multimedia.Audio.Renderer 594 595| Name | Value | Description | 596| ------------------ | ------ | ---------- | 597| EFFECT_NONE | 0 | The audio effect is disabled.| 598| EFFECT_DEFAULT | 1 | The default audio effect is used.| 599 600## AudioRendererRate<sup>8+</sup> 601 602Enumerates the audio renderer rates. 603 604**System capability**: SystemCapability.Multimedia.Audio.Renderer 605 606| Name | Value | Description | 607| ------------------ | ------ | ---------- | 608| RENDER_RATE_NORMAL | 0 | Normal rate.| 609| RENDER_RATE_DOUBLE | 1 | Double rate. | 610| RENDER_RATE_HALF | 2 | 0.5x rate. | 611 612## InterruptType 613 614Enumerates the audio interruption types. 615 616**Atomic service API**: This API can be used in atomic services since API version 12. 617 618**System capability**: SystemCapability.Multimedia.Audio.Renderer 619 620| Name | Value | Description | 621| -------------------- | ------ | ---------------------- | 622| INTERRUPT_TYPE_BEGIN | 1 | Audio interruption started.| 623| INTERRUPT_TYPE_END | 2 | Audio interruption ended.| 624 625## InterruptForceType<sup>9+</sup> 626 627Enumerates the types of force that causes audio interruption. 628 629The force type is obtained when an [InterruptEvent](#interruptevent9) is received. 630 631This type specifies whether audio interruption is forcibly performed by the system. The operation information (such as audio pause or stop) can be obtained through [InterruptHint](#interrupthint). For details about the audio interruption strategy, see [Introduction to Audio Focus and Audio Sessions](../../media/audio/audio-playback-concurrency.md). 632 633**Atomic service API**: This API can be used in atomic services since API version 12. 634 635**System capability**: SystemCapability.Multimedia.Audio.Renderer 636 637| Name | Value | Description | 638| --------------- | ------ | ------------------------------------ | 639| INTERRUPT_FORCE | 0 | The operation is forcibly performed by the system. | 640| INTERRUPT_SHARE | 1 | The operation will not be performed by the system. [InterruptHint](#interrupthint) is used to provide recommended operations for the application, and the application can determine the next processing mode.| 641 642## InterruptHint 643 644Enumerates the hints provided along with audio interruption. 645 646The hint is obtained when an [InterruptEvent](#interruptevent9) is received. 647 648The hint specifies the operation (such as audio pause or volume adjustment) to be performed on audio streams based on the focus strategy. 649 650You can determine whether the operation is forcibly performed by the system based on [InterruptForceType](#interruptforcetype9) in **InterruptEvent**. For details, see [Introduction to Audio Focus and Audio Sessions](../../media/audio/audio-playback-concurrency.md). 651 652**Atomic service API**: This API can be used in atomic services since API version 12. 653 654**System capability**: SystemCapability.Multimedia.Audio.Renderer 655 656| Name | Value | Description | 657| ---------------------------------- | ------ | -------------------------------------------- | 658| INTERRUPT_HINT_NONE<sup>8+</sup> | 0 | None. | 659| INTERRUPT_HINT_RESUME | 1 | A hint is displayed, indicating that the audio stream is restored. The application can proactively trigger operations related to rendering or recording.<br>This operation cannot be forcibly performed by the system, and the corresponding [InterruptForceType](#interruptforcetype9) must be **INTERRUPT_SHARE**.| 660| INTERRUPT_HINT_PAUSE | 2 | A hint is displayed, indicating that the audio stream is paused and the audio focus is lost temporarily.<br>When the audio focus is available, the **INTERRUPT_HINT_RESUME** event is received. | 661| INTERRUPT_HINT_STOP | 3 | A hint is displayed, indicating that the audio stream stops and the audio focus is lost. | 662| INTERRUPT_HINT_DUCK | 4 | A hint is displayed, indicating that audio ducking starts and the audio is played at a lower volume.| 663| INTERRUPT_HINT_UNDUCK<sup>8+</sup> | 5 | A hint is displayed, indicating that audio ducking ends and the audio is played at the normal volume. | 664 665## AudioVolumeMode<sup>19+</sup> 666 667Enumerates the audio volume modes. 668 669**System capability**: SystemCapability.Multimedia.Audio.Volume 670 671| Name | Value | Description | 672| -------------- | ------ |--------------| 673| SYSTEM_GLOBAL | 0 | System-level volume (default mode).| 674| APP_INDIVIDUAL | 1 | Application-level volume. | 675 676## AudioStreamInfo<sup>8+</sup> 677 678Describes audio stream information. 679 680**System capability**: SystemCapability.Multimedia.Audio.Core 681 682| Name | Type | Mandatory| Description | 683| ------------ | ------------------------------------------------- | ---- | ------------------ | 684| samplingRate | [AudioSamplingRate](#audiosamplingrate8) | Yes | Audio sampling rate.| 685| channels | [AudioChannel](#audiochannel8) | Yes | Number of audio channels.| 686| sampleFormat | [AudioSampleFormat](#audiosampleformat8) | Yes | Audio sample format. | 687| encodingType | [AudioEncodingType](#audioencodingtype8) | Yes | Audio encoding type. | 688| channelLayout<sup>11+</sup> | [AudioChannelLayout](#audiochannellayout11) | No | Audio channel layout. The default value is **0x0**.| 689 690## AudioRendererInfo<sup>8+</sup> 691 692Describes audio renderer information. 693 694**System capability**: SystemCapability.Multimedia.Audio.Core 695 696| Name | Type | Mandatory | Description | 697| ------------- | --------------------------- | ---- | --------------- | 698| content | [ContentType](#contenttypedeprecated) | No | Audio content type.<br>This parameter is mandatory in API versions 8 and 9 and optional since API version 10. The default value is **CONTENT_TYPE_UNKNOWN**.<br>This API is supported since API version 7 and deprecated since API version 10. You are advised to use [StreamUsage](#streamusage) instead.| 699| usage | [StreamUsage](#streamusage) | Yes | Audio stream usage.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 700| rendererFlags | number | Yes | Audio renderer flags.<br>The value **0** means an audio renderer.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 701| volumeMode<sup>19+</sup> | [AudioVolumeMode](#audiovolumemode19) | No| Audio volume mode. The default value is **SYSTEM_GLOBAL**.| 702 703## AudioRendererOptions<sup>8+</sup> 704 705Describes audio renderer configurations. 706 707| Name | Type | Mandatory | Description | 708| ------------ | ---------------------------------------- | ---- | ---------------- | 709| streamInfo | [AudioStreamInfo](#audiostreaminfo8) | Yes | Audio stream information.<br>**System capability**: SystemCapability.Multimedia.Audio.Renderer| 710| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | Yes | Audio renderer information.<br>**System capability**: SystemCapability.Multimedia.Audio.Renderer| 711| privacyType<sup>10+</sup> | [AudioPrivacyType](#audioprivacytype10) | No| Whether the audio stream can be recorded by other applications. The default value is **0**.<br>**System capability**: SystemCapability.Multimedia.Audio.PlaybackCapture| 712 713## AudioPrivacyType<sup>10+</sup> 714 715Enumerates whether an audio stream can be recorded by other applications. 716 717**System capability**: SystemCapability.Multimedia.Audio.PlaybackCapture 718 719| Name | Value | Description | 720| -------------------- | ---- | -------------------------------- | 721| PRIVACY_TYPE_PUBLIC | 0 | The audio stream can be recorded by other applications. | 722| PRIVACY_TYPE_PRIVATE | 1 | The audio stream cannot be recorded by other applications.| 723 724## InterruptEvent<sup>9+</sup> 725 726Describes the interruption event received by the application when the audio is interrupted. 727 728**Atomic service API**: This API can be used in atomic services since API version 12. 729 730**System capability**: SystemCapability.Multimedia.Audio.Renderer 731 732| Name | Type |Mandatory | Description | 733| --------- | ------------------------------------------ | ---- | ------------------------------------ | 734| eventType | [InterruptType](#interrupttype) | Yes | Whether the audio interruption has started or ended. | 735| forceType | [InterruptForceType](#interruptforcetype9) | Yes | Whether the audio interruption is forcibly taken by the system or taken by an application.| 736| hintType | [InterruptHint](#interrupthint) | Yes | Hint provided along the interruption to provide information related to the interruption event.| 737 738## VolumeEvent<sup>9+</sup> 739 740Describes the event received by the application when the volume is changed. 741 742**System capability**: SystemCapability.Multimedia.Audio.Volume 743 744| Name | Type | Mandatory | Description | 745| ---------- | ----------------------------------- | ---- |-------------------------------------------| 746| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | 747| volume | number | Yes |Volume to set. The value range can be obtained by calling **getMinVolume** and **getMaxVolume**. | 748| updateUi | boolean | Yes | Whether to show the volume change in UI. The value **true** means to show the volume change in UI, and **false** means the opposite. | 749| volumeMode<sup>19+</sup> | [AudioVolumeMode](#audiovolumemode19) | No| Audio volume mode. The default value is **SYSTEM_GLOBAL**.| 750 751## MicStateChangeEvent<sup>9+</sup> 752 753Describes the event received by the application when the microphone mute status is changed. 754 755**System capability**: SystemCapability.Multimedia.Audio.Device 756 757| Name | Type | Mandatory| Description | 758| ---------- | ----------------------------------- | ---- |-------------------------------------------------------- | 759| mute | boolean | Yes | Mute status of the microphone The value **true** means that the microphone is muted, and **false** means the opposite. | 760 761## DeviceChangeAction 762 763Describes the device connection status and device information. 764 765**System capability**: SystemCapability.Multimedia.Audio.Device 766 767| Name | Type | Mandatory| Description | 768| :---------------- | :------------------------------------------------ | :--- | :----------------- | 769| type | [DeviceChangeType](#devicechangetype) | Yes | Device connection status.| 770| deviceDescriptors | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Device information. | 771 772## DeviceBlockStatusInfo<sup>13+</sup> 773 774Describes the audio device blocked status and device information. 775 776**System capability**: SystemCapability.Multimedia.Audio.Device 777 778| Name | Type | Mandatory| Description | 779| :---------------- | :------------------------------------------------ | :--- | :----------------- | 780| blockStatus | [DeviceBlockStatus](#deviceblockstatus13) | Yes | Blocked status of the audio device.| 781| devices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Device information. | 782 783## ChannelBlendMode<sup>11+</sup> 784 785Enumerates the audio channel blending modes. 786 787**System capability**: SystemCapability.Multimedia.Audio.Core 788 789| Name | Value | Description | 790| :------------------------------------------- | :----- | :--------------------- | 791| MODE_DEFAULT | 0 | No channel mixing. | 792| MODE_BLEND_LR | 1 | Blends the left and right channels together.| 793| MODE_ALL_LEFT | 2 | Copies the left channel and applies it to both the left and right channels. | 794| MODE_ALL_RIGHT | 3 | Copies the right channel and applies it to both the left and right channels. | 795 796## AudioStreamDeviceChangeReason<sup>11+</sup> 797 798Enumerates the reasons for audio stream device changes. 799 800**Atomic service API**: This API can be used in atomic services since API version 12. 801 802**System capability**: SystemCapability.Multimedia.Audio.Device 803 804| Name | Value | Description | 805|:------------------------------------------| :----- |:----------------| 806| REASON_UNKNOWN | 0 | Unknown reason. | 807| REASON_NEW_DEVICE_AVAILABLE | 1 | A new device is available. | 808| REASON_OLD_DEVICE_UNAVAILABLE | 2 | The old device is unavailable. When this reason is reported, consider pausing audio playback.| 809| REASON_OVERRODE | 3 | Forcibly selected.| 810 811## AudioStreamDeviceChangeInfo<sup>11+</sup> 812 813Describes the event received by the application when the audio stream device is changed. 814 815**Atomic service API**: This API can be used in atomic services since API version 12. 816 817**System capability**: SystemCapability.Multimedia.Audio.Device 818 819| Name | Type | Mandatory| Description | 820| :---------------- |:------------------------------------------------------------------| :--- | :----------------- | 821| devices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Device information.| 822| changeReason | [AudioStreamDeviceChangeReason](#audiostreamdevicechangereason11) | Yes | Reason for the change.| 823 824## DeviceChangeType 825 826Enumerates the device connection statuses. 827 828**System capability**: SystemCapability.Multimedia.Audio.Device 829 830| Name | Value | Description | 831| :--------- | :--- | :------------- | 832| CONNECT | 0 | Connected. | 833| DISCONNECT | 1 | Disconnected.| 834 835## DeviceBlockStatus<sup>13+</sup> 836 837Enumerates the blocked statuses of audio devices. 838 839**System capability**: SystemCapability.Multimedia.Audio.Device 840 841| Name | Value | Description | 842| :--------- | :--- | :------------- | 843| UNBLOCKED | 0 | The audio device is not blocked. | 844| BLOCKED | 1 | The audio device is blocked.| 845 846## AudioCapturerOptions<sup>8+</sup> 847 848Describes audio capturer configurations. 849 850| Name | Type | Mandatory| Description | 851| ----------------------------------- | --------------------------------------------------------- | ---- | ------------------------------------------------------------ | 852| streamInfo | [AudioStreamInfo](#audiostreaminfo8) | Yes | Audio stream information.<br>**System capability**: SystemCapability.Multimedia.Audio.Capturer | 853| capturerInfo | [AudioCapturerInfo](#audiocapturerinfo8) | Yes | Audio capturer information.<br>**System capability**: SystemCapability.Multimedia.Audio.Capturer | 854| playbackCaptureConfig<sup>(deprecated)</sup> | [AudioPlaybackCaptureConfig](#audioplaybackcaptureconfigdeprecated) | No | Configuration of internal audio recording.<br>**System capability**: SystemCapability.Multimedia.Audio.PlaybackCapture<br> This API is supported since API version 10 and deprecated since API version 12. You are advised to use [AVScreenCapture](../apis-media-kit/capi-avscreencapture.md) instead. | 855 856## AudioCapturerInfo<sup>8+</sup> 857 858Describes audio capturer information. 859 860**System capability**: SystemCapability.Multimedia.Audio.Core 861 862| Name | Type | Mandatory| Description | 863| :------------ | :------------------------ | :--- | :--------------- | 864| source | [SourceType](#sourcetype8) | Yes | Audio source type. | 865| capturerFlags | number | Yes | Audio capturer flags.<br>The value **0** means an audio capturer.| 866 867## SourceType<sup>8+</sup> 868 869Enumerates the audio source types. 870 871| Name | Value | Description | 872| :------------------------------------------- | :----- | :--------------------- | 873| SOURCE_TYPE_INVALID | -1 | Invalid audio source.<br>**System capability**: SystemCapability.Multimedia.Audio.Core | 874| SOURCE_TYPE_MIC | 0 | Mic source.<br>**System capability**: SystemCapability.Multimedia.Audio.Core| 875| SOURCE_TYPE_VOICE_RECOGNITION<sup>9+</sup> | 1 | Voice recognition source.<br>**System capability**: SystemCapability.Multimedia.Audio.Core | 876| SOURCE_TYPE_PLAYBACK_CAPTURE<sup>(deprecated)</sup> | 2 | Internal audio recording source.<br>**System capability**: SystemCapability.Multimedia.Audio.PlaybackCapture<br> This API is supported since API version 10 and deprecated since API version 12. You are advised to use [AVScreenCapture](../apis-media-kit/capi-avscreencapture.md) instead. | 877| SOURCE_TYPE_VOICE_COMMUNICATION | 7 | Voice communication source.<br>**System capability**: SystemCapability.Multimedia.Audio.Core| 878| SOURCE_TYPE_VOICE_MESSAGE<sup>12+</sup> | 10 | Voice message source.<br>**System capability**: SystemCapability.Multimedia.Audio.Core| 879| SOURCE_TYPE_CAMCORDER<sup>13+</sup> | 13 | Video recording source.<br>**System capability**: SystemCapability.Multimedia.Audio.Core| 880| SOURCE_TYPE_UNPROCESSED<sup>14+</sup> | 14 | Audio source for raw microphone recording, where the system does not perform any algorithm processing.<br>**System capability**: SystemCapability.Multimedia.Audio.Core| 881| SOURCE_TYPE_LIVE<sup>20+</sup> | 17 | Audio source in live streaming scenarios.<br>**System capability**: SystemCapability.Multimedia.Audio.Core| 882 883## AudioPlaybackCaptureConfig<sup>(deprecated)</sup> 884 885Defines the configuration of internal audio recording. 886 887> **NOTE** 888> 889> This API is supported since API version 10 and deprecated since API version 12. You are advised to use [AVScreenCapture](../apis-media-kit/capi-avscreencapture.md) instead. 890 891**System capability**: SystemCapability.Multimedia.Audio.PlaybackCapture 892 893| Name | Type | Mandatory| Description | 894| ------------- | --------------------------------------------- | ---- | -------------------------------- | 895| filterOptions | [CaptureFilterOptions](#capturefilteroptionsdeprecated) | Yes | Options for filtering the played audio streams to be recorded.| 896 897## CaptureFilterOptions<sup>(deprecated)</sup> 898 899Defines the options for filtering the played audio streams to be recorded. 900 901> **NOTE** 902> 903> This API is supported since API version 10 and deprecated since API version 12. You are advised to use [AVScreenCapture](../apis-media-kit/capi-avscreencapture.md) instead. 904 905**System capability**: SystemCapability.Multimedia.Audio.PlaybackCapture 906 907| Name | Type | Mandatory| Description | 908| ------ | ---------------------------------- | ---- | ------------------------------------------------------------ | 909| usages | Array<[StreamUsage](#streamusage)> | Yes | **StreamUsage** of the audio stream to be recorded. You can specify zero or more stream usages. If the array is empty, the audio stream for which **StreamUsage** is **STREAM_USAGE_MUSIC**, **STREAM_USAGE_MOVIE**, **STREAM_USAGE_GAME**, or **STREAM_USAGE_AUDIOBOOK** is recorded by default.<br>In API version 10, **CaptureFilterOptions** supports **StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION**, and therefore the ohos.permission.CAPTURE_VOICE_DOWNLINK_AUDIO permission is required. Only system applications can request this permission.<br>Since API version 11, **CaptureFilterOptions** does not support **StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION**. Therefore, no permission is required for calling this API.| 910 911## AudioScene<sup>8+</sup> 912 913Enumerates the audio scenes. 914 915**System capability**: SystemCapability.Multimedia.Audio.Communication 916 917| Name | Value | Description | 918| :--------------------- | :----- | :-------------------------------------------- | 919| AUDIO_SCENE_DEFAULT | 0 | Default audio scene. | 920| AUDIO_SCENE_RINGING<sup>12+</sup> | 1 | Normal mode.| 921| AUDIO_SCENE_PHONE_CALL<sup>12+</sup> | 2 | Phone call scene.| 922| AUDIO_SCENE_VOICE_CHAT | 3 | Voice chat scene. | 923 924## AudioConcurrencyMode<sup>12+</sup> 925 926Enumerates the audio concurrency modes. 927 928**System capability**: SystemCapability.Multimedia.Audio.Core 929 930| Name | Value| Description | 931| :--------------------- |:--|:--------| 932| CONCURRENCY_DEFAULT | 0 | Uses the system strategy by default. | 933| CONCURRENCY_MIX_WITH_OTHERS | 1 | Mixes with other audio streams. | 934| CONCURRENCY_DUCK_OTHERS | 2 | Ducks other audio streams.| 935| CONCURRENCY_PAUSE_OTHERS | 3 | Pauses other audio streams.| 936 937## AudioSessionDeactivatedReason<sup>12+</sup> 938 939Enumerates the reasons for deactivating an audio session. 940 941**System capability**: SystemCapability.Multimedia.Audio.Core 942 943| Name | Value| Description | 944| :--------------------- |:--|:-------| 945| DEACTIVATED_LOWER_PRIORITY | 0 | The application focus is preempted.| 946| DEACTIVATED_TIMEOUT | 1 | The audio session times out. | 947 948## AudioSessionStrategy<sup>12+</sup> 949 950Describes an audio session strategy. 951 952**System capability**: SystemCapability.Multimedia.Audio.Core 953 954| Name | Type | Mandatory| Description | 955| :------------ |:------------------------------------------------| :--- | :--------------- | 956| concurrencyMode | [AudioConcurrencyMode](#audioconcurrencymode12) | Yes | Audio concurrency mode. | 957 958## AudioSessionDeactivatedEvent<sup>12+</sup> 959 960Describes the event indicating that an audio session is deactivated. 961 962**System capability**: SystemCapability.Multimedia.Audio.Core 963 964| Name | Type | Mandatory| Description | 965| :------------ |:------------------------------------------------------------------| :--- | :--------------- | 966| reason | [AudioSessionDeactivatedReason](#audiosessiondeactivatedreason12) | Yes | Reason for deactivating an audio session. | 967 968## AudioManager 969 970Implements audio volume and device management. 971 972Before calling any API in AudioManager, you must use [getAudioManager](#audiogetaudiomanager) to create an AudioManager instance. 973 974### setAudioParameter<sup>(deprecated)</sup> 975 976setAudioParameter(key: string, value: string, callback: AsyncCallback<void>): void 977 978Sets an audio parameter. This API uses an asynchronous callback to return the result. 979 980This API is used to extend the audio configuration based on the hardware capability. The supported audio parameters vary according to the device and are not common parameters. Sample parameters are used in the sample code below. 981 982> **NOTE** 983> 984> This API is supported since API version 7 and deprecated since API version 11. Its substitute is available only to system applications. 985 986**Required permissions**: ohos.permission.MODIFY_AUDIO_SETTINGS 987 988**System capability**: SystemCapability.Multimedia.Audio.Core 989 990**Parameters** 991 992| Name | Type | Mandatory| Description | 993| -------- | ------------------------- | ---- | ------------------------ | 994| key | string | Yes | Key of the audio parameter to set. | 995| value | string | Yes | Value of the audio parameter to set. | 996| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 997 998**Example** 999 1000```ts 1001import { BusinessError } from '@kit.BasicServicesKit'; 1002 1003audioManager.setAudioParameter('key_example', 'value_example', (err: BusinessError) => { 1004 if (err) { 1005 console.error(`Failed to set the audio parameter. ${err}`); 1006 return; 1007 } 1008 console.info('Callback invoked to indicate a successful setting of the audio parameter.'); 1009}); 1010``` 1011 1012### setAudioParameter<sup>(deprecated)</sup> 1013 1014setAudioParameter(key: string, value: string): Promise<void> 1015 1016Sets an audio parameter. This API uses a promise to return the result. 1017 1018This API is used to extend the audio configuration based on the hardware capability. The supported audio parameters vary according to the device and are not common parameters. Sample parameters are used in the sample code below. 1019 1020> **NOTE** 1021> 1022> This API is supported since API version 7 and deprecated since API version 11. Its substitute is available only to system applications. 1023 1024**Required permissions**: ohos.permission.MODIFY_AUDIO_SETTINGS 1025 1026**System capability**: SystemCapability.Multimedia.Audio.Core 1027 1028**Parameters** 1029 1030| Name| Type | Mandatory| Description | 1031| ------ | ------ | ---- | ---------------------- | 1032| key | string | Yes | Key of the audio parameter to set.| 1033| value | string | Yes | Value of the audio parameter to set.| 1034 1035**Return value** 1036 1037| Type | Description | 1038| ------------------- | ------------------------------- | 1039| Promise<void> | Promise that returns no value.| 1040 1041**Example** 1042 1043```ts 1044audioManager.setAudioParameter('key_example', 'value_example').then(() => { 1045 console.info('Promise returned to indicate a successful setting of the audio parameter.'); 1046}); 1047``` 1048 1049### getAudioParameter<sup>(deprecated)</sup> 1050 1051getAudioParameter(key: string, callback: AsyncCallback<string>): void 1052 1053Obtains the value of an audio parameter. This API uses an asynchronous callback to return the result. 1054 1055This API is used to extend the audio configuration based on the hardware capability. The supported audio parameters vary according to the device and can be obtained from the device manual. The example below is for reference only. 1056 1057> **NOTE** 1058> 1059> This API is supported since API version 7 and deprecated since API version 11. Its substitute is available only to system applications. 1060 1061**System capability**: SystemCapability.Multimedia.Audio.Core 1062 1063**Parameters** 1064 1065| Name | Type | Mandatory| Description | 1066| -------- | --------------------------- | ---- | ---------------------------- | 1067| key | string | Yes | Key of the audio parameter whose value is to be obtained. | 1068| callback | AsyncCallback<string> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the audio parameter value obtained; otherwise, **err** is an error object.| 1069 1070**Example** 1071 1072```ts 1073import { BusinessError } from '@kit.BasicServicesKit'; 1074 1075audioManager.getAudioParameter('key_example', (err: BusinessError, value: string) => { 1076 if (err) { 1077 console.error(`Failed to obtain the value of the audio parameter. ${err}`); 1078 return; 1079 } 1080 console.info(`Callback invoked to indicate that the value of the audio parameter is obtained ${value}.`); 1081}); 1082``` 1083 1084### getAudioParameter<sup>(deprecated)</sup> 1085 1086getAudioParameter(key: string): Promise<string> 1087 1088Obtains the value of an audio parameter. This API uses a promise to return the result. 1089 1090This API is used to extend the audio configuration based on the hardware capability. The supported audio parameters vary according to the device and can be obtained from the device manual. The example below is for reference only. 1091 1092> **NOTE** 1093> 1094> This API is supported since API version 7 and deprecated since API version 11. Its substitute is available only to system applications. 1095 1096**System capability**: SystemCapability.Multimedia.Audio.Core 1097 1098**Parameters** 1099 1100| Name| Type | Mandatory| Description | 1101| ------ | ------ | ---- | ---------------------- | 1102| key | string | Yes | Key of the audio parameter whose value is to be obtained.| 1103 1104**Return value** 1105 1106| Type | Description | 1107| --------------------- | ----------------------------------- | 1108| Promise<string> | Promise used to return the value of the audio parameter.| 1109 1110**Example** 1111 1112```ts 1113audioManager.getAudioParameter('key_example').then((value: string) => { 1114 console.info(`Promise returned to indicate that the value of the audio parameter is obtained ${value}.`); 1115}); 1116``` 1117 1118### getAudioScene<sup>8+</sup> 1119 1120getAudioScene\(callback: AsyncCallback<AudioScene\>\): void 1121 1122Obtains the audio scene. This API uses an asynchronous callback to return the result. 1123 1124**System capability**: SystemCapability.Multimedia.Audio.Communication 1125 1126**Parameters** 1127 1128| Name | Type | Mandatory| Description | 1129| :------- | :-------------------------------------------------- | :--- | :--------------------------- | 1130| callback | AsyncCallback<[AudioScene](#audioscene8)> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the audio scene obtained; otherwise, **err** is an error object.| 1131 1132**Example** 1133 1134```ts 1135import { BusinessError } from '@kit.BasicServicesKit'; 1136 1137audioManager.getAudioScene((err: BusinessError, value: audio.AudioScene) => { 1138 if (err) { 1139 console.error(`Failed to obtain the audio scene mode. ${err}`); 1140 return; 1141 } 1142 console.info(`Callback invoked to indicate that the audio scene mode is obtained ${value}.`); 1143}); 1144``` 1145 1146### getAudioScene<sup>8+</sup> 1147 1148getAudioScene\(\): Promise<AudioScene\> 1149 1150Obtains the audio scene. This API uses a promise to return the result. 1151 1152**System capability**: SystemCapability.Multimedia.Audio.Communication 1153 1154**Return value** 1155 1156| Type | Description | 1157| :-------------------------------------------- | :--------------------------- | 1158| Promise<[AudioScene](#audioscene8)> | Promise used to return the audio scene.| 1159 1160**Example** 1161 1162```ts 1163import { BusinessError } from '@kit.BasicServicesKit'; 1164 1165audioManager.getAudioScene().then((value: audio.AudioScene) => { 1166 console.info(`Promise returned to indicate that the audio scene mode is obtained ${value}.`); 1167}).catch ((err: BusinessError) => { 1168 console.error(`Failed to obtain the audio scene mode ${err}`); 1169}); 1170``` 1171 1172### getAudioSceneSync<sup>10+</sup> 1173 1174getAudioSceneSync\(\): AudioScene 1175 1176Obtains the audio scene. This API returns the result synchronously. 1177 1178**System capability**: SystemCapability.Multimedia.Audio.Communication 1179 1180**Return value** 1181 1182| Type | Description | 1183| :-------------------------------------------- | :--------------------------- | 1184| [AudioScene](#audioscene8) | Audio scene.| 1185 1186**Example** 1187 1188```ts 1189import { BusinessError } from '@kit.BasicServicesKit'; 1190 1191try { 1192 let value: audio.AudioScene = audioManager.getAudioSceneSync(); 1193 console.info(`indicate that the audio scene mode is obtained ${value}.`); 1194} catch (err) { 1195 let error = err as BusinessError; 1196 console.error(`Failed to obtain the audio scene mode ${error}`); 1197} 1198``` 1199 1200### on('audioSceneChange')<sup>20+</sup> 1201 1202on(type: 'audioSceneChange', callback: Callback\<AudioScene\>): void 1203 1204Subscribes to the audio scene change event. This API uses an asynchronous callback to return the result. 1205 1206**System capability**: SystemCapability.Multimedia.Audio.Communication 1207 1208**Parameters** 1209 1210| Name | Type | Mandatory| Description | 1211| :------- | :------------------------- | :--- | :------------------------------------------ | 1212| type | string | Yes | Event type. The event **'audioSceneChange'** is triggered when the audio scene is changed.| 1213| callback | Callback\<[AudioScene](#audioscene8)> | Yes | Callback used to return the current audio scene.| 1214 1215**Example** 1216 1217```ts 1218audioManager.on('audioSceneChange', (audioScene: audio.AudioScene) => { 1219 console.info(`audio scene : ${audioScene}.`); 1220}); 1221``` 1222 1223### off('audioSceneChange')<sup>20+</sup> 1224 1225off(type: 'audioSceneChange', callback?: Callback\<AudioScene\>): void 1226 1227Unsubscribes from the audio scene change event. This API uses an asynchronous callback to return the result. 1228 1229**System capability**: SystemCapability.Multimedia.Audio.Communication 1230 1231**Parameters** 1232 1233| Name | Type | Mandatory| Description | 1234| :------- | :------------------------- | :--- | :------------------------------------------ | 1235| type | string | Yes | Event type. The event **'audioSceneChange'** is triggered when the audio scene is changed.| 1236| callback | Callback\<[AudioScene](#audioscene8)> | Yes | Callback used to return the current audio scene.| 1237 1238**Example** 1239 1240```ts 1241// Cancel all subscriptions to the event. 1242audioManager.off('audioSceneChange'); 1243 1244// For the same event, if the callback parameter passed to the off API is the same as that passed to the on API, the off API cancels the subscription registered with the specified callback parameter. 1245let audioSceneChangeCallback = (audioScene: audio.AudioScene) => { 1246 console.info(`audio scene : ${audioScene}.`); 1247}; 1248 1249audioManager.on('audioSceneChange', audioSceneChangeCallback); 1250 1251audioManager.off('audioSceneChange', audioSceneChangeCallback); 1252``` 1253 1254### getVolumeManager<sup>9+</sup> 1255 1256getVolumeManager(): AudioVolumeManager 1257 1258Obtains an AudioVolumeManager instance. 1259 1260**System capability**: SystemCapability.Multimedia.Audio.Volume 1261 1262**Return value** 1263 1264| Type | Description | 1265|-----------------------------------------| ----------------------------- | 1266| [AudioVolumeManager](#audiovolumemanager9) | AudioVolumeManager instance.| 1267 1268**Example** 1269 1270```ts 1271import { audio } from '@kit.AudioKit'; 1272 1273let audioVolumeManager: audio.AudioVolumeManager = audioManager.getVolumeManager(); 1274``` 1275 1276### getStreamManager<sup>9+</sup> 1277 1278getStreamManager(): AudioStreamManager 1279 1280Obtains an AudioStreamManager instance. 1281 1282**System capability**: SystemCapability.Multimedia.Audio.Core 1283 1284**Return value** 1285 1286| Type | Description | 1287|--------------------------------------------| ----------------------------- | 1288| [AudioStreamManager](#audiostreammanager9) | AudioStreamManager instance.| 1289 1290**Example** 1291 1292```ts 1293import { audio } from '@kit.AudioKit'; 1294 1295let audioStreamManager: audio.AudioStreamManager = audioManager.getStreamManager(); 1296``` 1297 1298### getRoutingManager<sup>9+</sup> 1299 1300getRoutingManager(): AudioRoutingManager 1301 1302Obtains an AudioRoutingManager instance. 1303 1304**System capability**: SystemCapability.Multimedia.Audio.Device 1305 1306**Return value** 1307 1308| Type | Description | 1309|------------------------------------------| ----------------------------- | 1310| [AudioRoutingManager](#audioroutingmanager9) | AudioRoutingManager instance.| 1311 1312**Example** 1313 1314```ts 1315import { audio } from '@kit.AudioKit'; 1316 1317let audioRoutingManager: audio.AudioRoutingManager = audioManager.getRoutingManager(); 1318``` 1319 1320### getSessionManager<sup>12+</sup> 1321 1322getSessionManager(): AudioSessionManager 1323 1324Obtains an AudioSessionManager instance. 1325 1326**System capability**: SystemCapability.Multimedia.Audio.Core 1327 1328**Return value** 1329 1330| Type | Description | 1331|----------------------------------------------| ----------------------------- | 1332| [AudioSessionManager](#audiosessionmanager12) | AudioSessionManager instance.| 1333 1334**Example** 1335 1336```ts 1337import { audio } from '@kit.AudioKit'; 1338 1339let audioSessionManager: audio.AudioSessionManager = audioManager.getSessionManager(); 1340``` 1341 1342### getSpatializationManager<sup>18+</sup> 1343 1344getSpatializationManager(): AudioSpatializationManager 1345 1346Obtains an AudioSpatializationManager instance. 1347 1348**System capability**: SystemCapability.Multimedia.Audio.Spatialization 1349 1350**Return value** 1351 1352| Type | Description | 1353|------------------------------------------| ----------------------------- | 1354| [AudioSpatializationManager](#audiospatializationmanager18) | AudioSpatializationManager instance.| 1355 1356**Example** 1357 1358```ts 1359import { audio } from '@kit.AudioKit'; 1360let audioSpatializationManager: audio.AudioSpatializationManager = audioManager.getSpatializationManager(); 1361``` 1362 1363### setVolume<sup>(deprecated)</sup> 1364 1365setVolume(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback<void>): void 1366 1367Sets the volume for a stream. This API uses an asynchronous callback to return the result. 1368 1369> **NOTE** 1370> 1371> This API is supported since API version 7 and deprecated since API version 9. Its substitute is available only to system applications. 1372> 1373> Applications cannot directly adjust the system volume. They can use the system volume panel to control the volume. For details about the samples and introduction, see [AVVolumePanel Reference](ohos-multimedia-avvolumepanel.md). 1374 1375**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY 1376 1377This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. 1378 1379**System capability**: SystemCapability.Multimedia.Audio.Volume 1380 1381**Parameters** 1382 1383| Name | Type | Mandatory| Description | 1384| ---------- | ----------------------------------- | ---- | -------------------------------------------------------- | 1385| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | 1386| volume | number | Yes | Volume to set. The value range can be obtained by calling [getMinVolume](#getminvolumedeprecated) and [getMaxVolume](#getmaxvolumedeprecated).| 1387| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 1388 1389**Example** 1390 1391```ts 1392import { BusinessError } from '@kit.BasicServicesKit'; 1393 1394audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10, (err: BusinessError) => { 1395 if (err) { 1396 console.error(`Failed to set the volume. ${err}`); 1397 return; 1398 } 1399 console.info('Callback invoked to indicate a successful volume setting.'); 1400}); 1401``` 1402 1403### setVolume<sup>(deprecated)</sup> 1404 1405setVolume(volumeType: AudioVolumeType, volume: number): Promise<void> 1406 1407Sets the volume for a stream. This API uses a promise to return the result. 1408 1409> **NOTE** 1410> 1411> This API is supported since API version 7 and deprecated since API version 9. Its substitute is available only to system applications. 1412> 1413> Applications cannot directly adjust the system volume. They can use the system volume panel to control the volume. For details about the samples and introduction, see [AVVolumePanel Reference](ohos-multimedia-avvolumepanel.md). 1414 1415**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY 1416 1417This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. 1418 1419**System capability**: SystemCapability.Multimedia.Audio.Volume 1420 1421**Parameters** 1422 1423| Name | Type | Mandatory| Description | 1424| ---------- | ----------------------------------- | ---- | -------------------------------------------------------- | 1425| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | 1426| volume | number | Yes | Volume to set. The value range can be obtained by calling [getMinVolume](#getminvolumedeprecated) and [getMaxVolume](#getmaxvolumedeprecated).| 1427 1428**Return value** 1429 1430| Type | Description | 1431| ------------------- | ----------------------------- | 1432| Promise<void> | Promise that returns no value.| 1433 1434**Example** 1435 1436```ts 1437audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10).then(() => { 1438 console.info('Promise returned to indicate a successful volume setting.'); 1439}); 1440``` 1441 1442### getVolume<sup>(deprecated)</sup> 1443 1444getVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void 1445 1446Obtains the volume of a stream. This API uses an asynchronous callback to return the result. 1447 1448> **NOTE** 1449> 1450> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getVolume](#getvolume9) instead. 1451 1452**System capability**: SystemCapability.Multimedia.Audio.Volume 1453 1454**Parameters** 1455 1456| Name | Type | Mandatory| Description | 1457| ---------- | ----------------------------------- | ---- | ------------------ | 1458| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | 1459| callback | AsyncCallback<number> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the stream volume obtained; otherwise, **err** is an error object. The volume range of a specified stream can be obtained by calling [getMinVolume](#getminvolumedeprecated) and [getMaxVolume](#getmaxvolumedeprecated).| 1460 1461**Example** 1462 1463```ts 1464import { BusinessError } from '@kit.BasicServicesKit'; 1465 1466audioManager.getVolume(audio.AudioVolumeType.MEDIA, (err: BusinessError, value: number) => { 1467 if (err) { 1468 console.error(`Failed to obtain the volume. ${err}`); 1469 return; 1470 } 1471 console.info('Callback invoked to indicate that the volume is obtained.'); 1472}); 1473``` 1474 1475### getVolume<sup>(deprecated)</sup> 1476 1477getVolume(volumeType: AudioVolumeType): Promise<number> 1478 1479Obtains the volume of a stream. This API uses a promise to return the result. 1480 1481> **NOTE** 1482> 1483> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getVolume](#getvolume9) instead. 1484 1485**System capability**: SystemCapability.Multimedia.Audio.Volume 1486 1487**Parameters** 1488 1489| Name | Type | Mandatory| Description | 1490| ---------- | ----------------------------------- | ---- | ------------ | 1491| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| 1492 1493**Return value** 1494 1495| Type | Description | 1496| --------------------- | ------------------------- | 1497| Promise<number> | Promise used to return the volume of the stream. The volume range of a specified stream can be obtained by calling [getMinVolume](#getminvolumedeprecated) and [getMaxVolume](#getmaxvolumedeprecated).| 1498 1499**Example** 1500 1501```ts 1502audioManager.getVolume(audio.AudioVolumeType.MEDIA).then((value: number) => { 1503 console.info(`Promise returned to indicate that the volume is obtained ${value} .`); 1504}); 1505``` 1506 1507### getMinVolume<sup>(deprecated)</sup> 1508 1509getMinVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void 1510 1511Obtains the minimum volume allowed for a stream. This API uses an asynchronous callback to return the result. 1512 1513> **NOTE** 1514> 1515> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getMinVolume](#getminvolume9) instead. 1516 1517**System capability**: SystemCapability.Multimedia.Audio.Volume 1518 1519**Parameters** 1520 1521| Name | Type | Mandatory| Description | 1522| ---------- | ----------------------------------- | ---- | ------------------ | 1523| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | 1524| callback | AsyncCallback<number> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the minimum stream volume obtained; otherwise, **err** is an error object.| 1525 1526**Example** 1527 1528```ts 1529import { BusinessError } from '@kit.BasicServicesKit'; 1530 1531audioManager.getMinVolume(audio.AudioVolumeType.MEDIA, (err: BusinessError, value: number) => { 1532 if (err) { 1533 console.error(`Failed to obtain the minimum volume. ${err}`); 1534 return; 1535 } 1536 console.info(`Callback invoked to indicate that the minimum volume is obtained. ${value}`); 1537}); 1538``` 1539 1540### getMinVolume<sup>(deprecated)</sup> 1541 1542getMinVolume(volumeType: AudioVolumeType): Promise<number> 1543 1544Obtains the minimum volume allowed for a stream. This API uses a promise to return the result. 1545 1546> **NOTE** 1547> 1548> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getMinVolume](#getminvolume9) instead. 1549 1550**System capability**: SystemCapability.Multimedia.Audio.Volume 1551 1552**Parameters** 1553 1554| Name | Type | Mandatory| Description | 1555| ---------- | ----------------------------------- | ---- | ------------ | 1556| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| 1557 1558**Return value** 1559 1560| Type | Description | 1561| --------------------- | ------------------------- | 1562| Promise<number> | Promise used to return the minimum volume.| 1563 1564**Example** 1565 1566```ts 1567audioManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value: number) => { 1568 console.info(`Promised returned to indicate that the minimum volume is obtained. ${value}`); 1569}); 1570``` 1571 1572### getMaxVolume<sup>(deprecated)</sup> 1573 1574getMaxVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void 1575 1576Obtains the maximum volume allowed for a stream. This API uses an asynchronous callback to return the result. 1577 1578> **NOTE** 1579> 1580> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getMaxVolume](#getmaxvolume9) instead. 1581 1582**System capability**: SystemCapability.Multimedia.Audio.Volume 1583 1584**Parameters** 1585 1586| Name | Type | Mandatory| Description | 1587| ---------- | ----------------------------------- | ---- | ---------------------- | 1588| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | 1589| callback | AsyncCallback<number> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the maximum stream volume obtained; otherwise, **err** is an error object.| 1590 1591**Example** 1592 1593```ts 1594import { BusinessError } from '@kit.BasicServicesKit'; 1595 1596audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err: BusinessError, value: number) => { 1597 if (err) { 1598 console.error(`Failed to obtain the maximum volume. ${err}`); 1599 return; 1600 } 1601 console.info(`Callback invoked to indicate that the maximum volume is obtained. ${value}`); 1602}); 1603``` 1604 1605### getMaxVolume<sup>(deprecated)</sup> 1606 1607getMaxVolume(volumeType: AudioVolumeType): Promise<number> 1608 1609Obtains the maximum volume allowed for a stream. This API uses a promise to return the result. 1610 1611> **NOTE** 1612> 1613> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getMaxVolume](#getmaxvolume9) instead. 1614 1615**System capability**: SystemCapability.Multimedia.Audio.Volume 1616 1617**Parameters** 1618 1619| Name | Type | Mandatory| Description | 1620| ---------- | ----------------------------------- | ---- | ------------ | 1621| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| 1622 1623**Return value** 1624 1625| Type | Description | 1626| --------------------- | ----------------------------- | 1627| Promise<number> | Promise used to return the maximum volume.| 1628 1629**Example** 1630 1631```ts 1632audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((data: number) => { 1633 console.info('Promised returned to indicate that the maximum volume is obtained.'); 1634}); 1635``` 1636 1637### mute<sup>(deprecated)</sup> 1638 1639mute(volumeType: AudioVolumeType, mute: boolean, callback: AsyncCallback<void>): void 1640 1641Mutes or unmutes a stream. This API uses an asynchronous callback to return the result. 1642 1643When the minimum volume of a stream cannot be set to 0, muting the stream is not supported. Example scenarios: alarms or phone calls. 1644 1645> **NOTE** 1646> 1647> This API is supported since API version 7 and deprecated since API version 9. Its substitute is available only to system applications. 1648 1649**System capability**: SystemCapability.Multimedia.Audio.Volume 1650 1651**Parameters** 1652 1653| Name | Type | Mandatory| Description | 1654| ---------- | ----------------------------------- | ---- | ------------------------------------- | 1655| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | 1656| mute | boolean | Yes | Whether to mute the stream. The value **true** means to mute the stream, and **false** means the opposite.| 1657| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 1658 1659**Example** 1660 1661```ts 1662import { BusinessError } from '@kit.BasicServicesKit'; 1663 1664audioManager.mute(audio.AudioVolumeType.MEDIA, true, (err: BusinessError) => { 1665 if (err) { 1666 console.error(`Failed to mute the stream. ${err}`); 1667 return; 1668 } 1669 console.info('Callback invoked to indicate that the stream is muted.'); 1670}); 1671``` 1672 1673### mute<sup>(deprecated)</sup> 1674 1675mute(volumeType: AudioVolumeType, mute: boolean): Promise<void> 1676 1677Mutes or unmutes a stream. This API uses a promise to return the result. 1678 1679When the minimum volume of a stream cannot be set to 0, muting the stream is not supported. Example scenarios: alarms or phone calls. 1680 1681> **NOTE** 1682> 1683> This API is supported since API version 7 and deprecated since API version 9. Its substitute is available only to system applications. 1684 1685**System capability**: SystemCapability.Multimedia.Audio.Volume 1686 1687**Parameters** 1688 1689| Name | Type | Mandatory| Description | 1690| ---------- | ----------------------------------- | ---- | ------------------------------------- | 1691| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | 1692| mute | boolean | Yes | Whether to mute the stream. The value **true** means to mute the stream, and **false** means the opposite.| 1693 1694**Return value** 1695 1696| Type | Description | 1697| ------------------- | ----------------------------- | 1698| Promise<void> | Promise that returns no value.| 1699 1700**Example** 1701 1702 1703```ts 1704audioManager.mute(audio.AudioVolumeType.MEDIA, true).then(() => { 1705 console.info('Promise returned to indicate that the stream is muted.'); 1706}); 1707``` 1708 1709### isMute<sup>(deprecated)</sup> 1710 1711isMute(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void 1712 1713Checks whether a stream is muted. This API uses an asynchronous callback to return the result. 1714 1715> **NOTE** 1716> 1717> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isMute](#ismute9) instead. 1718 1719**System capability**: SystemCapability.Multimedia.Audio.Volume 1720 1721**Parameters** 1722 1723| Name | Type | Mandatory| Description | 1724| ---------- | ----------------------------------- | ---- | ----------------------------------------------- | 1725| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | 1726| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is **true** if the stream is muted or **false** if not muted; otherwise, **err** is an error object.| 1727 1728**Example** 1729 1730```ts 1731import { BusinessError } from '@kit.BasicServicesKit'; 1732 1733audioManager.isMute(audio.AudioVolumeType.MEDIA, (err: BusinessError, value: boolean) => { 1734 if (err) { 1735 console.error(`Failed to obtain the mute status. ${err}`); 1736 return; 1737 } 1738 console.info(`Callback invoked to indicate that the mute status of the stream is obtained. ${value}`); 1739}); 1740``` 1741 1742### isMute<sup>(deprecated)</sup> 1743 1744isMute(volumeType: AudioVolumeType): Promise<boolean> 1745 1746Checks whether a stream is muted. This API uses a promise to return the result. 1747 1748> **NOTE** 1749> 1750> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isMute](#ismute9) instead. 1751 1752**System capability**: SystemCapability.Multimedia.Audio.Volume 1753 1754**Parameters** 1755 1756| Name | Type | Mandatory| Description | 1757| ---------- | ----------------------------------- | ---- | ------------ | 1758| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| 1759 1760**Return value** 1761 1762| Type | Description | 1763| ---------------------- | ------------------------------------------------------ | 1764| Promise<boolean> | Promise used to return the result. The value **true** means that the stream is muted, and **false** means the opposite.| 1765 1766**Example** 1767 1768```ts 1769audioManager.isMute(audio.AudioVolumeType.MEDIA).then((value: boolean) => { 1770 console.info(`Promise returned to indicate that the mute status of the stream is obtained ${value}.`); 1771}); 1772``` 1773 1774### isActive<sup>(deprecated)</sup> 1775 1776isActive(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void 1777 1778Checks whether a stream is active. This API uses an asynchronous callback to return the result. 1779 1780> **NOTE** 1781> 1782> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isActive](#isactive9) instead. 1783 1784**System capability**: SystemCapability.Multimedia.Audio.Volume 1785 1786**Parameters** 1787 1788| Name | Type | Mandatory| Description | 1789| ---------- | ----------------------------------- | ---- | ------------------------------------------------- | 1790| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | 1791| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is **true** if the stream is active or **false** if not active; otherwise, **err** is an error object.| 1792 1793**Example** 1794 1795```ts 1796import { BusinessError } from '@kit.BasicServicesKit'; 1797 1798audioManager.isActive(audio.AudioVolumeType.MEDIA, (err: BusinessError, value: boolean) => { 1799 if (err) { 1800 console.error(`Failed to obtain the active status of the stream. ${err}`); 1801 return; 1802 } 1803 console.info(`Callback invoked to indicate that the active status of the stream is obtained ${value}.`); 1804}); 1805``` 1806 1807### isActive<sup>(deprecated)</sup> 1808 1809isActive(volumeType: AudioVolumeType): Promise<boolean> 1810 1811Checks whether a stream is active. This API uses a promise to return the result. 1812 1813> **NOTE** 1814> 1815> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isActive](#isactive9) instead. 1816 1817**System capability**: SystemCapability.Multimedia.Audio.Volume 1818 1819**Parameters** 1820 1821| Name | Type | Mandatory| Description | 1822| ---------- | ----------------------------------- | ---- | ------------ | 1823| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| 1824 1825**Return value** 1826 1827| Type | Description | 1828| ---------------------- | -------------------------------------------------------- | 1829| Promise<boolean> | Promise used to return the result. The value **true** means that the stream is active, and **false** means the opposite.| 1830 1831**Example** 1832 1833```ts 1834audioManager.isActive(audio.AudioVolumeType.MEDIA).then((value: boolean) => { 1835 console.info(`Promise returned to indicate that the active status of the stream is obtained ${value}.`); 1836}); 1837``` 1838 1839### setRingerMode<sup>(deprecated)</sup> 1840 1841setRingerMode(mode: AudioRingMode, callback: AsyncCallback<void>): void 1842 1843Sets the ringer mode. This API uses an asynchronous callback to return the result. 1844 1845> **NOTE** 1846> 1847> This API is supported since API version 7 and deprecated since API version 9. Its substitute is available only to system applications. 1848 1849**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY 1850 1851This permission is required only for muting or unmuting the ringer. 1852 1853**System capability**: SystemCapability.Multimedia.Audio.Communication 1854 1855**Parameters** 1856 1857| Name | Type | Mandatory| Description | 1858| -------- | ------------------------------- | ---- | ------------------------ | 1859| mode | [AudioRingMode](#audioringmode) | Yes | Ringer mode. | 1860| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 1861 1862**Example** 1863 1864```ts 1865import { BusinessError } from '@kit.BasicServicesKit'; 1866 1867audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL, (err: BusinessError) => { 1868 if (err) { 1869 console.error(`Failed to set the ringer mode. ${err}`); 1870 return; 1871 } 1872 console.info('Callback invoked to indicate a successful setting of the ringer mode.'); 1873}); 1874``` 1875 1876### setRingerMode<sup>(deprecated)</sup> 1877 1878setRingerMode(mode: AudioRingMode): Promise<void> 1879 1880Sets the ringer mode. This API uses a promise to return the result. 1881 1882> **NOTE** 1883> 1884> This API is supported since API version 7 and deprecated since API version 9. Its substitute is available only to system applications. 1885 1886 1887**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY 1888 1889This permission is required only for muting or unmuting the ringer. 1890 1891**System capability**: SystemCapability.Multimedia.Audio.Communication 1892 1893**Parameters** 1894 1895| Name| Type | Mandatory| Description | 1896| ------ | ------------------------------- | ---- | -------------- | 1897| mode | [AudioRingMode](#audioringmode) | Yes | Ringer mode.| 1898 1899**Return value** 1900 1901| Type | Description | 1902| ------------------- | ------------------------------- | 1903| Promise<void> | Promise that returns no value.| 1904 1905**Example** 1906 1907```ts 1908audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL).then(() => { 1909 console.info('Promise returned to indicate a successful setting of the ringer mode.'); 1910}); 1911``` 1912 1913### getRingerMode<sup>(deprecated)</sup> 1914 1915getRingerMode(callback: AsyncCallback<AudioRingMode>): void 1916 1917Obtains the ringer mode. This API uses an asynchronous callback to return the result. 1918 1919> **NOTE** 1920> 1921> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getRingerMode](#getringermode9) instead. 1922 1923**System capability**: SystemCapability.Multimedia.Audio.Communication 1924 1925**Parameters** 1926 1927| Name | Type | Mandatory| Description | 1928| -------- | ---------------------------------------------------- | ---- | ------------------------ | 1929| callback | AsyncCallback<[AudioRingMode](#audioringmode)> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the ringer mode obtained; otherwise, **err** is an error object.| 1930 1931**Example** 1932 1933```ts 1934import { BusinessError } from '@kit.BasicServicesKit'; 1935 1936audioManager.getRingerMode((err: BusinessError, value: audio.AudioRingMode) => { 1937 if (err) { 1938 console.error(`Failed to obtain the ringer mode. ${err}`); 1939 return; 1940 } 1941 console.info(`Callback invoked to indicate that the ringer mode is obtained ${value}.`); 1942}); 1943``` 1944 1945### getRingerMode<sup>(deprecated)</sup> 1946 1947getRingerMode(): Promise<AudioRingMode> 1948 1949Obtains the ringer mode. This API uses a promise to return the result. 1950 1951> **NOTE** 1952> 1953> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getRingerMode](#getringermode9) instead. 1954 1955**System capability**: SystemCapability.Multimedia.Audio.Communication 1956 1957**Return value** 1958 1959| Type | Description | 1960| ---------------------------------------------- | ------------------------------- | 1961| Promise<[AudioRingMode](#audioringmode)> | Promise used to return the ringer mode.| 1962 1963**Example** 1964 1965```ts 1966audioManager.getRingerMode().then((value: audio.AudioRingMode) => { 1967 console.info(`Promise returned to indicate that the ringer mode is obtained ${value}.`); 1968}); 1969``` 1970 1971### getDevices<sup>(deprecated)</sup> 1972 1973getDevices(deviceFlag: DeviceFlag, callback: AsyncCallback<AudioDeviceDescriptors>): void 1974 1975Obtains the audio devices with a specific flag. This API uses an asynchronous callback to return the result. 1976 1977> **NOTE** 1978> 1979> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getDevices](#getdevices9) instead. 1980 1981**System capability**: SystemCapability.Multimedia.Audio.Device 1982 1983**Parameters** 1984 1985| Name | Type | Mandatory| Description | 1986| ---------- | ------------------------------------------------------------ | ---- | -------------------- | 1987| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag. | 1988| callback | AsyncCallback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the audio devices obtained; otherwise, **err** is an error object.| 1989 1990**Example** 1991```ts 1992import { BusinessError } from '@kit.BasicServicesKit'; 1993 1994audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err: BusinessError, value: audio.AudioDeviceDescriptors) => { 1995 if (err) { 1996 console.error(`Failed to obtain the device list. ${err}`); 1997 return; 1998 } 1999 console.info('Callback invoked to indicate that the device list is obtained.'); 2000}); 2001``` 2002 2003### getDevices<sup>(deprecated)</sup> 2004 2005getDevices(deviceFlag: DeviceFlag): Promise<AudioDeviceDescriptors> 2006 2007Obtains the audio devices with a specific flag. This API uses a promise to return the result. 2008 2009> **NOTE** 2010> 2011> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getDevices](#getdevices9) instead. 2012 2013**System capability**: SystemCapability.Multimedia.Audio.Device 2014 2015**Parameters** 2016 2017| Name | Type | Mandatory| Description | 2018| ---------- | ------------------------- | ---- | ---------------- | 2019| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag.| 2020 2021**Return value** 2022 2023| Type | Description | 2024| ------------------------------------------------------------ | ------------------------- | 2025| Promise<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Promise used to return the device list.| 2026 2027**Example** 2028 2029```ts 2030audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data: audio.AudioDeviceDescriptors) => { 2031 console.info('Promise returned to indicate that the device list is obtained.'); 2032}); 2033``` 2034 2035### setDeviceActive<sup>(deprecated)</sup> 2036 2037setDeviceActive(deviceType: ActiveDeviceType, active: boolean, callback: AsyncCallback<void>): void 2038 2039Sets a device to the active state. This API uses an asynchronous callback to return the result. 2040 2041> **NOTE** 2042> 2043> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setCommunicationDevice](#setcommunicationdevice9) instead. 2044 2045**System capability**: SystemCapability.Multimedia.Audio.Device 2046 2047**Parameters** 2048 2049| Name | Type | Mandatory| Description | 2050| ---------- | ------------------------------------- | ---- |-------------| 2051| deviceType | [ActiveDeviceType](#activedevicetypedeprecated) | Yes | Active audio device type. | 2052| active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite.| 2053| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 2054 2055**Example** 2056 2057```ts 2058import { BusinessError } from '@kit.BasicServicesKit'; 2059 2060audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true, (err: BusinessError) => { 2061 if (err) { 2062 console.error(`Failed to set the active status of the device. ${err}`); 2063 return; 2064 } 2065 console.info('Callback invoked to indicate that the device is set to the active status.'); 2066}); 2067``` 2068 2069### setDeviceActive<sup>(deprecated)</sup> 2070 2071setDeviceActive(deviceType: ActiveDeviceType, active: boolean): Promise<void> 2072 2073Sets a device to the active state. This API uses a promise to return the result. 2074 2075> **NOTE** 2076> 2077> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setCommunicationDevice](#setcommunicationdevice9) instead. 2078 2079**System capability**: SystemCapability.Multimedia.Audio.Device 2080 2081**Parameters** 2082 2083| Name | Type | Mandatory| Description | 2084| ---------- | ------------------------------------- | ---- | ------------------ | 2085| deviceType | [ActiveDeviceType](#activedevicetypedeprecated) | Yes | Active audio device type.| 2086| active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite.| 2087 2088**Return value** 2089 2090| Type | Description | 2091| ------------------- | ------------------------------- | 2092| Promise<void> | Promise that returns no value.| 2093 2094**Example** 2095 2096 2097```ts 2098audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true).then(() => { 2099 console.info('Promise returned to indicate that the device is set to the active status.'); 2100}); 2101``` 2102 2103### isDeviceActive<sup>(deprecated)</sup> 2104 2105isDeviceActive(deviceType: ActiveDeviceType, callback: AsyncCallback<boolean>): void 2106 2107Checks whether a device is active. This API uses an asynchronous callback to return the result. 2108 2109> **NOTE** 2110> 2111> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isCommunicationDeviceActive](#iscommunicationdeviceactive9) instead. 2112 2113**System capability**: SystemCapability.Multimedia.Audio.Device 2114 2115**Parameters** 2116 2117| Name | Type | Mandatory| Description | 2118| ---------- | ------------------------------------- | ---- | ------------------------ | 2119| deviceType | [ActiveDeviceType](#activedevicetypedeprecated) | Yes | Active audio device type. | 2120| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is **true** if the device is active or **false** if not active; otherwise, **err** is an error object.| 2121 2122**Example** 2123 2124```ts 2125import { BusinessError } from '@kit.BasicServicesKit'; 2126 2127audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER, (err: BusinessError, value: boolean) => { 2128 if (err) { 2129 console.error(`Failed to obtain the active status of the device. ${err}`); 2130 return; 2131 } 2132 console.info('Callback invoked to indicate that the active status of the device is obtained.'); 2133}); 2134``` 2135 2136### isDeviceActive<sup>(deprecated)</sup> 2137 2138isDeviceActive(deviceType: ActiveDeviceType): Promise<boolean> 2139 2140Checks whether a device is active. This API uses a promise to return the result. 2141 2142> **NOTE** 2143> 2144> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isCommunicationDeviceActive](#iscommunicationdeviceactive9) instead. 2145 2146**System capability**: SystemCapability.Multimedia.Audio.Device 2147 2148**Parameters** 2149 2150| Name | Type | Mandatory| Description | 2151| ---------- | ------------------------------------- | ---- | ------------------ | 2152| deviceType | [ActiveDeviceType](#activedevicetypedeprecated) | Yes | Active audio device type.| 2153 2154**Return value** 2155 2156| Type | Description | 2157| ---------------------- |---------------------------------------| 2158| Promise<boolean> | Promise used to return the result. The value **true** means that the device is active, and **false** means the opposite.| 2159 2160**Example** 2161 2162```ts 2163audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER).then((value: boolean) => { 2164 console.info(`Promise returned to indicate that the active status of the device is obtained ${value}.`); 2165}); 2166``` 2167 2168### setMicrophoneMute<sup>(deprecated)</sup> 2169 2170setMicrophoneMute(mute: boolean, callback: AsyncCallback<void>): void 2171 2172Mutes or unmutes the microphone. This API uses an asynchronous callback to return the result. 2173 2174> **NOTE** 2175> 2176> This API is supported since API version 7 and deprecated since API version 9. Its substitute is available only to system applications. 2177 2178**Required permissions**: ohos.permission.MICROPHONE 2179 2180**System capability**: SystemCapability.Multimedia.Audio.Device 2181 2182**Parameters** 2183 2184| Name | Type | Mandatory| Description | 2185| -------- | ------------------------- | ---- | --------------------------------------------- | 2186| mute | boolean | Yes | Mute status to set. The value **true** means to mute the microphone, and **false** means the opposite.| 2187| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 2188 2189**Example** 2190 2191```ts 2192import { BusinessError } from '@kit.BasicServicesKit'; 2193 2194audioManager.setMicrophoneMute(true, (err: BusinessError) => { 2195 if (err) { 2196 console.error(`Failed to mute the microphone. ${err}`); 2197 return; 2198 } 2199 console.info('Callback invoked to indicate that the microphone is muted.'); 2200}); 2201``` 2202 2203### setMicrophoneMute<sup>(deprecated)</sup> 2204 2205setMicrophoneMute(mute: boolean): Promise<void> 2206 2207Mutes or unmutes the microphone. This API uses a promise to return the result. 2208 2209> **NOTE** 2210> 2211> This API is supported since API version 7 and deprecated since API version 9. Its substitute is available only to system applications. 2212 2213**Required permissions**: ohos.permission.MICROPHONE 2214 2215**System capability**: SystemCapability.Multimedia.Audio.Device 2216 2217**Parameters** 2218 2219| Name| Type | Mandatory| Description | 2220| ------ | ------- | ---- | --------------------------------------------- | 2221| mute | boolean | Yes | Mute status to set. The value **true** means to mute the microphone, and **false** means the opposite.| 2222 2223**Return value** 2224 2225| Type | Description | 2226| ------------------- | ------------------------------- | 2227| Promise<void> | Promise that returns no value.| 2228 2229**Example** 2230 2231```ts 2232audioManager.setMicrophoneMute(true).then(() => { 2233 console.info('Promise returned to indicate that the microphone is muted.'); 2234}); 2235``` 2236 2237### isMicrophoneMute<sup>(deprecated)</sup> 2238 2239isMicrophoneMute(callback: AsyncCallback<boolean>): void 2240 2241Checks whether the microphone is muted. This API uses an asynchronous callback to return the result. 2242 2243> **NOTE** 2244> 2245> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isMicrophoneMute](#ismicrophonemute9) instead. 2246 2247**Required permissions**: ohos.permission.MICROPHONE 2248 2249**System capability**: SystemCapability.Multimedia.Audio.Device 2250 2251**Parameters** 2252 2253| Name | Type | Mandatory| Description | 2254| -------- | ---------------------------- | ---- | ------------------------------------------------------- | 2255| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is **true** if the microphone is muted or **false** if not muted; otherwise, **err** is an error object.| 2256 2257**Example** 2258 2259```ts 2260import { BusinessError } from '@kit.BasicServicesKit'; 2261 2262audioManager.isMicrophoneMute((err: BusinessError, value: boolean) => { 2263 if (err) { 2264 console.error(`Failed to obtain the mute status of the microphone. ${err}`); 2265 return; 2266 } 2267 console.info(`Callback invoked to indicate that the mute status of the microphone is obtained ${value}.`); 2268}); 2269``` 2270 2271### isMicrophoneMute<sup>(deprecated)</sup> 2272 2273isMicrophoneMute(): Promise<boolean> 2274 2275Checks whether the microphone is muted. This API uses a promise to return the result. 2276 2277> **NOTE** 2278> 2279> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isMicrophoneMute](#ismicrophonemute9) instead. 2280 2281**Required permissions**: ohos.permission.MICROPHONE 2282 2283**System capability**: SystemCapability.Multimedia.Audio.Device 2284 2285**Return value** 2286 2287| Type | Description | 2288| ---------------------- | ------------------------------------------------------------ | 2289| Promise<boolean> | Promise used to return the result. The value **true** means that the microphone is muted, and **false** means the opposite.| 2290 2291**Example** 2292 2293```ts 2294audioManager.isMicrophoneMute().then((value: boolean) => { 2295 console.info(`Promise returned to indicate that the mute status of the microphone is obtained ${value}.`); 2296}); 2297``` 2298 2299### on('deviceChange')<sup>(deprecated)</sup> 2300 2301on(type: 'deviceChange', callback: Callback<DeviceChangeAction\>): void 2302 2303Subscribes to the event indicating that the connection status of an audio device is changed. This API uses an asynchronous callback to return the result. 2304 2305> **NOTE** 2306> 2307> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [on('deviceChange')](#ondevicechange9) instead. 2308 2309**System capability**: SystemCapability.Multimedia.Audio.Device 2310 2311**Parameters** 2312 2313| Name | Type | Mandatory| Description | 2314| :------- | :--------------------------------------------------- | :--- | :----------------------------------------- | 2315| type | string | Yes | Event type. The event **'deviceChange'** is triggered when the connection status of an audio device is changed.| 2316| callback | Callback<[DeviceChangeAction](#devicechangeaction)\> | Yes | Callback used to return the device change details.| 2317 2318**Example** 2319 2320```ts 2321audioManager.on('deviceChange', (deviceChanged: audio.DeviceChangeAction) => { 2322 console.info(`device change type : ${deviceChanged.type} `); 2323 console.info(`device descriptor size : ${deviceChanged.deviceDescriptors.length} `); 2324 console.info(`device change descriptor : ${deviceChanged.deviceDescriptors[0].deviceRole} `); 2325 console.info(`device change descriptor : ${deviceChanged.deviceDescriptors[0].deviceType} `); 2326}); 2327``` 2328 2329### off('deviceChange')<sup>(deprecated)</sup> 2330 2331off(type: 'deviceChange', callback?: Callback<DeviceChangeAction\>): void 2332 2333Unsubscribes from the audio device change event. This API uses an asynchronous callback to return the result. 2334 2335> **NOTE** 2336> 2337> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [off('deviceChange')](#offdevicechange9) instead. 2338 2339**System capability**: SystemCapability.Multimedia.Audio.Device 2340 2341**Parameters** 2342 2343| Name | Type | Mandatory| Description | 2344| -------- | --------------------------------------------------- | ---- | ------------------------------------------ | 2345| type | string | Yes | Event type. The event **'deviceChange'** is triggered when the connection status of an audio device is changed.| 2346| callback | Callback<[DeviceChangeAction](#devicechangeaction)> | No | Callback used to return the device change details.| 2347 2348**Example** 2349 2350```ts 2351// Cancel all subscriptions to the event. 2352audioManager.off('deviceChange'); 2353 2354// For the same event, if the callback parameter passed to the off API is the same as that passed to the on API, the off API cancels the subscription registered with the specified callback parameter. 2355let deviceChangeCallback = (deviceChanged: audio.DeviceChangeAction) => { 2356 console.info(`device change type : ${deviceChanged.type} `); 2357 console.info(`device descriptor size : ${deviceChanged.deviceDescriptors.length} `); 2358 console.info(`device change descriptor : ${deviceChanged.deviceDescriptors[0].deviceRole} `); 2359 console.info(`device change descriptor : ${deviceChanged.deviceDescriptors[0].deviceType} `); 2360}; 2361 2362audioManager.on('deviceChange', deviceChangeCallback); 2363 2364audioManager.off('deviceChange', deviceChangeCallback); 2365``` 2366 2367### on('interrupt')<sup>(deprecated)</sup> 2368 2369on(type: 'interrupt', interrupt: AudioInterrupt, callback: Callback\<InterruptAction>): void 2370 2371Subscribes to the audio interruption event, which is triggered when the audio focus is changed. This API uses an asynchronous callback to return the result. 2372 2373Same as [on('audioInterrupt')](#onaudiointerrupt9), this API is used to listen for focus is changed. However, this API is used in scenarios without audio streams (no AudioRenderer instance is created), such as frequency modulation (FM) and voice wakeup. 2374 2375> **NOTE** 2376> 2377> This API is supported since API version 7 and deprecated since API version 11. You are advised to use [on('audioInterrupt')](#onaudiointerrupt10) instead. 2378 2379**System capability**: SystemCapability.Multimedia.Audio.Renderer 2380 2381**Parameters** 2382 2383| Name | Type | Mandatory| Description | 2384| --------- |---------------------------------------------------------| ---- | ------------------------------------------------------------ | 2385| type | string | Yes | Event type. The event **'interrupt'** is triggered when the audio focus is changed.| 2386| interrupt | [AudioInterrupt](#audiointerruptdeprecated) | Yes | Audio interruption event type. | 2387| callback | Callback<[InterruptAction](#interruptactiondeprecated)> | Yes | Callback used to return the event information.| 2388 2389**Example** 2390 2391```ts 2392import { audio } from '@kit.AudioKit'; 2393 2394let interAudioInterrupt: audio.AudioInterrupt = { 2395 streamUsage:2, 2396 contentType:0, 2397 pauseWhenDucked:true 2398}; 2399 2400audioManager.on('interrupt', interAudioInterrupt, (interruptAction: audio.InterruptAction) => { 2401 if (interruptAction.actionType === 0) { 2402 console.info('An event to gain the audio focus starts.'); 2403 console.info(`Focus gain event: ${interruptAction} `); 2404 } 2405 if (interruptAction.actionType === 1) { 2406 console.info('An audio interruption event starts.'); 2407 console.info(`Audio interruption event: ${interruptAction} `); 2408 } 2409}); 2410``` 2411 2412### off('interrupt')<sup>(deprecated)</sup> 2413 2414off(type: 'interrupt', interrupt: AudioInterrupt, callback?: Callback\<InterruptAction>): void 2415 2416Unsubscribes from the audio interruption event. This API uses an asynchronous callback to return the result. 2417 2418> **NOTE** 2419> 2420> This API is supported since API version 7 and deprecated since API version 11. You are advised to use [off('audioInterrupt')](#offaudiointerrupt10) instead. 2421 2422**System capability**: SystemCapability.Multimedia.Audio.Renderer 2423 2424**Parameters** 2425 2426| Name | Type | Mandatory| Description | 2427| --------- |---------------------------------------------------------| ---- | ------------------------------------------------------------ | 2428| type | string | Yes | Event type. The event **'interrupt'** is triggered when the audio focus is changed.| 2429| interrupt | [AudioInterrupt](#audiointerruptdeprecated) | Yes | Audio interruption event type. | 2430| callback | Callback<[InterruptAction](#interruptactiondeprecated)> | No | Callback used to return the event information.| 2431 2432**Example** 2433 2434```ts 2435import { audio } from '@kit.AudioKit'; 2436 2437let interAudioInterrupt: audio.AudioInterrupt = { 2438 streamUsage:2, 2439 contentType:0, 2440 pauseWhenDucked:true 2441}; 2442 2443// Cancel all subscriptions to the event. 2444audioManager.off('interrupt', interAudioInterrupt); 2445 2446// For the same event, if the callback parameter passed to the off API is the same as that passed to the on API, the off API cancels the subscription registered with the specified callback parameter. 2447let interruptCallback = (interruptAction: audio.InterruptAction) => { 2448 if (interruptAction.actionType === 0) { 2449 console.info('An event to gain the audio focus starts.'); 2450 console.info(`Focus gain event: ${interruptAction} `); 2451 } 2452 if (interruptAction.actionType === 1) { 2453 console.info('An audio interruption event starts.'); 2454 console.info(`Audio interruption event: ${interruptAction} `); 2455 } 2456}; 2457 2458audioManager.on('interrupt', interAudioInterrupt, interruptCallback); 2459 2460audioManager.off('interrupt', interAudioInterrupt, interruptCallback); 2461``` 2462 2463## AudioVolumeManager<sup>9+</sup> 2464 2465Implements audio volume management. 2466 2467Before calling any API in AudioVolumeManager, you must use [getVolumeManager](#getvolumemanager9) to create an AudioVolumeManager instance. 2468 2469### getVolumeGroupManager<sup>9+</sup> 2470 2471getVolumeGroupManager(groupId: number, callback: AsyncCallback<AudioVolumeGroupManager\>\): void 2472 2473Obtains the volume group manager. This API uses an asynchronous callback to return the result. 2474 2475**System capability**: SystemCapability.Multimedia.Audio.Volume 2476 2477**Parameters** 2478 2479| Name | Type | Mandatory| Description | 2480| ---------- | ------------------------------------------------------------ | ---- |-----------------------------------------------------------| 2481| groupId | number | Yes | Volume group ID. The default value is **DEFAULT_VOLUME_GROUP_ID**. | 2482| callback | AsyncCallback<[AudioVolumeGroupManager](#audiovolumegroupmanager9)> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the volume group manager obtained; otherwise, **err** is an error object.| 2483 2484**Example** 2485 2486```ts 2487import { BusinessError } from '@kit.BasicServicesKit'; 2488 2489let groupId: number = audio.DEFAULT_VOLUME_GROUP_ID; 2490 2491audioVolumeManager.getVolumeGroupManager(groupId, (err: BusinessError, value: audio.AudioVolumeGroupManager) => { 2492 if (err) { 2493 console.error(`Failed to obtain the volume group infos list. ${err}`); 2494 return; 2495 } 2496 console.info('Callback invoked to indicate that the volume group infos list is obtained.'); 2497}); 2498 2499``` 2500 2501### getVolumeGroupManager<sup>9+</sup> 2502 2503getVolumeGroupManager(groupId: number\): Promise<AudioVolumeGroupManager\> 2504 2505Obtains the volume group manager. This API uses a promise to return the result. 2506 2507**System capability**: SystemCapability.Multimedia.Audio.Volume 2508 2509**Parameters** 2510 2511| Name | Type | Mandatory| Description | 2512| ---------- | ---------------------------------------- | ---- |----------------------------------| 2513| groupId | number | Yes | Volume group ID. The default value is **DEFAULT_VOLUME_GROUP_ID**.| 2514 2515**Return value** 2516 2517| Type | Description | 2518| ------------------- | ----------------------------- | 2519| Promise< [AudioVolumeGroupManager](#audiovolumegroupmanager9) > | Promise used to return the volume group manager.| 2520 2521**Example** 2522 2523```ts 2524import { audio } from '@kit.AudioKit'; 2525 2526let groupId: number = audio.DEFAULT_VOLUME_GROUP_ID; 2527let audioVolumeGroupManager: audio.AudioVolumeGroupManager | undefined = undefined; 2528 2529async function getVolumeGroupManager(){ 2530 audioVolumeGroupManager = await audioVolumeManager.getVolumeGroupManager(groupId); 2531 console.info('Promise returned to indicate that the volume group infos list is obtained.'); 2532} 2533``` 2534 2535### getVolumeGroupManagerSync<sup>10+</sup> 2536 2537getVolumeGroupManagerSync(groupId: number\): AudioVolumeGroupManager 2538 2539Obtains the volume group manager. This API returns the result synchronously. 2540 2541**System capability**: SystemCapability.Multimedia.Audio.Volume 2542 2543**Parameters** 2544 2545| Name | Type | Mandatory| Description | 2546| ---------- | ---------------------------------------- | ---- |----------------------------------| 2547| groupId | number | Yes | Volume group ID. The default value is **DEFAULT_VOLUME_GROUP_ID**.| 2548 2549**Return value** 2550 2551| Type | Description | 2552| ------------------- | ----------------------------- | 2553| [AudioVolumeGroupManager](#audiovolumegroupmanager9) | Volume group manager.| 2554 2555**Error codes** 2556 2557For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 2558 2559| ID| Error Message| 2560| ------- | --------------------------------------------| 2561| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 2562| 6800101 | Parameter verification failed. | 2563 2564**Example** 2565 2566```ts 2567import { BusinessError } from '@kit.BasicServicesKit'; 2568 2569try { 2570 let audioVolumeGroupManager: audio.AudioVolumeGroupManager = audioVolumeManager.getVolumeGroupManagerSync(audio.DEFAULT_VOLUME_GROUP_ID); 2571 console.info(`Get audioVolumeGroupManager success.`); 2572} catch (err) { 2573 let error = err as BusinessError; 2574 console.error(`Failed to get audioVolumeGroupManager, error: ${error}`); 2575} 2576``` 2577 2578### getAppVolumePercentage<sup>19+</sup> 2579 2580getAppVolumePercentage(): Promise<number\> 2581 2582Obtains the volume of the application. This API uses a promise to return the result. 2583 2584**System capability**: SystemCapability.Multimedia.Audio.Volume 2585 2586**Return value** 2587 2588| Type | Description | 2589| ------------------- |--------------------| 2590| Promise<number> | Promise used to return the application volume (ranging from 0 to 100).| 2591 2592**Example** 2593 2594```ts 2595import { audio } from '@kit.AudioKit'; 2596 2597audioVolumeManager.getAppVolumePercentage().then((value: number) => { 2598 console.info(`app volume is ${value}.`); 2599}); 2600``` 2601 2602### setAppVolumePercentage<sup>19+</sup> 2603 2604setAppVolumePercentage(volume: number\): Promise<void\> 2605 2606Sets the volume for the application. This API uses a promise to return the result. 2607 2608**System capability**: SystemCapability.Multimedia.Audio.Volume 2609 2610**Parameters** 2611 2612| Name | Type | Mandatory| Description | 2613| ---------- | ---------------------------------------- | ---- |----------| 2614| volume | number | Yes | Volume to set.| 2615 2616**Return value** 2617 2618| Type | Description | 2619| ------------------- | ------------------------------- | 2620| Promise<void> | Promise that returns no value.| 2621 2622**Error codes** 2623 2624For details about the error codes, see [Audio Error Codes](errorcode-audio.md). 2625 2626| ID| Error Message| 2627| ------- | --------------------------------------------| 2628| 6800101 | Parameter verification failed.| 2629| 6800301 | Crash or blocking occurs in system process. | 2630 2631**Example** 2632 2633```ts 2634import { audio } from '@kit.AudioKit'; 2635 2636audioVolumeManager.setAppVolumePercentage(20).then(() => { 2637 console.info(`set app volume success.`); 2638}); 2639``` 2640 2641### on('volumeChange')<sup>9+</sup> 2642 2643on(type: 'volumeChange', callback: Callback\<VolumeEvent>): void 2644 2645Subscribes to the system volume change event, which is triggered when the system volume is changed. This API uses an asynchronous callback to return the result. 2646 2647**System capability**: SystemCapability.Multimedia.Audio.Volume 2648 2649**Parameters** 2650 2651| Name | Type | Mandatory| Description | 2652| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | 2653| type | string | Yes | Event type. The event **'volumeChange'** is triggered when the system volume is changed.| 2654| callback | Callback<[VolumeEvent](#volumeevent9)> | Yes | Callback used to return the changed volume.| 2655 2656**Error codes** 2657 2658For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 2659 2660| ID| Error Message| 2661| ------- | --------------------------------------------| 2662| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 2663| 6800101 | Parameter verification failed. | 2664 2665**Example** 2666 2667```ts 2668audioVolumeManager.on('volumeChange', (volumeEvent: audio.VolumeEvent) => { 2669 console.info(`VolumeType of stream: ${volumeEvent.volumeType} `); 2670 console.info(`Volume level: ${volumeEvent.volume} `); 2671 console.info(`Whether to updateUI: ${volumeEvent.updateUi} `); 2672}); 2673``` 2674 2675### off('volumeChange')<sup>12+</sup> 2676 2677off(type: 'volumeChange', callback?: Callback\<VolumeEvent>): void 2678 2679Unsubscribes from the system volume change event. This API uses an asynchronous callback to return the result. 2680 2681**System capability**: SystemCapability.Multimedia.Audio.Volume 2682 2683**Parameters** 2684 2685| Name | Type | Mandatory| Description | 2686| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | 2687| type | string | Yes | Event type. The event **'volumeChange'** is triggered when the system volume is changed.| 2688| callback | Callback<[VolumeEvent](#volumeevent9)> | No | Callback used to return the changed volume.| 2689 2690**Error codes** 2691 2692For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 2693 2694| ID| Error Message| 2695| ------- | --------------------------------------------| 2696| 401 | Parameter error. Possible causes: 1.Mandatory parameters missing; 2.Incorrect parameter types. | 2697| 6800101 | Parameter verification failed. | 2698 2699**Example** 2700 2701```ts 2702// Cancel all subscriptions to the event. 2703audioVolumeManager.off('volumeChange'); 2704 2705// For the same event, if the callback parameter passed to the off API is the same as that passed to the on API, the off API cancels the subscription registered with the specified callback parameter. 2706let volumeChangeCallback = (volumeEvent: audio.VolumeEvent) => { 2707 console.info(`VolumeType of stream: ${volumeEvent.volumeType} `); 2708 console.info(`Volume level: ${volumeEvent.volume} `); 2709 console.info(`Whether to updateUI: ${volumeEvent.updateUi} `); 2710}; 2711 2712audioVolumeManager.on('volumeChange', volumeChangeCallback); 2713 2714audioVolumeManager.off('volumeChange', volumeChangeCallback); 2715``` 2716 2717### on('appVolumeChange')<sup>19+</sup> 2718 2719on(type: 'appVolumeChange', callback: Callback\<VolumeEvent>): void 2720 2721Subscribes to the application-level volume change event of the application. This API uses an asynchronous callback to return the result. 2722 2723**System capability**: SystemCapability.Multimedia.Audio.Volume 2724 2725**Parameters** 2726 2727| Name | Type | Mandatory| Description | 2728| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | 2729| type | string | Yes | Event type. The event **'appVolumeChange'** is triggered when the application-level volume is changed.| 2730| callback | Callback<[VolumeEvent](#volumeevent9)> | Yes | Callback used to return the changed volume.| 2731 2732**Error codes** 2733 2734For details about the error codes, see [Audio Error Codes](errorcode-audio.md). 2735 2736| ID| Error Message| 2737| ------- | --------------------------------------------| 2738| 6800101 | Parameter verification failed. | 2739 2740**Example** 2741 2742```ts 2743audioVolumeManager.on('appVolumeChange', (volumeEvent: audio.VolumeEvent) => { 2744 console.info(`VolumeType of stream: ${volumeEvent.volumeType} `); 2745 console.info(`Volume level: ${volumeEvent.volume} `); 2746 console.info(`Whether to updateUI: ${volumeEvent.updateUi} `); 2747}); 2748``` 2749 2750### off('appVolumeChange')<sup>19+</sup> 2751 2752off(type: 'appVolumeChange', callback?: Callback\<VolumeEvent>): void 2753 2754Unsubscribes from the application-level volume change event of the application. This API uses an asynchronous callback to return the result. 2755 2756**System capability**: SystemCapability.Multimedia.Audio.Volume 2757 2758**Parameters** 2759 2760| Name | Type | Mandatory| Description | 2761| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | 2762| type | string | Yes | Event type. The event **'appVolumeChange'** is triggered when the application-level volume is changed.| 2763| callback | Callback<[VolumeEvent](#volumeevent9)> | No | Callback used to return the changed volume.| 2764 2765**Error codes** 2766 2767For details about the error codes, see [Audio Error Codes](errorcode-audio.md). 2768 2769| ID| Error Message| 2770| ------- | --------------------------------------------| 2771| 6800101 | Parameter verification failed. | 2772 2773**Example** 2774 2775```ts 2776// Cancel all subscriptions to the event. 2777audioVolumeManager.off('appVolumeChange'); 2778 2779// For the same event, if the callback parameter passed to the off API is the same as that passed to the on API, the off API cancels the subscription registered with the specified callback parameter. 2780let appVolumeChangeCallback = (volumeEvent: audio.VolumeEvent) => { 2781 console.info(`VolumeType of stream: ${volumeEvent.volumeType} `); 2782 console.info(`Volume level: ${volumeEvent.volume} `); 2783 console.info(`Whether to updateUI: ${volumeEvent.updateUi} `); 2784}; 2785 2786audioVolumeManager.on('appVolumeChange', appVolumeChangeCallback); 2787 2788audioVolumeManager.off('appVolumeChange', appVolumeChangeCallback); 2789``` 2790 2791### on('activeVolumeTypeChange')<sup>20+</sup> 2792 2793on(type: 'activeVolumeTypeChange', callback: Callback\<AudioVolumeType>): void 2794 2795Subscribes to the active volume type change event. This API uses an asynchronous callback to return the result. 2796 2797**System capability**: SystemCapability.Multimedia.Audio.Volume 2798 2799**Parameters** 2800 2801| Name | Type | Mandatory| Description | 2802| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | 2803| type | string | Yes | Event type. The event **'activeVolumeTypeChange'** is triggered when the active volume type changes.| 2804| callback | Callback\<[AudioVolumeType](#audiovolumetype)> | Yes | Callback used to return the changed active volume type.| 2805 2806**Error codes** 2807 2808For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 2809 2810| ID| Error Message| 2811| ------- | --------------------------------------------| 2812| 202 | Not system App. | 2813| 6800101 | Parameter verification failed. | 2814 2815**Example** 2816 2817```ts 2818audioVolumeManager.on('activeVolumeTypeChange', (volumeType: audio.AudioVolumeType) => { 2819 console.info(`VolumeType of stream: ${volumeType} `); 2820}); 2821``` 2822 2823### off('activeVolumeTypeChange')<sup>20+</sup> 2824 2825off(type: 'activeVolumeTypeChange', callback?: Callback\<AudioVolumeType>): void 2826 2827Unsubscribes from the active volume type change event. This API uses an asynchronous callback to return the result. 2828 2829**System capability**: SystemCapability.Multimedia.Audio.Volume 2830 2831**Parameters** 2832 2833| Name | Type | Mandatory| Description | 2834| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | 2835| type | string | Yes | Event type. The event **'activeVolumeTypeChange'** is triggered when the active volume type changes.| 2836| callback | Callback\<[AudioVolumeType](#audiovolumetype)> | No | Callback used to return the changed active volume type.| 2837 2838**Error codes** 2839 2840For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 2841 2842| ID| Error Message| 2843| ------- | --------------------------------------------| 2844| 202 | Not system App. | 2845| 6800101 | Parameter verification failed. | 2846 2847**Example** 2848 2849```ts 2850// Cancel all subscriptions to the event. 2851audioVolumeManager.off('activeVolumeTypeChange'); 2852 2853// For the same event, if the callback parameter passed to the off API is the same as that passed to the on API, the off API cancels the subscription registered with the specified callback parameter. 2854let activeVolumeTypeChangeCallback = (volumeType: audio.AudioVolumeType) => { 2855 console.info(`VolumeType of stream: ${volumeType} `); 2856}; 2857 2858audioVolumeManager.on('activeVolumeTypeChange', activeVolumeTypeChangeCallback); 2859 2860audioVolumeManager.off('activeVolumeTypeChange', activeVolumeTypeChangeCallback); 2861``` 2862 2863## AudioVolumeGroupManager<sup>9+</sup> 2864 2865Manages the volume of an audio group. 2866 2867Before calling any API in AudioVolumeGroupManager, you must use [getVolumeGroupManager](#getvolumegroupmanager9) to obtain an AudioVolumeGroupManager instance. 2868 2869### getVolume<sup>9+</sup> 2870 2871getVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void 2872 2873Obtains the volume of a stream. This API uses an asynchronous callback to return the result. 2874 2875**System capability**: SystemCapability.Multimedia.Audio.Volume 2876 2877**Parameters** 2878 2879| Name | Type | Mandatory| Description | 2880| ---------- | ----------------------------------- | ---- | ------------------ | 2881| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | 2882| callback | AsyncCallback<number> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the stream volume obtained; otherwise, **err** is an error object. The volume range of a specified stream can be obtained by calling [getMinVolume](#getminvolume9) and [getMaxVolume](#getmaxvolume9).| 2883 2884**Example** 2885 2886```ts 2887import { BusinessError } from '@kit.BasicServicesKit'; 2888 2889audioVolumeGroupManager.getVolume(audio.AudioVolumeType.MEDIA, (err: BusinessError, value: number) => { 2890 if (err) { 2891 console.error(`Failed to obtain the volume. ${err}`); 2892 return; 2893 } 2894 console.info('Callback invoked to indicate that the volume is obtained.'); 2895}); 2896``` 2897 2898### getVolume<sup>9+</sup> 2899 2900getVolume(volumeType: AudioVolumeType): Promise<number> 2901 2902Obtains the volume of a stream. This API uses a promise to return the result. 2903 2904**System capability**: SystemCapability.Multimedia.Audio.Volume 2905 2906**Parameters** 2907 2908| Name | Type | Mandatory| Description | 2909| ---------- | ----------------------------------- | ---- | ------------ | 2910| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| 2911 2912**Return value** 2913 2914| Type | Description | 2915| --------------------- | ------------------------- | 2916| Promise<number> | Promise used to return the volume of the stream. The volume range of a specified stream can be obtained by calling [getMinVolume](#getminvolume9) and [getMaxVolume](#getmaxvolume9).| 2917 2918**Example** 2919 2920```ts 2921audioVolumeGroupManager.getVolume(audio.AudioVolumeType.MEDIA).then((value: number) => { 2922 console.info(`Promise returned to indicate that the volume is obtained ${value}.`); 2923}); 2924``` 2925 2926### getVolumeSync<sup>10+</sup> 2927 2928getVolumeSync(volumeType: AudioVolumeType): number 2929 2930Obtains the volume of a stream. This API returns the result synchronously. 2931 2932**System capability**: SystemCapability.Multimedia.Audio.Volume 2933 2934**Parameters** 2935 2936| Name | Type | Mandatory| Description | 2937| ---------- | ----------------------------------- | ---- | ------------ | 2938| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| 2939 2940**Return value** 2941 2942| Type | Description | 2943| --------------------- | ------------------------- | 2944| number | Volume of the stream. The volume range of a specified stream can be obtained by calling [getMinVolume](#getminvolume9) and [getMaxVolume](#getmaxvolume9).| 2945 2946**Error codes** 2947 2948For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 2949 2950| ID| Error Message| 2951| ------- | --------------------------------------------| 2952| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 2953| 6800101 | Parameter verification failed. | 2954 2955**Example** 2956 2957```ts 2958import { BusinessError } from '@kit.BasicServicesKit'; 2959 2960try { 2961 let value: number = audioVolumeGroupManager.getVolumeSync(audio.AudioVolumeType.MEDIA); 2962 console.info(`Indicate that the volume is obtained ${value}.`); 2963} catch (err) { 2964 let error = err as BusinessError; 2965 console.error(`Failed to obtain the volume, error ${error}.`); 2966} 2967``` 2968 2969### getMinVolume<sup>9+</sup> 2970 2971getMinVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void 2972 2973Obtains the minimum volume allowed for a stream. This API uses an asynchronous callback to return the result. 2974 2975**System capability**: SystemCapability.Multimedia.Audio.Volume 2976 2977**Parameters** 2978 2979| Name | Type | Mandatory| Description | 2980| ---------- | ----------------------------------- | ---- | ------------------ | 2981| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | 2982| callback | AsyncCallback<number> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the minimum stream volume obtained; otherwise, **err** is an error object.| 2983 2984**Example** 2985 2986```ts 2987import { BusinessError } from '@kit.BasicServicesKit'; 2988 2989audioVolumeGroupManager.getMinVolume(audio.AudioVolumeType.MEDIA, (err: BusinessError, value: number) => { 2990 if (err) { 2991 console.error(`Failed to obtain the minimum volume. ${err}`); 2992 return; 2993 } 2994 console.info(`Callback invoked to indicate that the minimum volume is obtained. ${value}`); 2995}); 2996``` 2997 2998### getMinVolume<sup>9+</sup> 2999 3000getMinVolume(volumeType: AudioVolumeType): Promise<number> 3001 3002Obtains the minimum volume allowed for a stream. This API uses a promise to return the result. 3003 3004**System capability**: SystemCapability.Multimedia.Audio.Volume 3005 3006**Parameters** 3007 3008| Name | Type | Mandatory| Description | 3009| ---------- | ----------------------------------- | ---- | ------------ | 3010| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| 3011 3012**Return value** 3013 3014| Type | Description | 3015| --------------------- | ------------------------- | 3016| Promise<number> | Promise used to return the minimum volume.| 3017 3018**Example** 3019 3020```ts 3021audioVolumeGroupManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value: number) => { 3022 console.info(`Promised returned to indicate that the minimum volume is obtained ${value}.`); 3023}); 3024``` 3025 3026### getMinVolumeSync<sup>10+</sup> 3027 3028getMinVolumeSync(volumeType: AudioVolumeType): number 3029 3030Obtains the minimum volume allowed for a stream. This API returns the result synchronously. 3031 3032**System capability**: SystemCapability.Multimedia.Audio.Volume 3033 3034**Parameters** 3035 3036| Name | Type | Mandatory| Description | 3037| ---------- | ----------------------------------- | ---- | ------------ | 3038| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| 3039 3040**Return value** 3041 3042| Type | Description | 3043| --------------------- | ------------------------- | 3044| number | Minimum volume.| 3045 3046**Error codes** 3047 3048For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 3049 3050| ID| Error Message| 3051| ------- | --------------------------------------------| 3052| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 3053| 6800101 | Parameter verification failed. | 3054 3055**Example** 3056 3057```ts 3058import { BusinessError } from '@kit.BasicServicesKit'; 3059 3060try { 3061 let value: number = audioVolumeGroupManager.getMinVolumeSync(audio.AudioVolumeType.MEDIA); 3062 console.info(`Indicate that the minimum volume is obtained ${value}.`); 3063} catch (err) { 3064 let error = err as BusinessError; 3065 console.error(`Failed to obtain the minimum volume, error ${error}.`); 3066} 3067``` 3068 3069### getMaxVolume<sup>9+</sup> 3070 3071getMaxVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void 3072 3073Obtains the maximum volume allowed for a stream. This API uses an asynchronous callback to return the result. 3074 3075**System capability**: SystemCapability.Multimedia.Audio.Volume 3076 3077**Parameters** 3078 3079| Name | Type | Mandatory| Description | 3080| ---------- | ----------------------------------- | ---- | ---------------------- | 3081| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | 3082| callback | AsyncCallback<number> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the maximum stream volume obtained; otherwise, **err** is an error object.| 3083 3084**Example** 3085 3086```ts 3087import { BusinessError } from '@kit.BasicServicesKit'; 3088 3089audioVolumeGroupManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err: BusinessError, value: number) => { 3090 if (err) { 3091 console.error(`Failed to obtain the maximum volume. ${err}`); 3092 return; 3093 } 3094 console.info(`Callback invoked to indicate that the maximum volume is obtained. ${value}`); 3095}); 3096``` 3097 3098### getMaxVolume<sup>9+</sup> 3099 3100getMaxVolume(volumeType: AudioVolumeType): Promise<number> 3101 3102Obtains the maximum volume allowed for a stream. This API uses a promise to return the result. 3103 3104**System capability**: SystemCapability.Multimedia.Audio.Volume 3105 3106**Parameters** 3107 3108| Name | Type | Mandatory| Description | 3109| ---------- | ----------------------------------- | ---- | ------------ | 3110| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| 3111 3112**Return value** 3113 3114| Type | Description | 3115| --------------------- | ----------------------------- | 3116| Promise<number> | Promise used to return the maximum volume.| 3117 3118**Example** 3119 3120```ts 3121audioVolumeGroupManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((data: number) => { 3122 console.info('Promised returned to indicate that the maximum volume is obtained.'); 3123}); 3124``` 3125 3126### getMaxVolumeSync<sup>10+</sup> 3127 3128getMaxVolumeSync(volumeType: AudioVolumeType): number 3129 3130Obtains the maximum volume allowed for a stream. This API returns the result synchronously. 3131 3132**System capability**: SystemCapability.Multimedia.Audio.Volume 3133 3134**Parameters** 3135 3136| Name | Type | Mandatory| Description | 3137| ---------- | ----------------------------------- | ---- | ------------ | 3138| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| 3139 3140**Return value** 3141 3142| Type | Description | 3143| --------------------- | ----------------------------- | 3144| number | Maximum volume.| 3145 3146**Error codes** 3147 3148For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 3149 3150| ID| Error Message| 3151| ------- | --------------------------------------------| 3152| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 3153| 6800101 | Parameter verification failed. | 3154 3155**Example** 3156 3157```ts 3158import { BusinessError } from '@kit.BasicServicesKit'; 3159 3160try { 3161 let value: number = audioVolumeGroupManager.getMaxVolumeSync(audio.AudioVolumeType.MEDIA); 3162 console.info(`Indicate that the maximum volume is obtained. ${value}`); 3163} catch (err) { 3164 let error = err as BusinessError; 3165 console.error(`Failed to obtain the maximum volume, error ${error}.`); 3166} 3167``` 3168 3169### isMute<sup>9+</sup> 3170 3171isMute(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void 3172 3173Checks whether a stream is muted. This API uses an asynchronous callback to return the result. 3174 3175**System capability**: SystemCapability.Multimedia.Audio.Volume 3176 3177**Parameters** 3178 3179| Name | Type | Mandatory| Description | 3180| ---------- | ----------------------------------- | ---- | ----------------------------------------------- | 3181| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | 3182| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is **true** if the stream is muted or **false** if not muted; otherwise, **err** is an error object.| 3183 3184**Example** 3185 3186```ts 3187import { BusinessError } from '@kit.BasicServicesKit'; 3188 3189audioVolumeGroupManager.isMute(audio.AudioVolumeType.MEDIA, (err: BusinessError, value: boolean) => { 3190 if (err) { 3191 console.error(`Failed to obtain the mute status. ${err}`); 3192 return; 3193 } 3194 console.info(`Callback invoked to indicate that the mute status of the stream is obtained ${value}.`); 3195}); 3196``` 3197 3198### isMute<sup>9+</sup> 3199 3200isMute(volumeType: AudioVolumeType): Promise<boolean> 3201 3202Checks whether a stream is muted. This API uses a promise to return the result. 3203 3204**System capability**: SystemCapability.Multimedia.Audio.Volume 3205 3206**Parameters** 3207 3208| Name | Type | Mandatory| Description | 3209| ---------- | ----------------------------------- | ---- | ------------ | 3210| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| 3211 3212**Return value** 3213 3214| Type | Description | 3215| ---------------------- | ------------------------------------------------------ | 3216| Promise<boolean> | Promise used to return the result. The value **true** means that the stream is muted, and **false** means the opposite.| 3217 3218**Example** 3219 3220```ts 3221audioVolumeGroupManager.isMute(audio.AudioVolumeType.MEDIA).then((value: boolean) => { 3222 console.info(`Promise returned to indicate that the mute status of the stream is obtained ${value}.`); 3223}); 3224``` 3225 3226### isMuteSync<sup>10+</sup> 3227 3228isMuteSync(volumeType: AudioVolumeType): boolean 3229 3230Checks whether a stream is muted. This API returns the result synchronously. 3231 3232**System capability**: SystemCapability.Multimedia.Audio.Volume 3233 3234**Parameters** 3235 3236| Name | Type | Mandatory| Description | 3237| ---------- | ----------------------------------- | ---- | ------------ | 3238| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| 3239 3240**Return value** 3241 3242| Type | Description | 3243| ---------------------- | ------------------------------------------------------ | 3244| boolean | Check result. The value **true** means that the stream is muted, and **false** means the opposite.| 3245 3246**Error codes** 3247 3248For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 3249 3250| ID| Error Message| 3251| ------- | --------------------------------------------| 3252| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 3253| 6800101 | Parameter verification failed. | 3254 3255**Example** 3256 3257```ts 3258import { BusinessError } from '@kit.BasicServicesKit'; 3259 3260try { 3261 let value: boolean = audioVolumeGroupManager.isMuteSync(audio.AudioVolumeType.MEDIA); 3262 console.info(`Indicate that the mute status of the stream is obtained ${value}.`); 3263} catch (err) { 3264 let error = err as BusinessError; 3265 console.error(`Failed to obtain the mute status of the stream, error ${error}.`); 3266} 3267``` 3268 3269### getRingerMode<sup>9+</sup> 3270 3271getRingerMode(callback: AsyncCallback<AudioRingMode>): void 3272 3273Obtains the ringer mode. This API uses an asynchronous callback to return the result. 3274 3275**System capability**: SystemCapability.Multimedia.Audio.Volume 3276 3277**Parameters** 3278 3279| Name | Type | Mandatory| Description | 3280| -------- | ---------------------------------------------------- | ---- | ------------------------ | 3281| callback | AsyncCallback<[AudioRingMode](#audioringmode)> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the ringer mode obtained; otherwise, **err** is an error object.| 3282 3283**Example** 3284 3285```ts 3286import { BusinessError } from '@kit.BasicServicesKit'; 3287 3288audioVolumeGroupManager.getRingerMode((err: BusinessError, value: audio.AudioRingMode) => { 3289 if (err) { 3290 console.error(`Failed to obtain the ringer mode. ${err}`); 3291 return; 3292 } 3293 console.info(`Callback invoked to indicate that the ringer mode is obtained ${value}.`); 3294}); 3295``` 3296 3297### getRingerMode<sup>9+</sup> 3298 3299getRingerMode(): Promise<AudioRingMode> 3300 3301Obtains the ringer mode. This API uses a promise to return the result. 3302 3303**System capability**: SystemCapability.Multimedia.Audio.Volume 3304 3305**Return value** 3306 3307| Type | Description | 3308| ---------------------------------------------- | ------------------------------- | 3309| Promise<[AudioRingMode](#audioringmode)> | Promise used to return the ringer mode.| 3310 3311**Example** 3312 3313```ts 3314audioVolumeGroupManager.getRingerMode().then((value: audio.AudioRingMode) => { 3315 console.info(`Promise returned to indicate that the ringer mode is obtained ${value}.`); 3316}); 3317``` 3318 3319### getRingerModeSync<sup>10+</sup> 3320 3321getRingerModeSync(): AudioRingMode 3322 3323Obtains the ringer mode. This API returns the result synchronously. 3324 3325**System capability**: SystemCapability.Multimedia.Audio.Volume 3326 3327**Return value** 3328 3329| Type | Description | 3330| ---------------------------------------------- | ------------------------------- | 3331| [AudioRingMode](#audioringmode) | Ringer mode.| 3332 3333**Example** 3334 3335```ts 3336import { BusinessError } from '@kit.BasicServicesKit'; 3337 3338try { 3339 let value: audio.AudioRingMode = audioVolumeGroupManager.getRingerModeSync(); 3340 console.info(`Indicate that the ringer mode is obtained ${value}.`); 3341} catch (err) { 3342 let error = err as BusinessError; 3343 console.error(`Failed to obtain the ringer mode, error ${error}.`); 3344} 3345``` 3346 3347### on('ringerModeChange')<sup>9+</sup> 3348 3349on(type: 'ringerModeChange', callback: Callback\<AudioRingMode>): void 3350 3351Subscribes to the ringer mode change event, which is triggered when [audioringmode](#audioringmode) is changed. This API uses an asynchronous callback to return the result. 3352 3353**System capability**: SystemCapability.Multimedia.Audio.Volume 3354 3355**Parameters** 3356 3357| Name | Type | Mandatory| Description | 3358| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | 3359| type | string | Yes | Event type. The event **'ringerModeChange'** is triggered when the ringer mode is changed.| 3360| callback | Callback<[AudioRingMode](#audioringmode)> | Yes | Callback used to return the changed ringer mode.| 3361 3362**Error codes** 3363 3364For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 3365 3366| ID| Error Message| 3367| ------- | --------------------------------------------| 3368| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 3369| 6800101 | Parameter verification failed. | 3370 3371**Example** 3372 3373```ts 3374audioVolumeGroupManager.on('ringerModeChange', (ringerMode: audio.AudioRingMode) => { 3375 console.info(`Updated ringermode: ${ringerMode}`); 3376}); 3377``` 3378 3379### off('ringerModeChange')<sup>18+</sup> 3380 3381off(type: 'ringerModeChange', callback?: Callback<AudioRingMode>): void 3382 3383Subscribes to the ringer mode change event. This API uses an asynchronous callback to return the result. 3384 3385**System capability**: SystemCapability.Multimedia.Audio.Volume 3386 3387**Parameters** 3388 3389| Name | Type | Mandatory| Description | 3390| -------- | -------------------------------------- |----| ------------------------------------------------------------ | 3391| type | string | Yes | Event type. The event **'ringerModeChange'** is triggered when the ringer mode is changed.| 3392| callback |Callback<[AudioRingMode](#audioringmode)> | No | Callback used to return the changed ringer mode.| 3393 3394**Error codes** 3395 3396For details about the error codes, see [Audio Error Codes](errorcode-audio.md). 3397 3398| ID| Error Message| 3399| ------- | --------------------------------------------| 3400| 6800101 | Parameter verification failed. | 3401 3402**Example** 3403 3404```ts 3405// Cancel all subscriptions to the event. 3406audioVolumeGroupManager.off('ringerModeChange'); 3407 3408// For the same event, if the callback parameter passed to the off API is the same as that passed to the on API, the off API cancels the subscription registered with the specified callback parameter. 3409let ringerModeChangeCallback = (ringerMode: audio.AudioRingMode) => { 3410 console.info(`Updated ringermode: ${ringerMode}`); 3411}; 3412 3413audioVolumeGroupManager.on('ringerModeChange', ringerModeChangeCallback); 3414 3415audioVolumeGroupManager.off('ringerModeChange', ringerModeChangeCallback); 3416``` 3417 3418### setMicrophoneMute<sup>(deprecated)</sup> 3419 3420setMicrophoneMute(mute: boolean, callback: AsyncCallback<void>): void 3421 3422Mutes or unmutes the microphone. This API uses an asynchronous callback to return the result. 3423 3424> **NOTE** 3425> 3426> This API is supported since API version 9 and deprecated since API version 11. Its substitute is available only to system applications. 3427 3428**Required permissions**: ohos.permission.MANAGE_AUDIO_CONFIG (available only for system applications) 3429 3430**System capability**: SystemCapability.Multimedia.Audio.Volume 3431 3432**Parameters** 3433 3434| Name | Type | Mandatory| Description | 3435| -------- | ------------------------- | ---- | --------------------------------------------- | 3436| mute | boolean | Yes | Mute status to set. The value **true** means to mute the microphone, and **false** means the opposite.| 3437| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 3438 3439**Example** 3440 3441```ts 3442import { BusinessError } from '@kit.BasicServicesKit'; 3443 3444audioVolumeGroupManager.setMicrophoneMute(true, (err: BusinessError) => { 3445 if (err) { 3446 console.error(`Failed to mute the microphone. ${err}`); 3447 return; 3448 } 3449 console.info('Callback invoked to indicate that the microphone is muted.'); 3450}); 3451``` 3452 3453### setMicrophoneMute<sup>(deprecated)</sup> 3454 3455setMicrophoneMute(mute: boolean): Promise<void> 3456 3457Mutes or unmutes the microphone. This API uses a promise to return the result. 3458 3459> **NOTE** 3460> 3461> This API is supported since API version 9 and deprecated since API version 11. Its substitute is available only to system applications. 3462 3463**Required permissions**: ohos.permission.MANAGE_AUDIO_CONFIG (available only for system applications) 3464 3465**System capability**: SystemCapability.Multimedia.Audio.Volume 3466 3467**Parameters** 3468 3469| Name| Type | Mandatory| Description | 3470| ------ | ------- | ---- | --------------------------------------------- | 3471| mute | boolean | Yes | Mute status to set. The value **true** means to mute the microphone, and **false** means the opposite.| 3472 3473**Return value** 3474 3475| Type | Description | 3476| ------------------- | ------------------------------- | 3477| Promise<void> | Promise that returns no value.| 3478 3479**Example** 3480 3481```ts 3482audioVolumeGroupManager.setMicrophoneMute(true).then(() => { 3483 console.info('Promise returned to indicate that the microphone is muted.'); 3484}); 3485``` 3486 3487### isMicrophoneMute<sup>9+</sup> 3488 3489isMicrophoneMute(callback: AsyncCallback<boolean>): void 3490 3491Checks whether the microphone is muted. This API uses an asynchronous callback to return the result. 3492 3493**System capability**: SystemCapability.Multimedia.Audio.Volume 3494 3495**Parameters** 3496 3497| Name | Type | Mandatory| Description | 3498| -------- | ---------------------------- | ---- | ------------------------------------------------------- | 3499| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is **true** if the microphone is muted or **false** if not muted; otherwise, **err** is an error object.| 3500 3501**Example** 3502 3503```ts 3504import { BusinessError } from '@kit.BasicServicesKit'; 3505 3506audioVolumeGroupManager.isMicrophoneMute((err: BusinessError, value: boolean) => { 3507 if (err) { 3508 console.error(`Failed to obtain the mute status of the microphone. ${err}`); 3509 return; 3510 } 3511 console.info(`Callback invoked to indicate that the mute status of the microphone is obtained ${value}.`); 3512}); 3513``` 3514 3515### isMicrophoneMute<sup>9+</sup> 3516 3517isMicrophoneMute(): Promise<boolean> 3518 3519Checks whether the microphone is muted. This API uses a promise to return the result. 3520 3521**System capability**: SystemCapability.Multimedia.Audio.Volume 3522 3523**Return value** 3524 3525| Type | Description | 3526| ---------------------- | ------------------------------------------------------------ | 3527| Promise<boolean> | Promise used to return the result. The value **true** means that the microphone is muted, and **false** means the opposite.| 3528 3529**Example** 3530 3531```ts 3532audioVolumeGroupManager.isMicrophoneMute().then((value: boolean) => { 3533 console.info(`Promise returned to indicate that the mute status of the microphone is obtained ${value}.`); 3534}); 3535``` 3536 3537### isMicrophoneMuteSync<sup>10+</sup> 3538 3539isMicrophoneMuteSync(): boolean 3540 3541Checks whether the microphone is muted. This API returns the result synchronously. 3542 3543**System capability**: SystemCapability.Multimedia.Audio.Volume 3544 3545**Return value** 3546 3547| Type | Description | 3548| ---------------------- | ------------------------------------------------------------ | 3549| boolean | Check result. The value **true** means that the microphone is muted, and **false** means the opposite.| 3550 3551**Example** 3552 3553```ts 3554import { BusinessError } from '@kit.BasicServicesKit'; 3555 3556try { 3557 let value: boolean = audioVolumeGroupManager.isMicrophoneMuteSync(); 3558 console.info(`Indicate that the mute status of the microphone is obtained ${value}.`); 3559} catch (err) { 3560 let error = err as BusinessError; 3561 console.error(`Failed to obtain the mute status of the microphone, error ${error}.`); 3562} 3563``` 3564 3565### on('micStateChange')<sup>9+</sup> 3566 3567on(type: 'micStateChange', callback: Callback<MicStateChangeEvent>): void 3568 3569Subscribes to the microphone state change event, which is triggered when the microphone state is changed. This API uses an asynchronous callback to return the result. 3570 3571Currently, when multiple AudioManager instances are used in a single process, only the subscription of the last instance takes effect, and the subscription of other instances is overwritten (even if the last instance does not initiate a subscription). Therefore, you are advised to use a single AudioManager instance. 3572 3573**System capability**: SystemCapability.Multimedia.Audio.Volume 3574 3575**Parameters** 3576 3577| Name | Type | Mandatory| Description | 3578| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | 3579| type | string | Yes | Event type. The event **'micStateChange'** is triggered when the microphone state is changed.| 3580| callback | Callback<[MicStateChangeEvent](#micstatechangeevent9)> | Yes | Callback used to return the changed microphone state.| 3581 3582**Error codes** 3583 3584For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 3585 3586| ID| Error Message| 3587| ------- | --------------------------------------------| 3588| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 3589| 6800101 | Parameter verification failed. | 3590 3591**Example** 3592 3593```ts 3594audioVolumeGroupManager.on('micStateChange', (micStateChange: audio.MicStateChangeEvent) => { 3595 console.info(`Current microphone status is: ${micStateChange.mute} `); 3596}); 3597``` 3598 3599### off('micStateChange')<sup>12+</sup> 3600 3601off(type: 'micStateChange', callback?: Callback<MicStateChangeEvent>): void 3602 3603Unsubscribes from the microphone state change event. This API uses an asynchronous callback to return the result. 3604 3605**System capability**: SystemCapability.Multimedia.Audio.Volume 3606 3607**Parameters** 3608 3609| Name | Type | Mandatory| Description | 3610| -------- | -------------------------------------- |----| ------------------------------------------------------------ | 3611| type | string | Yes | Event type. The event **'micStateChange'** is triggered when the microphone state is changed.| 3612| callback | Callback<[MicStateChangeEvent](#micstatechangeevent9)> | No | Callback used to return the changed microphone state.| 3613 3614**Error codes** 3615 3616For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 3617 3618| ID| Error Message| 3619| ------- | --------------------------------------------| 3620| 401 | Parameter error. Possible causes: 1.Mandatory parameters missing; 2.Incorrect parameter types. | 3621| 6800101 | Parameter verification failed. | 3622 3623**Example** 3624 3625```ts 3626// Cancel all subscriptions to the event. 3627audioVolumeGroupManager.off('micStateChange'); 3628 3629// For the same event, if the callback parameter passed to the off API is the same as that passed to the on API, the off API cancels the subscription registered with the specified callback parameter. 3630let micStateChangeCallback = (micStateChange: audio.MicStateChangeEvent) => { 3631 console.info(`Current microphone status is: ${micStateChange.mute} `); 3632}; 3633 3634audioVolumeGroupManager.on('micStateChange', micStateChangeCallback); 3635 3636audioVolumeGroupManager.off('micStateChange', micStateChangeCallback); 3637``` 3638 3639### isVolumeUnadjustable<sup>10+</sup> 3640 3641isVolumeUnadjustable(): boolean 3642 3643Checks whether the fixed volume mode is enabled. When the fixed volume mode is enabled, the volume cannot be adjusted. This API returns the result synchronously. 3644 3645**System capability**: SystemCapability.Multimedia.Audio.Volume 3646 3647**Return value** 3648 3649| Type | Description | 3650| ---------------------- | ------------------------------------------------------ | 3651| boolean | Check result. The value **true** means that the fixed volume mode is enabled, and **false** means the opposite.| 3652 3653**Example** 3654 3655```ts 3656let volumeAdjustSwitch: boolean = audioVolumeGroupManager.isVolumeUnadjustable(); 3657console.info(`Whether it is volume unadjustable: ${volumeAdjustSwitch}.`); 3658``` 3659 3660### getSystemVolumeInDb<sup>10+</sup> 3661 3662getSystemVolumeInDb(volumeType: AudioVolumeType, volumeLevel: number, device: DeviceType, callback: AsyncCallback<number>): void 3663 3664Obtains the volume gain. This API uses an asynchronous callback to return the result. 3665 3666**System capability**: SystemCapability.Multimedia.Audio.Volume 3667 3668**Parameters** 3669 3670| Name | Type | Mandatory| Description | 3671| ---------- | ----------------------------------- | ---- | -------------------------------------------------------- | 3672| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | 3673| volumeLevel | number | Yes | Volume level. | 3674| device | [DeviceType](#devicetype) | Yes | Device type. | 3675| callback | AsyncCallback<number> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the volume gain obtained; otherwise, **err** is an error object.| 3676 3677**Error codes** 3678 3679For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 3680 3681| ID| Error Message| 3682| ------- | --------------------------------------------| 3683| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 3684| 6800101 | Parameter verification failed. Return by callback. | 3685| 6800301 | System error. Return by callback. | 3686 3687**Example** 3688 3689```ts 3690import { BusinessError } from '@kit.BasicServicesKit'; 3691 3692audioVolumeGroupManager.getSystemVolumeInDb(audio.AudioVolumeType.MEDIA, 3, audio.DeviceType.SPEAKER, (err: BusinessError, dB: number) => { 3693 if (err) { 3694 console.error(`Failed to get the volume DB. ${err}`); 3695 } else { 3696 console.info(`Success to get the volume DB. ${dB}`); 3697 } 3698}); 3699``` 3700 3701### getSystemVolumeInDb<sup>10+</sup> 3702 3703getSystemVolumeInDb(volumeType: AudioVolumeType, volumeLevel: number, device: DeviceType): Promise<number> 3704 3705Obtains the volume gain. This API uses a promise to return the result. 3706 3707**System capability**: SystemCapability.Multimedia.Audio.Volume 3708 3709**Parameters** 3710 3711| Name | Type | Mandatory| Description | 3712| ---------- | ----------------------------------- | ---- | -------------------------------------------------------- | 3713| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | 3714| volumeLevel | number | Yes | Volume level. | 3715| device | [DeviceType](#devicetype) | Yes | Device type. | 3716 3717**Return value** 3718 3719| Type | Description | 3720| --------------------- | ---------------------------------- | 3721| Promise<number> | Promise used to return the volume gain (in dB).| 3722 3723**Error codes** 3724 3725For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 3726 3727| ID| Error Message| 3728| ------- | --------------------------------------------| 3729| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 3730| 6800101 | Parameter verification failed. Return by promise. | 3731| 6800301 | System error. Return by promise. | 3732 3733**Example** 3734 3735```ts 3736import { BusinessError } from '@kit.BasicServicesKit'; 3737 3738audioVolumeGroupManager.getSystemVolumeInDb(audio.AudioVolumeType.MEDIA, 3, audio.DeviceType.SPEAKER).then((value: number) => { 3739 console.info(`Success to get the volume DB. ${value}`); 3740}).catch((error: BusinessError) => { 3741 console.error(`Fail to adjust the system volume by step. ${error}`); 3742}); 3743``` 3744 3745### getSystemVolumeInDbSync<sup>10+</sup> 3746 3747getSystemVolumeInDbSync(volumeType: AudioVolumeType, volumeLevel: number, device: DeviceType): number 3748 3749Obtains the volume gain. This API returns the result synchronously. 3750 3751**System capability**: SystemCapability.Multimedia.Audio.Volume 3752 3753**Parameters** 3754 3755| Name | Type | Mandatory| Description | 3756| ---------- | ----------------------------------- | ---- | -------------------------------------------------------- | 3757| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | 3758| volumeLevel | number | Yes | Volume level. | 3759| device | [DeviceType](#devicetype) | Yes | Device type. | 3760 3761**Return value** 3762 3763| Type | Description | 3764| --------------------- | ---------------------------------- | 3765| number | Volume gain (in dB).| 3766 3767**Error codes** 3768 3769For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 3770 3771| ID| Error Message| 3772| ------- | --------------------------------------------| 3773| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 3774| 6800101 | Parameter verification failed. | 3775 3776**Example** 3777 3778```ts 3779import { BusinessError } from '@kit.BasicServicesKit'; 3780 3781try { 3782 let value: number = audioVolumeGroupManager.getSystemVolumeInDbSync(audio.AudioVolumeType.MEDIA, 3, audio.DeviceType.SPEAKER); 3783 console.info(`Success to get the volume DB. ${value}`); 3784} catch (err) { 3785 let error = err as BusinessError; 3786 console.error(`Fail to adjust the system volume by step. ${error}`); 3787} 3788``` 3789 3790### getMaxAmplitudeForInputDevice<sup>12+</sup> 3791 3792getMaxAmplitudeForInputDevice(inputDevice: AudioDeviceDescriptor): Promise<number> 3793 3794Obtains the maximum amplitude (in the range [0, 1]) of the audio stream for an input device. This API uses a promise to return the result. 3795 3796**System capability**: SystemCapability.Multimedia.Audio.Volume 3797 3798**Parameters** 3799 3800| Name | Type | Mandatory| Description | 3801| ----------- | ------------------------------------- | ---- | --------------------------------------------------- | 3802| inputDevice | [AudioDeviceDescriptor](#audiodevicedescriptor) | Yes | Descriptor of the target device. | 3803 3804**Return value** 3805 3806| Type | Description | 3807| --------------------- | ---------------------------------- | 3808| Promise<number> | Promise used to return the maximum amplitude, which is in the range [0, 1].| 3809 3810**Error codes** 3811 3812For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 3813 3814| ID| Error Message| 3815| ------- | --------------------------------------------| 3816| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 3817| 6800101 | Parameter verification failed. Return by promise. | 3818| 6800301 | System error. Return by promise. | 3819 3820**Example** 3821 3822```ts 3823import { BusinessError } from '@kit.BasicServicesKit'; 3824 3825let capturerInfo: audio.AudioCapturerInfo = { 3826 source: audio.SourceType.SOURCE_TYPE_MIC, // Audio source type: microphone. Set this parameter based on the service scenario. 3827 capturerFlags: 0 // AudioCapturer flag. 3828}; 3829 3830audio.getAudioManager().getRoutingManager().getPreferredInputDeviceForCapturerInfo(capturerInfo).then((data) => { 3831 audioVolumeGroupManager.getMaxAmplitudeForInputDevice(data[0]).then((value) => { 3832 console.info(`mic volatileume amplitude is: ${value}`); 3833 }).catch((err: BusinessError) => { 3834 console.error("getMaxAmplitudeForInputDevice error" + JSON.stringify(err)); 3835 }) 3836}).catch((err: BusinessError) => { 3837 console.error("get outputDeviceId error" + JSON.stringify(err)); 3838}) 3839``` 3840 3841### getMaxAmplitudeForOutputDevice<sup>12+</sup> 3842 3843getMaxAmplitudeForOutputDevice(outputDevice: AudioDeviceDescriptor): Promise<number> 3844 3845Obtains the maximum amplitude (in the range [0, 1]) of the audio stream for an output device. This API uses a promise to return the result. 3846 3847**System capability**: SystemCapability.Multimedia.Audio.Volume 3848 3849**Parameters** 3850 3851| Name | Type | Mandatory| Description | 3852| ------------ | --------------------------------------- | ---- | -------------------------------------------------------- | 3853| outputDevice | [AudioDeviceDescriptor](#audiodevicedescriptor) | Yes | Descriptor of the target device. | 3854 3855**Return value** 3856 3857| Type | Description | 3858| --------------------- | ---------------------------------- | 3859| Promise<number> | Promise used to return the maximum amplitude, which is in the range [0, 1].| 3860 3861**Error codes** 3862 3863For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 3864 3865| ID| Error Message| 3866| ------- | --------------------------------------------| 3867| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 3868| 6800101 | Parameter verification failed. Return by promise. | 3869| 6800301 | System error. Return by promise. | 3870 3871**Example** 3872 3873```ts 3874import { BusinessError } from '@kit.BasicServicesKit'; 3875 3876let rendererInfo: audio.AudioRendererInfo = { 3877 usage: audio.StreamUsage.STREAM_USAGE_MUSIC, // Audio stream usage type: music. Set this parameter based on the service scenario. 3878 rendererFlags: 0 // AudioRenderer flag. 3879}; 3880 3881audio.getAudioManager().getRoutingManager().getPreferOutputDeviceForRendererInfo(rendererInfo).then((data) => { 3882 audioVolumeGroupManager.getMaxAmplitudeForOutputDevice(data[0]).then((value) => { 3883 console.info(`mic volatileume amplitude is: ${value}`); 3884 }).catch((err: BusinessError) => { 3885 console.error("getMaxAmplitudeForOutputDevice error" + JSON.stringify(err)); 3886 }) 3887}).catch((err: BusinessError) => { 3888 console.error("getPreferOutputDeviceForRendererInfo error" + JSON.stringify(err)); 3889}) 3890``` 3891 3892## AudioStreamManager<sup>9+</sup> 3893 3894Implements audio stream management. 3895 3896Before calling any API in AudioStreamManager, you must use [getStreamManager](#getstreammanager9) to obtain an AudioStreamManager instance. 3897 3898### getCurrentAudioRendererInfoArray<sup>9+</sup> 3899 3900getCurrentAudioRendererInfoArray(callback: AsyncCallback<AudioRendererChangeInfoArray>): void 3901 3902Obtains the information about this audio renderer. This API uses an asynchronous callback to return the result. 3903 3904**System capability**: SystemCapability.Multimedia.Audio.Renderer 3905 3906**Parameters** 3907 3908| Name | Type | Mandatory | Description | 3909| -------- | ----------------------------------- | -------- | --------------------------- | 3910| callback | AsyncCallback<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the audio renderer information obtained; otherwise, **err** is an error object.| 3911 3912**Example** 3913 3914```ts 3915import { BusinessError } from '@kit.BasicServicesKit'; 3916 3917audioStreamManager.getCurrentAudioRendererInfoArray(async (err: BusinessError, AudioRendererChangeInfoArray: audio.AudioRendererChangeInfoArray) => { 3918 console.info('getCurrentAudioRendererInfoArray **** Get Callback Called ****'); 3919 if (err) { 3920 console.error(`getCurrentAudioRendererInfoArray :ERROR: ${err}`); 3921 } else { 3922 if (AudioRendererChangeInfoArray != null) { 3923 for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { 3924 let AudioRendererChangeInfo: audio.AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; 3925 console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`); 3926 console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`); 3927 console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`); 3928 console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`); 3929 for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) { 3930 console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`); 3931 console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`); 3932 console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`); 3933 console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`); 3934 console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`); 3935 console.info(`SampleRate: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`); 3936 console.info(`ChannelCount: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`); 3937 console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks[0]}`); 3938 } 3939 } 3940 } 3941 } 3942}); 3943``` 3944 3945### getCurrentAudioRendererInfoArray<sup>9+</sup> 3946 3947getCurrentAudioRendererInfoArray(): Promise<AudioRendererChangeInfoArray> 3948 3949Obtains the information about this audio renderer. This API uses a promise to return the result. 3950 3951**System capability**: SystemCapability.Multimedia.Audio.Renderer 3952 3953**Return value** 3954 3955| Type | Description | 3956| ---------------------------------------------------------------------------------| --------------------------------------- | 3957| Promise<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | Promise used to return the audio renderer information. | 3958 3959**Example** 3960 3961```ts 3962import { BusinessError } from '@kit.BasicServicesKit'; 3963 3964async function getCurrentAudioRendererInfoArray(){ 3965 await audioStreamManager.getCurrentAudioRendererInfoArray().then((AudioRendererChangeInfoArray: audio.AudioRendererChangeInfoArray) => { 3966 console.info(`getCurrentAudioRendererInfoArray ######### Get Promise is called ##########`); 3967 if (AudioRendererChangeInfoArray != null) { 3968 for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { 3969 let AudioRendererChangeInfo: audio.AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; 3970 console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`); 3971 console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`); 3972 console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`); 3973 console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`); 3974 for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) { 3975 console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`); 3976 console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`); 3977 console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`); 3978 console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`); 3979 console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`); 3980 console.info(`SampleRate: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`); 3981 console.info(`ChannelCount: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`); 3982 console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks[0]}`); 3983 } 3984 } 3985 } 3986 }).catch((err: BusinessError) => { 3987 console.error(`getCurrentAudioRendererInfoArray :ERROR: ${err}`); 3988 }); 3989} 3990``` 3991### getCurrentAudioRendererInfoArraySync<sup>10+</sup> 3992 3993getCurrentAudioRendererInfoArraySync(): AudioRendererChangeInfoArray 3994 3995Obtains the information about this audio renderer. This API returns the result synchronously. 3996 3997**System capability**: SystemCapability.Multimedia.Audio.Renderer 3998 3999**Return value** 4000 4001| Type | Description | 4002| ---------------------------------------------------------------------------------| --------------------------------------- | 4003| [AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9) | Audio renderer information. | 4004 4005**Example** 4006 4007```ts 4008import { BusinessError } from '@kit.BasicServicesKit'; 4009 4010try { 4011 let audioRendererChangeInfoArray: audio.AudioRendererChangeInfoArray = audioStreamManager.getCurrentAudioRendererInfoArraySync(); 4012 console.info(`getCurrentAudioRendererInfoArraySync success.`); 4013 if (audioRendererChangeInfoArray != null) { 4014 for (let i = 0; i < audioRendererChangeInfoArray.length; i++) { 4015 let AudioRendererChangeInfo: audio.AudioRendererChangeInfo = audioRendererChangeInfoArray[i]; 4016 console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`); 4017 console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`); 4018 console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`); 4019 console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`); 4020 for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) { 4021 console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`); 4022 console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`); 4023 console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`); 4024 console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`); 4025 console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`); 4026 console.info(`SampleRate: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`); 4027 console.info(`ChannelCount: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`); 4028 console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks[0]}`); 4029 } 4030 } 4031 } 4032} catch (err) { 4033 let error = err as BusinessError; 4034 console.error(`getCurrentAudioRendererInfoArraySync :ERROR: ${error}`); 4035} 4036``` 4037 4038### getCurrentAudioCapturerInfoArray<sup>9+</sup> 4039 4040getCurrentAudioCapturerInfoArray(callback: AsyncCallback<AudioCapturerChangeInfoArray>): void 4041 4042Obtains the information about this audio capturer. This API uses an asynchronous callback to return the result. 4043 4044**System capability**: SystemCapability.Multimedia.Audio.Renderer 4045 4046**Parameters** 4047 4048| Name | Type | Mandatory | Description | 4049| ---------- | ----------------------------------- | --------- | -------------------------------------------------------- | 4050| callback | AsyncCallback<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the audio capturer information obtained; otherwise, **err** is an error object.| 4051 4052**Example** 4053 4054```ts 4055import { BusinessError } from '@kit.BasicServicesKit'; 4056 4057audioStreamManager.getCurrentAudioCapturerInfoArray(async (err: BusinessError, AudioCapturerChangeInfoArray: audio.AudioCapturerChangeInfoArray) => { 4058 console.info('getCurrentAudioCapturerInfoArray **** Get Callback Called ****'); 4059 if (err) { 4060 console.error(`getCurrentAudioCapturerInfoArray :ERROR: ${err}`); 4061 } else { 4062 if (AudioCapturerChangeInfoArray != null) { 4063 for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { 4064 console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); 4065 console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); 4066 console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); 4067 for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { 4068 console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); 4069 console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); 4070 console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); 4071 console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); 4072 console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); 4073 console.info(`SampleRate: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); 4074 console.info(`ChannelCount: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); 4075 console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks[0]}`); 4076 } 4077 } 4078 } 4079 } 4080}); 4081``` 4082 4083### getCurrentAudioCapturerInfoArray<sup>9+</sup> 4084 4085getCurrentAudioCapturerInfoArray(): Promise<AudioCapturerChangeInfoArray> 4086 4087Obtains the information about this audio capturer. This API uses a promise to return the result. 4088 4089**System capability**: SystemCapability.Multimedia.Audio.Renderer 4090 4091**Return value** 4092 4093| Type | Description | 4094| -----------------------------------------------------------------------------| ----------------------------------- | 4095| Promise<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | Promise used to return the audio capturer information. | 4096 4097**Example** 4098 4099```ts 4100import { BusinessError } from '@kit.BasicServicesKit'; 4101 4102async function getCurrentAudioCapturerInfoArray(){ 4103 await audioStreamManager.getCurrentAudioCapturerInfoArray().then((AudioCapturerChangeInfoArray: audio.AudioCapturerChangeInfoArray) => { 4104 console.info('getCurrentAudioCapturerInfoArray **** Get Promise Called ****'); 4105 if (AudioCapturerChangeInfoArray != null) { 4106 for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { 4107 console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); 4108 console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); 4109 console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); 4110 for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { 4111 console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); 4112 console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); 4113 console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); 4114 console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); 4115 console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); 4116 console.info(`SampleRate: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); 4117 console.info(`ChannelCount: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); 4118 console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks[0]}`); 4119 } 4120 } 4121 } 4122 }).catch((err: BusinessError) => { 4123 console.error(`getCurrentAudioCapturerInfoArray :ERROR: ${err}`); 4124 }); 4125} 4126``` 4127### getCurrentAudioCapturerInfoArraySync<sup>10+</sup> 4128 4129getCurrentAudioCapturerInfoArraySync(): AudioCapturerChangeInfoArray 4130 4131Obtains the information about this audio capturer. This API returns the result synchronously. 4132 4133**System capability**: SystemCapability.Multimedia.Audio.Capturer 4134 4135**Return value** 4136 4137| Type | Description | 4138| -----------------------------------------------------------------------------| ----------------------------------- | 4139| [AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9) | Audio capturer information. | 4140 4141**Example** 4142 4143```ts 4144import { BusinessError } from '@kit.BasicServicesKit'; 4145 4146try { 4147 let audioCapturerChangeInfoArray: audio.AudioCapturerChangeInfoArray = audioStreamManager.getCurrentAudioCapturerInfoArraySync(); 4148 console.info('getCurrentAudioCapturerInfoArraySync success.'); 4149 if (audioCapturerChangeInfoArray != null) { 4150 for (let i = 0; i < audioCapturerChangeInfoArray.length; i++) { 4151 console.info(`StreamId for ${i} is: ${audioCapturerChangeInfoArray[i].streamId}`); 4152 console.info(`Source for ${i} is: ${audioCapturerChangeInfoArray[i].capturerInfo.source}`); 4153 console.info(`Flag ${i} is: ${audioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); 4154 for (let j = 0; j < audioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { 4155 console.info(`Id: ${i} : ${audioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); 4156 console.info(`Type: ${i} : ${audioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); 4157 console.info(`Role: ${i} : ${audioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); 4158 console.info(`Name: ${i} : ${audioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); 4159 console.info(`Address: ${i} : ${audioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); 4160 console.info(`SampleRate: ${i} : ${audioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); 4161 console.info(`ChannelCount: ${i} : ${audioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); 4162 console.info(`ChannelMask: ${i} : ${audioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks[0]}`); 4163 } 4164 } 4165 } 4166} catch (err) { 4167 let error = err as BusinessError; 4168 console.error(`getCurrentAudioCapturerInfoArraySync ERROR: ${error}`); 4169} 4170``` 4171 4172### on('audioRendererChange')<sup>9+</sup> 4173 4174on(type: 'audioRendererChange', callback: Callback<AudioRendererChangeInfoArray>): void 4175 4176Subscribes to the audio renderer change event, which is triggered when the audio playback stream status or device is changed. This API uses an asynchronous callback to return the result. 4177 4178**System capability**: SystemCapability.Multimedia.Audio.Renderer 4179 4180**Parameters** 4181 4182| Name | Type | Mandatory | Description | 4183| -------- | ---------- | --------- | ------------------------------------------------------------------------ | 4184| type | string | Yes | Event type. The event **'audioRendererChange'** is triggered when the audio playback stream status or device is changed.| 4185| callback | Callback<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | Yes | Callback used to return the audio renderer information.| 4186 4187**Error codes** 4188 4189For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 4190 4191| ID| Error Message| 4192| ------- | --------------------------------------------| 4193| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 4194| 6800101 | Parameter verification failed. | 4195 4196**Example** 4197 4198```ts 4199audioStreamManager.on('audioRendererChange', (audioRendererChangeInfoArray: audio.AudioRendererChangeInfoArray) => { 4200 for (let i = 0; i < audioRendererChangeInfoArray.length; i++) { 4201 let audioRendererChangeInfo: audio.AudioRendererChangeInfo = audioRendererChangeInfoArray[i]; 4202 console.info(`## RendererChange on is called for ${i} ##`); 4203 console.info(`StreamId for ${i} is: ${audioRendererChangeInfo.streamId}`); 4204 console.info(`Content ${i} is: ${audioRendererChangeInfo.rendererInfo.content}`); 4205 console.info(`Stream ${i} is: ${audioRendererChangeInfo.rendererInfo.usage}`); 4206 console.info(`Flag ${i} is: ${audioRendererChangeInfo.rendererInfo.rendererFlags}`); 4207 for (let j = 0;j < audioRendererChangeInfo.deviceDescriptors.length; j++) { 4208 console.info(`Id: ${i} : ${audioRendererChangeInfo.deviceDescriptors[j].id}`); 4209 console.info(`Type: ${i} : ${audioRendererChangeInfo.deviceDescriptors[j].deviceType}`); 4210 console.info(`Role: ${i} : ${audioRendererChangeInfo.deviceDescriptors[j].deviceRole}`); 4211 console.info(`Name: ${i} : ${audioRendererChangeInfo.deviceDescriptors[j].name}`); 4212 console.info(`Address: ${i} : ${audioRendererChangeInfo.deviceDescriptors[j].address}`); 4213 console.info(`SampleRate: ${i} : ${audioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`); 4214 console.info(`ChannelCount: ${i} : ${audioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`); 4215 console.info(`ChannelMask: ${i} : ${audioRendererChangeInfo.deviceDescriptors[j].channelMasks[0]}`); 4216 } 4217 } 4218}); 4219``` 4220 4221### off('audioRendererChange')<sup>9+</sup> 4222 4223off(type: 'audioRendererChange', callback?: Callback<AudioRendererChangeInfoArray>): void 4224 4225Unsubscribes from the audio renderer change event. This API uses an asynchronous callback to return the result. 4226 4227**System capability**: SystemCapability.Multimedia.Audio.Renderer 4228 4229**Parameters** 4230 4231| Name | Type | Mandatory| Description | 4232| -------- | ------- |----| ---------------- | 4233| type | string | Yes | Event type. The event **'audioRendererChange'** is triggered when the audio playback stream status or device is changed.| 4234| callback<sup>18+</sup> | Callback<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | No | Callback used to return the audio renderer information.| 4235 4236**Error codes** 4237 4238For details about the error codes, see [Audio Error Codes](errorcode-audio.md). 4239 4240| ID| Error Message | 4241| ------- |--------------------------| 4242| 6800101 | Parameter verification failed. | 4243 4244**Example** 4245 4246```ts 4247// Cancel all subscriptions to the event. 4248audioStreamManager.off('audioRendererChange'); 4249 4250// For the same event, if the callback parameter passed to the off API is the same as that passed to the on API, the off API cancels the subscription registered with the specified callback parameter. 4251let audioRendererChangeCallback = (audioRendererChangeInfoArray: audio.AudioRendererChangeInfoArray) => { 4252 for (let i = 0; i < audioRendererChangeInfoArray.length; i++) { 4253 let audioRendererChangeInfo: audio.AudioRendererChangeInfo = audioRendererChangeInfoArray[i]; 4254 console.info(`## RendererChange on is called for ${i} ##`); 4255 console.info(`StreamId for ${i} is: ${audioRendererChangeInfo.streamId}`); 4256 console.info(`Content ${i} is: ${audioRendererChangeInfo.rendererInfo.content}`); 4257 console.info(`Stream ${i} is: ${audioRendererChangeInfo.rendererInfo.usage}`); 4258 console.info(`Flag ${i} is: ${audioRendererChangeInfo.rendererInfo.rendererFlags}`); 4259 for (let j = 0;j < audioRendererChangeInfo.deviceDescriptors.length; j++) { 4260 console.info(`Id: ${i} : ${audioRendererChangeInfo.deviceDescriptors[j].id}`); 4261 console.info(`Type: ${i} : ${audioRendererChangeInfo.deviceDescriptors[j].deviceType}`); 4262 console.info(`Role: ${i} : ${audioRendererChangeInfo.deviceDescriptors[j].deviceRole}`); 4263 console.info(`Name: ${i} : ${audioRendererChangeInfo.deviceDescriptors[j].name}`); 4264 console.info(`Address: ${i} : ${audioRendererChangeInfo.deviceDescriptors[j].address}`); 4265 console.info(`SampleRate: ${i} : ${audioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`); 4266 console.info(`ChannelCount: ${i} : ${audioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`); 4267 console.info(`ChannelMask: ${i} : ${audioRendererChangeInfo.deviceDescriptors[j].channelMasks[0]}`); 4268 } 4269 } 4270}; 4271 4272audioStreamManager.on('audioRendererChange', audioRendererChangeCallback); 4273 4274audioStreamManager.off('audioRendererChange', audioRendererChangeCallback); 4275``` 4276 4277### on('audioCapturerChange')<sup>9+</sup> 4278 4279on(type: 'audioCapturerChange', callback: Callback<AudioCapturerChangeInfoArray>): void 4280 4281Subscribes to the audio capturer change event, which is triggered when the audio recording stream status or device is changed. This API uses an asynchronous callback to return the result. 4282 4283**System capability**: SystemCapability.Multimedia.Audio.Capturer 4284 4285**Parameters** 4286 4287| Name | Type | Mandatory | Description | 4288| -------- | ------- | --------- | ---------------------------------------------------------------------- | 4289| type | string | Yes | Event type. The event **'audioCapturerChange'** is triggered when the audio recording stream status or device is changed.| 4290| callback | Callback<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | Yes | Callback used to return the audio capturer information.| 4291 4292**Error codes** 4293 4294For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 4295 4296| ID| Error Message| 4297| ------- | --------------------------------------------| 4298| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 4299| 6800101 | Parameter verification failed. | 4300 4301**Example** 4302 4303```ts 4304audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray: audio.AudioCapturerChangeInfoArray) => { 4305 for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { 4306 console.info(`## CapChange on is called for element ${i} ##`); 4307 console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); 4308 console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); 4309 console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); 4310 for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { 4311 console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); 4312 console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); 4313 console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); 4314 console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); 4315 console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); 4316 console.info(`SampleRate: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); 4317 console.info(`ChannelCount: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); 4318 console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks[0]}`); 4319 } 4320 } 4321}); 4322``` 4323 4324### off('audioCapturerChange')<sup>9+</sup> 4325 4326off(type: 'audioCapturerChange', callback?: Callback<AudioCapturerChangeInfoArray>): void 4327 4328Unsubscribes from the audio capturer change event. This API uses an asynchronous callback to return the result. 4329 4330**System capability**: SystemCapability.Multimedia.Audio.Capturer 4331 4332**Parameters** 4333 4334| Name | Type | Mandatory| Description | 4335| -------- | -------- | --- | ------------------------------------------------------------- | 4336| type | string |Yes | Event type. The event **'audioCapturerChange'** is triggered when the audio capturer is changed.| 4337| callback<sup>18+</sup> | Callback<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | No| Callback used to return the audio capturer information.| 4338 4339**Error codes** 4340 4341For details about the error codes, see [Audio Error Codes](errorcode-audio.md). 4342 4343| ID| Error Message| 4344| ------- | --------------------------------------------| 4345| 6800101 | Parameter verification failed. | 4346 4347**Example** 4348 4349```ts 4350audioStreamManager.off('audioCapturerChange'); 4351// Cancel all subscriptions to the event. 4352audioStreamManager.off('audioCapturerChange'); 4353 4354// For the same event, if the callback parameter passed to the off API is the same as that passed to the on API, the off API cancels the subscription registered with the specified callback parameter. 4355let audioCapturerChangeCallback = (AudioCapturerChangeInfoArray: audio.AudioCapturerChangeInfoArray) => { 4356 for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { 4357 console.info(`## CapChange on is called for element ${i} ##`); 4358 console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); 4359 console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); 4360 console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); 4361 for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { 4362 console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); 4363 console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); 4364 console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); 4365 console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); 4366 console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); 4367 console.info(`SampleRate: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); 4368 console.info(`ChannelCount: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); 4369 console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks[0]}`); 4370 } 4371 } 4372}; 4373 4374audioStreamManager.on('audioCapturerChange', audioCapturerChangeCallback); 4375 4376audioStreamManager.off('audioCapturerChange', audioCapturerChangeCallback); 4377``` 4378 4379### isActive<sup>9+</sup> 4380 4381isActive(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void 4382 4383Checks whether a stream is active. This API uses an asynchronous callback to return the result. 4384 4385**System capability**: SystemCapability.Multimedia.Audio.Renderer 4386 4387**Parameters** 4388 4389| Name | Type | Mandatory| Description | 4390| ---------- | ----------------------------------- | ---- | ------------------------------------------------- | 4391| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream types. | 4392| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is **true** if the stream is active or **false** if not active; otherwise, **err** is an error object.| 4393 4394**Example** 4395 4396```ts 4397import { BusinessError } from '@kit.BasicServicesKit'; 4398 4399audioStreamManager.isActive(audio.AudioVolumeType.MEDIA, (err: BusinessError, value: boolean) => { 4400if (err) { 4401 console.error(`Failed to obtain the active status of the stream. ${err}`); 4402 return; 4403} 4404 console.info(`Callback invoked to indicate that the active status of the stream is obtained ${value}.`); 4405}); 4406``` 4407 4408### isActive<sup>9+</sup> 4409 4410isActive(volumeType: AudioVolumeType): Promise<boolean> 4411 4412Checks whether a stream is active. This API uses a promise to return the result. 4413 4414**System capability**: SystemCapability.Multimedia.Audio.Renderer 4415 4416**Parameters** 4417 4418| Name | Type | Mandatory| Description | 4419| ---------- | ----------------------------------- | ---- | ------------ | 4420| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream types.| 4421 4422**Return value** 4423 4424| Type | Description | 4425| ---------------------- | -------------------------------------------------------- | 4426| Promise<boolean> | Promise used to return the result. The value **true** means that the stream is active, and **false** means the opposite.| 4427 4428**Example** 4429 4430```ts 4431audioStreamManager.isActive(audio.AudioVolumeType.MEDIA).then((value: boolean) => { 4432 console.info(`Promise returned to indicate that the active status of the stream is obtained ${value}.`); 4433}); 4434``` 4435 4436### isActiveSync<sup>10+</sup> 4437 4438isActiveSync(volumeType: AudioVolumeType): boolean 4439 4440Checks whether a stream is active. This API returns the result synchronously. 4441 4442**System capability**: SystemCapability.Multimedia.Audio.Renderer 4443 4444**Parameters** 4445 4446| Name | Type | Mandatory| Description | 4447| ---------- | ----------------------------------- | ---- | ------------ | 4448| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream types.| 4449 4450**Return value** 4451 4452| Type | Description | 4453| ---------------------- | -------------------------------------------------------- | 4454| boolean | Check result. The value **true** means that the stream is active, and **false** means the opposite.| 4455 4456**Error codes** 4457 4458For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 4459 4460| ID| Error Message| 4461| ------- | --------------------------------------------| 4462| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 4463| 6800101 | Parameter verification failed. | 4464 4465**Example** 4466 4467```ts 4468import { BusinessError } from '@kit.BasicServicesKit'; 4469 4470try { 4471 let value: boolean = audioStreamManager.isActiveSync(audio.AudioVolumeType.MEDIA); 4472 console.info(`Indicate that the active status of the stream is obtained ${value}.`); 4473} catch (err) { 4474 let error = err as BusinessError; 4475 console.error(`Failed to obtain the active status of the stream ${error}.`); 4476} 4477``` 4478 4479### getAudioEffectInfoArray<sup>10+</sup> 4480 4481getAudioEffectInfoArray(usage: StreamUsage, callback: AsyncCallback<AudioEffectInfoArray>): void 4482 4483Obtains information about the audio effect mode in use. This API uses an asynchronous callback to return the result. 4484 4485**System capability**: SystemCapability.Multimedia.Audio.Renderer 4486 4487**Parameters** 4488 4489| Name | Type | Mandatory | Description | 4490| -------- | ----------------------------------- | -------- | --------------------------- | 4491| usage | [StreamUsage](#streamusage) | Yes | Audio stream usage. | 4492| callback | AsyncCallback<[AudioEffectInfoArray](#audioeffectinfoarray10)> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the information about the audio effect mode obtained; otherwise, **err** is an error object.| 4493 4494**Error codes** 4495 4496For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 4497 4498| ID| Error Message| 4499| ------- | --------------------------------------------| 4500| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 4501| 6800101 | Parameter verification failed. Return by callback.| 4502 4503**Example** 4504 4505```ts 4506import { BusinessError } from '@kit.BasicServicesKit'; 4507 4508audioStreamManager.getAudioEffectInfoArray(audio.StreamUsage.STREAM_USAGE_MUSIC, async (err: BusinessError, audioEffectInfoArray: audio.AudioEffectInfoArray) => { 4509 console.info('getAudioEffectInfoArray **** Get Callback Called ****'); 4510 if (err) { 4511 console.error(`getAudioEffectInfoArray :ERROR: ${err}`); 4512 return; 4513 } else { 4514 console.info(`The effect modes are: ${audioEffectInfoArray}`); 4515 } 4516}); 4517``` 4518 4519### getAudioEffectInfoArray<sup>10+</sup> 4520 4521getAudioEffectInfoArray(usage: StreamUsage): Promise<AudioEffectInfoArray> 4522 4523Obtains information about the audio effect mode in use. This API uses a promise to return the result. 4524 4525**System capability**: SystemCapability.Multimedia.Audio.Renderer 4526 4527**Parameters** 4528 4529| Name | Type | Mandatory | Description | 4530| -------- | ----------------------------------- | -------- | --------------------------- | 4531| usage | [StreamUsage](#streamusage) | Yes | Audio stream usage. | 4532 4533**Return value** 4534 4535| Type | Description | 4536| --------------------------------------------------------------------------| --------------------------------------- | 4537| Promise<[AudioEffectInfoArray](#audioeffectinfoarray10)> | Promise used to return the information about the audio effect mode obtained. | 4538 4539**Error codes** 4540 4541For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 4542 4543| ID| Error Message| 4544| ------- | --------------------------------------------| 4545| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 4546| 6800101 | Parameter verification failed. Return by promise. | 4547 4548**Example** 4549 4550```ts 4551import { BusinessError } from '@kit.BasicServicesKit'; 4552 4553audioStreamManager.getAudioEffectInfoArray(audio.StreamUsage.STREAM_USAGE_MUSIC).then((audioEffectInfoArray: audio.AudioEffectInfoArray) => { 4554 console.info('getAudioEffectInfoArray ######### Get Promise is called ##########'); 4555 console.info(`The effect modes are: ${audioEffectInfoArray}`); 4556}).catch((err: BusinessError) => { 4557 console.error(`getAudioEffectInfoArray :ERROR: ${err}`); 4558}); 4559``` 4560 4561### getAudioEffectInfoArraySync<sup>10+</sup> 4562 4563getAudioEffectInfoArraySync(usage: StreamUsage): AudioEffectInfoArray 4564 4565Obtains information about the audio effect mode in use. This API returns the result synchronously. 4566 4567**System capability**: SystemCapability.Multimedia.Audio.Renderer 4568 4569**Parameters** 4570 4571| Name | Type | Mandatory | Description | 4572| -------- | ----------------------------------- | -------- | --------------------------- | 4573| usage | [StreamUsage](#streamusage) | Yes | Audio stream usage. | 4574 4575**Return value** 4576 4577| Type | Description | 4578| --------------------------------------------------------------------------| --------------------------------------- | 4579| [AudioEffectInfoArray](#audioeffectinfoarray10) | Information about the audio effect mode. | 4580 4581**Error codes** 4582 4583For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 4584 4585| ID| Error Message| 4586| ------- | --------------------------------------------| 4587| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 4588| 6800101 | Parameter verification failed. | 4589 4590**Example** 4591 4592```ts 4593import { BusinessError } from '@kit.BasicServicesKit'; 4594 4595try { 4596 let audioEffectInfoArray: audio.AudioEffectInfoArray = audioStreamManager.getAudioEffectInfoArraySync(audio.StreamUsage.STREAM_USAGE_MUSIC); 4597 console.info(`The effect modes are: ${audioEffectInfoArray}`); 4598} catch (err) { 4599 let error = err as BusinessError; 4600 console.error(`getAudioEffectInfoArraySync ERROR: ${error}`); 4601} 4602``` 4603 4604### isAcousticEchoCancelerSupported<sup>20+</sup> 4605 4606isAcousticEchoCancelerSupported(sourceType: SourceType): boolean 4607 4608Checks whether the specified audio source type supports echo cancellation. 4609 4610**System capability**: SystemCapability.Multimedia.Audio.Capturer 4611 4612**Parameters** 4613 4614| Name | Type | Mandatory | Description | 4615| -------- | ----------------------------------- | -------- | --------------------------- | 4616| sourceType | [SourceType](#sourcetype8) | Yes | Audio source type. | 4617 4618**Return value** 4619 4620| Type | Description | 4621| --------------------------------------------------------------------------| --------------------------------------- | 4622| boolean | Check result. The value **true** means that echo cancellation is supported, and **false** means the opposite. | 4623 4624**Error codes** 4625 4626For details about the error codes, see [Audio Error Codes](errorcode-audio.md). 4627 4628| ID| Error Message| 4629| ------- | --------------------------------------------| 4630| 6800101 | Parameter verification failed. | 4631 4632**Example** 4633 4634```ts 4635import { BusinessError } from '@kit.BasicServicesKit'; 4636 4637try { 4638 let isSupportAEC = audioStreamManager.isAcousticEchoCancelerSupported(audio.SourceType.SOURCE_TYPE_LIVE); 4639 console.info(`[AEC Support] SourceType: ${audio.SourceType.SOURCE_TYPE_LIVE}, Status: ${isSupportAEC}`); 4640} catch (err) { 4641 let error = err as BusinessError; 4642 console.error(`isAcousticEchoCancelerSupported ERROR: ${error}`); 4643} 4644``` 4645 4646## AudioRoutingManager<sup>9+</sup> 4647 4648Implements audio routing management. 4649 4650Before calling any API in AudioRoutingManager, you must use [getRoutingManager](#getroutingmanager9) to obtain an AudioRoutingManager instance. 4651 4652### getDevices<sup>9+</sup> 4653 4654getDevices(deviceFlag: DeviceFlag, callback: AsyncCallback<AudioDeviceDescriptors>): void 4655 4656Obtains the audio devices with a specific flag. This API uses an asynchronous callback to return the result. 4657 4658**System capability**: SystemCapability.Multimedia.Audio.Device 4659 4660**Parameters** 4661 4662| Name | Type | Mandatory| Description | 4663| ---------- | ------------------------------------------------------------ | ---- | -------------------- | 4664| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag. | 4665| callback | AsyncCallback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the audio devices obtained; otherwise, **err** is an error object.| 4666 4667**Example** 4668 4669```ts 4670import { BusinessError } from '@kit.BasicServicesKit'; 4671 4672audioRoutingManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err: BusinessError, value: audio.AudioDeviceDescriptors) => { 4673 if (err) { 4674 console.error(`Failed to obtain the device list. ${err}`); 4675 return; 4676 } 4677 console.info('Callback invoked to indicate that the device list is obtained.'); 4678}); 4679``` 4680 4681### getDevices<sup>9+</sup> 4682 4683getDevices(deviceFlag: DeviceFlag): Promise<AudioDeviceDescriptors> 4684 4685Obtains the audio devices with a specific flag. This API uses a promise to return the result. 4686 4687**System capability**: SystemCapability.Multimedia.Audio.Device 4688 4689**Parameters** 4690 4691| Name | Type | Mandatory| Description | 4692| ---------- | ------------------------- | ---- | ---------------- | 4693| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag.| 4694 4695**Return value** 4696 4697| Type | Description | 4698| ------------------------------------------------------------ | ------------------------- | 4699| Promise<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Promise used to return the device list.| 4700 4701**Example** 4702 4703```ts 4704audioRoutingManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data: audio.AudioDeviceDescriptors) => { 4705 console.info('Promise returned to indicate that the device list is obtained.'); 4706}); 4707``` 4708 4709### getDevicesSync<sup>10+</sup> 4710 4711getDevicesSync(deviceFlag: DeviceFlag): AudioDeviceDescriptors 4712 4713Obtains the audio devices with a specific flag. This API returns the result synchronously. 4714 4715**System capability**: SystemCapability.Multimedia.Audio.Device 4716 4717**Parameters** 4718 4719| Name | Type | Mandatory| Description | 4720| ---------- | ------------------------- | ---- | ---------------- | 4721| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag.| 4722 4723**Return value** 4724 4725| Type | Description | 4726| ------------------------------------------------------------ | ------------------------- | 4727| [AudioDeviceDescriptors](#audiodevicedescriptors) | Device list.| 4728 4729**Error codes** 4730 4731For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 4732 4733| ID| Error Message| 4734| ------- | --------------------------------------------| 4735| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 4736| 6800101 | Parameter verification failed. | 4737 4738**Example** 4739 4740```ts 4741import { BusinessError } from '@kit.BasicServicesKit'; 4742 4743try { 4744 let data: audio.AudioDeviceDescriptors = audioRoutingManager.getDevicesSync(audio.DeviceFlag.OUTPUT_DEVICES_FLAG); 4745 console.info(`Indicate that the device list is obtained ${data}`); 4746} catch (err) { 4747 let error = err as BusinessError; 4748 console.error(`Failed to obtain the device list. ${error}`); 4749} 4750``` 4751 4752### isMicBlockDetectionSupported<sup>13+</sup> 4753 4754isMicBlockDetectionSupported(): Promise<boolean> 4755 4756Checks whether the current device supports microphone blocking detection. This API uses a promise to return the result. 4757 4758**System capability**: SystemCapability.Multimedia.Audio.Device 4759 4760**Return value** 4761 4762| Type | Description | 4763| ---------------------- | ------------------------------------------------------------ | 4764| Promise<boolean> | Promise used to return the result. The value **true** means that the current device supports microphone blocking detection, and **false** means the opposite.| 4765 4766**Example** 4767 4768```ts 4769audioRoutingManager.isMicBlockDetectionSupported().then((value: boolean) => { 4770 console.info(`Query whether microphone block detection is supported on current device result is ${value}.`); 4771}); 4772``` 4773 4774### on('micBlockStatusChanged')<sup>13+</sup> 4775 4776on(type: 'micBlockStatusChanged', callback: Callback<DeviceBlockStatusInfo\>): void 4777 4778Subscribes to the microphone blocked status change event. This API uses an asynchronous callback to return the result. 4779 4780Before using this API, check whether the current device supports microphone blocking detection. This event is triggered when the microphone blocked status changes during recording. Currently, this API takes effect only for the microphone on the local device. 4781 4782**System capability**: SystemCapability.Multimedia.Audio.Device 4783 4784**Parameters** 4785 4786| Name | Type | Mandatory| Description | 4787| :------- | :--------------------------------------------------- | :--- | :----------------------------------------- | 4788| type | string | Yes | Event type. The event **'micBlockStatusChanged'** is triggered when the microphone blocked status is changed.| 4789| callback | Callback<[DeviceBlockStatusInfo](#deviceblockstatusinfo13)\> | Yes | Callback used to return the microphone blocked status and device information.| 4790 4791**Error codes** 4792 4793For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 4794 4795| ID| Error Message| 4796| ------- | --------------------------------------------| 4797| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 4798| 6800101 | Parameter verification failed. | 4799 4800**Example** 4801 4802```ts 4803// Before the subscription, check whether the current device supports detection. 4804audioRoutingManager.isMicBlockDetectionSupported().then((value: boolean) => { 4805 console.info(`Query whether microphone block detection is supported on current device result is ${value}.`); 4806 if (value) { 4807 audioRoutingManager.on('micBlockStatusChanged', (micBlockStatusChanged: audio.DeviceBlockStatusInfo) => { 4808 console.info(`block status : ${micBlockStatusChanged.blockStatus} `); 4809 }); 4810 } 4811}); 4812``` 4813 4814### off('micBlockStatusChanged')<sup>13+</sup> 4815 4816off(type: 'micBlockStatusChanged', callback?: Callback<DeviceBlockStatusInfo\>): void 4817 4818Unsubscribes from the microphone blocked status change event. This API uses an asynchronous callback to return the result. 4819 4820**System capability**: SystemCapability.Multimedia.Audio.Device 4821 4822**Parameters** 4823 4824| Name | Type | Mandatory| Description | 4825| -------- | --------------------------------------------------- | ---- | ------------------------------------------ | 4826| type | string | Yes | Event type. The event **'micBlockStatusChanged'** is triggered when the microphone blocked status is changed.| 4827| callback | Callback<[DeviceBlockStatusInfo](#deviceblockstatusinfo13)\> | No | Callback used to return the microphone blocked status and device information.| 4828 4829**Error codes** 4830 4831For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 4832 4833| ID| Error Message| 4834| ------- | --------------------------------------------| 4835| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 4836| 6800101 | Parameter verification failed. | 4837 4838**Example** 4839 4840```ts 4841// Cancel all subscriptions to the event. 4842audioRoutingManager.off('micBlockStatusChanged'); 4843 4844// For the same event, if the callback parameter passed to the off API is the same as that passed to the on API, the off API cancels the subscription registered with the specified callback parameter. 4845let micBlockStatusCallback = (micBlockStatusChanged: audio.DeviceBlockStatusInfo) => { 4846 console.info(`block status : ${micBlockStatusChanged.blockStatus} `); 4847}; 4848 4849audioRoutingManager.on('micBlockStatusChanged', micBlockStatusCallback); 4850 4851audioRoutingManager.off('micBlockStatusChanged', micBlockStatusCallback); 4852``` 4853 4854### on('deviceChange')<sup>9+</sup> 4855 4856on(type: 'deviceChange', deviceFlag: DeviceFlag, callback: Callback<DeviceChangeAction\>): void 4857 4858Subscribes to the event indicating that the connection status of an audio device is changed. This API uses an asynchronous callback to return the result. 4859 4860**System capability**: SystemCapability.Multimedia.Audio.Device 4861 4862**Parameters** 4863 4864| Name | Type | Mandatory| Description | 4865| :------- | :--------------------------------------------------- | :--- |:------------------------| 4866| type | string | Yes | Event type. The event **'deviceChange'** is triggered when the connection status of an audio device is changed.| 4867| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag. | 4868| callback | Callback<[DeviceChangeAction](#devicechangeaction)\> | Yes | Callback used to return the device change details. | 4869 4870**Error codes** 4871 4872For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 4873 4874| ID| Error Message| 4875| ------- | --------------------------------------------| 4876| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 4877| 6800101 | Parameter verification failed. | 4878 4879**Example** 4880 4881```ts 4882audioRoutingManager.on('deviceChange', audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (deviceChanged: audio.DeviceChangeAction) => { 4883 console.info('device change type : ' + deviceChanged.type); 4884 console.info('device descriptor size : ' + deviceChanged.deviceDescriptors.length); 4885 console.info('device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceRole); 4886 console.info('device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceType); 4887}); 4888``` 4889 4890### off('deviceChange')<sup>9+</sup> 4891 4892off(type: 'deviceChange', callback?: Callback<DeviceChangeAction\>): void 4893 4894Unsubscribes from the event indicating that the connection status of an audio device is changed. This API uses an asynchronous callback to return the result. 4895 4896**System capability**: SystemCapability.Multimedia.Audio.Device 4897 4898**Parameters** 4899 4900| Name | Type | Mandatory| Description | 4901| -------- | --------------------------------------------------- | ---- | ------------------------------------------ | 4902| type | string | Yes | Event type. The event **'deviceChange'** is triggered when the connection status of an audio device is changed.| 4903| callback | Callback<[DeviceChangeAction](#devicechangeaction)> | No | Callback used to return the device change details.| 4904 4905**Error codes** 4906 4907For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 4908 4909| ID| Error Message| 4910| ------- | --------------------------------------------| 4911| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 4912| 6800101 | Parameter verification failed. | 4913 4914**Example** 4915 4916```ts 4917// Cancel all subscriptions to the event. 4918audioRoutingManager.off('deviceChange'); 4919 4920// For the same event, if the callback parameter passed to the off API is the same as that passed to the on API, the off API cancels the subscription registered with the specified callback parameter. 4921let deviceChangeCallback = (deviceChanged: audio.DeviceChangeAction) => { 4922 console.info('device change type : ' + deviceChanged.type); 4923 console.info('device descriptor size : ' + deviceChanged.deviceDescriptors.length); 4924 console.info('device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceRole); 4925 console.info('device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceType); 4926}; 4927 4928audioRoutingManager.on('deviceChange', audio.DeviceFlag.OUTPUT_DEVICES_FLAG, deviceChangeCallback); 4929 4930audioRoutingManager.off('deviceChange', deviceChangeCallback); 4931``` 4932 4933### setCommunicationDevice<sup>9+</sup> 4934 4935setCommunicationDevice(deviceType: CommunicationDeviceType, active: boolean, callback: AsyncCallback<void>): void 4936 4937Sets a communication device to the active state. This API uses an asynchronous callback to return the result. 4938 4939This API will be deprecated in a later version due to function design is changed. You are not advised to use it. 4940 4941You are advised to use the [AVCastPicker component](../../media/avsession/using-switch-call-devices.md) provided by AVSession to switch between call devices. 4942 4943**System capability**: SystemCapability.Multimedia.Audio.Communication 4944 4945**Parameters** 4946 4947| Name | Type | Mandatory| Description | 4948| ---------- | ------------------------------------- | ---- |-------------------------| 4949| deviceType | [CommunicationDeviceType](#communicationdevicetype9) | Yes | Audio device flag. | 4950| active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite.| 4951| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 4952 4953**Example** 4954 4955```ts 4956import { BusinessError } from '@kit.BasicServicesKit'; 4957 4958audioRoutingManager.setCommunicationDevice(audio.CommunicationDeviceType.SPEAKER, true, (err: BusinessError) => { 4959 if (err) { 4960 console.error(`Failed to set the active status of the device. ${err}`); 4961 return; 4962 } 4963 console.info('Callback invoked to indicate that the device is set to the active status.'); 4964}); 4965``` 4966 4967### getAvailableDevices<sup>12+</sup> 4968 4969getAvailableDevices(deviceUsage: DeviceUsage): AudioDeviceDescriptors 4970 4971Obtains the available audio devices. This API returns the result synchronously. 4972 4973**System capability**: SystemCapability.Multimedia.Audio.Device 4974 4975**Parameters** 4976 4977| Name | Type | Mandatory| Description | 4978| ---------- | ------------------------- | ---- | ---------------- | 4979| deviceUsage| [DeviceUsage](#deviceusage12) | Yes | Audio device type (classified by usage).| 4980 4981**Return value** 4982 4983| Type | Description | 4984| ------------------------------------------------------------ | ------------------------- | 4985| [AudioDeviceDescriptors](arkts-apis-audio-t.md#audiodevicedescriptors) | Device list.| 4986 4987**Error codes** 4988 4989For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 4990 4991| ID| Error Message| 4992| ------- | --------------------------------------------| 4993| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 4994| 6800101 | Parameter verification failed. | 4995 4996**Example** 4997 4998```ts 4999import { BusinessError } from '@kit.BasicServicesKit'; 5000 5001try { 5002 let data: audio.AudioDeviceDescriptors = audioRoutingManager.getAvailableDevices(audio.DeviceUsage.MEDIA_OUTPUT_DEVICES); 5003 console.info(`Indicate that the device list is obtained ${data}`); 5004} catch (err) { 5005 let error = err as BusinessError; 5006 console.error(`Failed to obtain the device list. ${error}`); 5007} 5008``` 5009 5010### on('availableDeviceChange')<sup>12+</sup> 5011 5012on(type: 'availableDeviceChange', deviceUsage: DeviceUsage, callback: Callback<DeviceChangeAction\>): void 5013 5014Subscribes to the event indicating that the connection status of an available audio device is changed. This API uses an asynchronous callback to return the result. 5015 5016**System capability**: SystemCapability.Multimedia.Audio.Device 5017 5018**Parameters** 5019 5020| Name | Type | Mandatory| Description | 5021| :------- | :--------------------------------------------------- | :--- | :----------------------------------------- | 5022| type | string | Yes | Event type. The event **'availableDeviceChange'** is triggered when the connection status of available audio devices is changed.| 5023| deviceUsage | [DeviceUsage](#deviceusage12) | Yes | Audio device type (classified by usage). | 5024| callback | Callback<[DeviceChangeAction](#devicechangeaction)\> | Yes | Callback used to return the device change details.| 5025 5026**Error codes** 5027 5028For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 5029 5030| ID| Error Message| 5031| ------- | --------------------------------------------| 5032| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 5033| 6800101 | Parameter verification failed. | 5034 5035**Example** 5036 5037```ts 5038audioRoutingManager.on('availableDeviceChange', audio.DeviceUsage.MEDIA_OUTPUT_DEVICES, (deviceChanged: audio.DeviceChangeAction) => { 5039 console.info('device change type : ' + deviceChanged.type); 5040 console.info('device descriptor size : ' + deviceChanged.deviceDescriptors.length); 5041 console.info('device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceRole); 5042 console.info('device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceType); 5043}); 5044``` 5045 5046### off('availableDeviceChange')<sup>12+</sup> 5047 5048off(type: 'availableDeviceChange', callback?: Callback<DeviceChangeAction\>): void 5049 5050Unsubscribes from the event indicating that the connection status of an available audio device is changed. This API uses an asynchronous callback to return the result. 5051 5052**System capability**: SystemCapability.Multimedia.Audio.Device 5053 5054**Parameters** 5055 5056| Name | Type | Mandatory| Description | 5057| -------- | --------------------------------------------------- | ---- | ------------------------------------------ | 5058| type | string | Yes | Event type. The event **'availableDeviceChange'** is triggered when the connection status of available audio devices is changed.| 5059| callback | Callback<[DeviceChangeAction](#devicechangeaction)> | No | Callback used to return the available device change details.| 5060 5061**Error codes** 5062 5063For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 5064 5065| ID| Error Message| 5066| ------- | --------------------------------------------| 5067| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 5068| 6800101 | Parameter verification failed. | 5069 5070**Example** 5071 5072```ts 5073// Cancel all subscriptions to the event. 5074audioRoutingManager.off('availableDeviceChange'); 5075 5076// For the same event, if the callback parameter passed to the off API is the same as that passed to the on API, the off API cancels the subscription registered with the specified callback parameter. 5077let availableDeviceChangeCallback = (deviceChanged: audio.DeviceChangeAction) => { 5078 console.info('device change type : ' + deviceChanged.type); 5079 console.info('device descriptor size : ' + deviceChanged.deviceDescriptors.length); 5080 console.info('device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceRole); 5081 console.info('device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceType); 5082}; 5083 5084audioRoutingManager.on('availableDeviceChange', audio.DeviceUsage.MEDIA_OUTPUT_DEVICES, availableDeviceChangeCallback); 5085 5086audioRoutingManager.off('availableDeviceChange', availableDeviceChangeCallback); 5087``` 5088 5089### setCommunicationDevice<sup>9+</sup> 5090 5091setCommunicationDevice(deviceType: CommunicationDeviceType, active: boolean): Promise<void> 5092 5093Sets a communication device to the active state. This API uses a promise to return the result. 5094 5095This API will be deprecated in a later version due to function design is changed. You are not advised to use it. 5096 5097You are advised to use the [AVCastPicker component](../../media/avsession/using-switch-call-devices.md) provided by AVSession to switch between call devices. 5098 5099**System capability**: SystemCapability.Multimedia.Audio.Communication 5100 5101**Parameters** 5102 5103| Name | Type | Mandatory| Description | 5104| ---------- | ----------------------------------------------------- | ---- | ------------------ | 5105| deviceType | [CommunicationDeviceType](#communicationdevicetype9) | Yes | Active audio device type.| 5106| active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite. | 5107 5108**Return value** 5109 5110| Type | Description | 5111| ------------------- | ------------------------------- | 5112| Promise<void> | Promise that returns no value.| 5113 5114**Example** 5115 5116```ts 5117audioRoutingManager.setCommunicationDevice(audio.CommunicationDeviceType.SPEAKER, true).then(() => { 5118 console.info('Promise returned to indicate that the device is set to the active status.'); 5119}); 5120``` 5121 5122### isCommunicationDeviceActive<sup>9+</sup> 5123 5124isCommunicationDeviceActive(deviceType: CommunicationDeviceType, callback: AsyncCallback<boolean>): void 5125 5126Checks whether a communication device is active. This API uses an asynchronous callback to return the result. 5127 5128**System capability**: SystemCapability.Multimedia.Audio.Communication 5129 5130**Parameters** 5131 5132| Name | Type | Mandatory| Description | 5133| ---------- | ---------------------------------------------------- | ---- | ------------------------ | 5134| deviceType | [CommunicationDeviceType](#communicationdevicetype9) | Yes | Active audio device type. | 5135| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is **true** if the device is active or **false** if not active; otherwise, **err** is an error object.| 5136 5137**Example** 5138 5139```ts 5140import { BusinessError } from '@kit.BasicServicesKit'; 5141 5142audioRoutingManager.isCommunicationDeviceActive(audio.CommunicationDeviceType.SPEAKER, (err: BusinessError, value: boolean) => { 5143 if (err) { 5144 console.error(`Failed to obtain the active status of the device. ${err}`); 5145 return; 5146 } 5147 console.info('Callback invoked to indicate that the active status of the device is obtained.'); 5148}); 5149``` 5150 5151### isCommunicationDeviceActive<sup>9+</sup> 5152 5153isCommunicationDeviceActive(deviceType: CommunicationDeviceType): Promise<boolean> 5154 5155Checks whether a communication device is active. This API uses a promise to return the result. 5156 5157**System capability**: SystemCapability.Multimedia.Audio.Communication 5158 5159**Parameters** 5160 5161| Name | Type | Mandatory| Description | 5162| ---------- | ---------------------------------------------------- | ---- | ------------------ | 5163| deviceType | [CommunicationDeviceType](#communicationdevicetype9) | Yes | Active audio device type.| 5164 5165**Return value** 5166 5167| Type | Description | 5168| ---------------------- | ------------------------------- | 5169| Promise<boolean> | Promise used to return the result. The value **true** means that the device is active, and **false** means the opposite.| 5170 5171**Example** 5172 5173```ts 5174audioRoutingManager.isCommunicationDeviceActive(audio.CommunicationDeviceType.SPEAKER).then((value: boolean) => { 5175 console.info(`Promise returned to indicate that the active status of the device is obtained ${value}.`); 5176}); 5177``` 5178 5179### isCommunicationDeviceActiveSync<sup>10+</sup> 5180 5181isCommunicationDeviceActiveSync(deviceType: CommunicationDeviceType): boolean 5182 5183Checks whether a communication device is active. This API returns the result synchronously. 5184 5185**System capability**: SystemCapability.Multimedia.Audio.Communication 5186 5187**Parameters** 5188 5189| Name | Type | Mandatory| Description | 5190| ---------- | ---------------------------------------------------- | ---- | ------------------ | 5191| deviceType | [CommunicationDeviceType](#communicationdevicetype9) | Yes | Active audio device type.| 5192 5193**Return value** 5194 5195| Type | Description | 5196| ---------------------- | ------------------------------- | 5197| boolean | Check result. The value **true** means that the device is active, and **false** means the opposite.| 5198 5199**Error codes** 5200 5201For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 5202 5203| ID| Error Message| 5204| ------- | --------------------------------------------| 5205| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 5206| 6800101 | Parameter verification failed. | 5207 5208**Example** 5209 5210```ts 5211import { BusinessError } from '@kit.BasicServicesKit'; 5212 5213try { 5214 let value: boolean = audioRoutingManager.isCommunicationDeviceActiveSync(audio.CommunicationDeviceType.SPEAKER); 5215 console.info(`Indicate that the active status of the device is obtained ${value}.`); 5216} catch (err) { 5217 let error = err as BusinessError; 5218 console.error(`Failed to obtain the active status of the device ${error}.`); 5219} 5220``` 5221 5222### getPreferOutputDeviceForRendererInfo<sup>10+</sup> 5223 5224getPreferOutputDeviceForRendererInfo(rendererInfo: AudioRendererInfo, callback: AsyncCallback<AudioDeviceDescriptors>): void 5225 5226Obtains the output device with the highest priority based on the audio renderer information. This API uses an asynchronous callback to return the result. 5227 5228**System capability**: SystemCapability.Multimedia.Audio.Device 5229 5230**Parameters** 5231 5232| Name | Type | Mandatory| Description | 5233| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | 5234| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | Yes | Audio renderer information. | 5235| callback | AsyncCallback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the output device with the highest priority obtained; otherwise, **err** is an error object.| 5236 5237**Error codes** 5238 5239For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 5240 5241| ID| Error Message | 5242| ------- |--------------------------------------------------| 5243| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 5244| 6800101 | Parameter verification failed. Return by callback. | 5245| 6800301 | System error. Return by callback. | 5246 5247**Example** 5248```ts 5249import { audio } from '@kit.AudioKit'; 5250import { BusinessError } from '@kit.BasicServicesKit'; 5251 5252let rendererInfo: audio.AudioRendererInfo = { 5253 usage: audio.StreamUsage.STREAM_USAGE_MUSIC, // Audio stream usage type: music. Set this parameter based on the service scenario. 5254 rendererFlags: 0 // AudioRenderer flag. 5255}; 5256 5257async function getPreferOutputDevice() { 5258 audioRoutingManager.getPreferOutputDeviceForRendererInfo(rendererInfo, (err: BusinessError, desc: audio.AudioDeviceDescriptors) => { 5259 if (err) { 5260 console.error(`Result ERROR: ${err}`); 5261 } else { 5262 console.info(`device descriptor: ${desc}`); 5263 } 5264 }); 5265} 5266``` 5267 5268### getPreferOutputDeviceForRendererInfo<sup>10+</sup> 5269getPreferOutputDeviceForRendererInfo(rendererInfo: AudioRendererInfo): Promise<AudioDeviceDescriptors> 5270 5271Obtains the output device with the highest priority based on the audio renderer information. This API uses a promise to return the result. 5272 5273**System capability**: SystemCapability.Multimedia.Audio.Device 5274 5275**Parameters** 5276 5277| Name | Type | Mandatory| Description | 5278| ----------------------| ------------------------------------------------------------ | ---- | ------------------------- | 5279| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | Yes | Audio renderer information. | 5280 5281**Return value** 5282 5283| Type | Description | 5284| --------------------- | --------------------------- | 5285| Promise<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Promise used to return the information about the output device with the highest priority.| 5286 5287**Error codes** 5288 5289For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 5290 5291| ID| Error Message | 5292| ------- |-------------------------------------------------| 5293| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 5294| 6800101 | Parameter verification failed. Return by promise. | 5295| 6800301 | System error. Return by promise. | 5296 5297**Example** 5298 5299```ts 5300import { audio } from '@kit.AudioKit'; 5301import { BusinessError } from '@kit.BasicServicesKit'; 5302 5303let rendererInfo: audio.AudioRendererInfo = { 5304 usage: audio.StreamUsage.STREAM_USAGE_MUSIC, // Audio stream usage type: music. Set this parameter based on the service scenario. 5305 rendererFlags: 0 // AudioRenderer flag. 5306}; 5307 5308async function getPreferOutputDevice() { 5309 audioRoutingManager.getPreferOutputDeviceForRendererInfo(rendererInfo).then((desc: audio.AudioDeviceDescriptors) => { 5310 console.info(`device descriptor: ${desc}`); 5311 }).catch((err: BusinessError) => { 5312 console.error(`Result ERROR: ${err}`); 5313 }) 5314} 5315``` 5316 5317### getPreferredOutputDeviceForRendererInfoSync<sup>10+</sup> 5318getPreferredOutputDeviceForRendererInfoSync(rendererInfo: AudioRendererInfo): AudioDeviceDescriptors 5319 5320Obtains the output device with the highest priority based on the audio renderer information. This API returns the result synchronously. 5321 5322**System capability**: SystemCapability.Multimedia.Audio.Device 5323 5324**Parameters** 5325 5326| Name | Type | Mandatory| Description | 5327| ----------------------| ------------------------------------------------------------ | ---- | ------------------------- | 5328| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | Yes | Audio renderer information. | 5329 5330**Return value** 5331 5332| Type | Description | 5333| --------------------- | --------------------------- | 5334| [AudioDeviceDescriptors](#audiodevicedescriptors) | Information about the output device with the highest priority.| 5335 5336**Error codes** 5337 5338For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 5339 5340| ID| Error Message | 5341| ------- |--------------------------| 5342| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 5343| 6800101 | Parameter verification failed. | 5344 5345**Example** 5346 5347```ts 5348import { audio } from '@kit.AudioKit'; 5349import { BusinessError } from '@kit.BasicServicesKit'; 5350 5351let rendererInfo: audio.AudioRendererInfo = { 5352 usage: audio.StreamUsage.STREAM_USAGE_MUSIC, // Audio stream usage type: music. Set this parameter based on the service scenario. 5353 rendererFlags: 0 // AudioRenderer flag. 5354}; 5355 5356try { 5357 let desc: audio.AudioDeviceDescriptors = audioRoutingManager.getPreferredOutputDeviceForRendererInfoSync(rendererInfo); 5358 console.info(`device descriptor: ${desc}`); 5359} catch (err) { 5360 let error = err as BusinessError; 5361 console.error(`Result ERROR: ${error}`); 5362} 5363``` 5364 5365### on('preferOutputDeviceChangeForRendererInfo')<sup>10+</sup> 5366 5367on(type: 'preferOutputDeviceChangeForRendererInfo', rendererInfo: AudioRendererInfo, callback: Callback<AudioDeviceDescriptors\>): void 5368 5369Subscribes to the change event of the output device with the highest priority, which is triggered when the output device with the highest priority is changed. This API uses an asynchronous callback to return the result. 5370 5371**System capability**: SystemCapability.Multimedia.Audio.Device 5372 5373**Parameters** 5374 5375| Name | Type | Mandatory| Description | 5376| :------- | :--------------------------------------------------- | :--- |:--------------------------------------------------------| 5377| type | string | Yes | Event type. The event **'preferOutputDeviceChangeForRendererInfo'** is triggered when the output device with the highest priority is changed.| 5378| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | Yes | Audio renderer information. | 5379| callback | Callback<[AudioDeviceDescriptors](#audiodevicedescriptors)\> | Yes | Callback used to return the information about the output device with the highest priority.| 5380 5381**Error codes** 5382 5383For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 5384 5385| ID| Error Message| 5386| ------- | --------------------------------------------| 5387| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 5388| 6800101 | Parameter verification failed. | 5389 5390**Example** 5391 5392```ts 5393import { audio } from '@kit.AudioKit'; 5394 5395let rendererInfo: audio.AudioRendererInfo = { 5396 usage: audio.StreamUsage.STREAM_USAGE_MUSIC, // Audio stream usage type: music. Set this parameter based on the service scenario. 5397 rendererFlags: 0 // AudioRenderer flag. 5398}; 5399 5400audioRoutingManager.on('preferOutputDeviceChangeForRendererInfo', rendererInfo, (desc: audio.AudioDeviceDescriptors) => { 5401 console.info(`device descriptor: ${desc}`); 5402}); 5403``` 5404 5405### off('preferOutputDeviceChangeForRendererInfo')<sup>10+</sup> 5406 5407off(type: 'preferOutputDeviceChangeForRendererInfo', callback?: Callback<AudioDeviceDescriptors\>): void 5408 5409Unsubscribes from the change event of the output device with the highest priority. This API uses an asynchronous callback to return the result. 5410 5411**System capability**: SystemCapability.Multimedia.Audio.Device 5412 5413**Parameters** 5414 5415| Name | Type | Mandatory| Description | 5416| -------- | --------------------------------------------------- | ---- | ------------------------------------------ | 5417| type | string | Yes | Event type. The event **'preferOutputDeviceChangeForRendererInfo'** is triggered when the output device with the highest priority is changed.| 5418| callback | Callback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | No | Callback used to return the information about the output device with the highest priority.| 5419 5420**Error codes** 5421 5422For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 5423 5424| ID| Error Message| 5425| ------- | --------------------------------------------| 5426| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 5427| 6800101 | Parameter verification failed. | 5428 5429**Example** 5430 5431```ts 5432// Cancel all subscriptions to the event. 5433audioRoutingManager.off('preferOutputDeviceChangeForRendererInfo'); 5434 5435// For the same event, if the callback parameter passed to the off API is the same as that passed to the on API, the off API cancels the subscription registered with the specified callback parameter. 5436let preferOutputDeviceChangeForRendererInfoCallback = (desc: audio.AudioDeviceDescriptors) => { 5437 console.info(`device descriptor: ${desc}`); 5438}; 5439let rendererInfo: audio.AudioRendererInfo = { 5440 usage: audio.StreamUsage.STREAM_USAGE_MUSIC, // Audio stream usage type: music. Set this parameter based on the service scenario. 5441 rendererFlags: 0 // AudioRenderer flag. 5442}; 5443 5444audioRoutingManager.on('preferOutputDeviceChangeForRendererInfo', rendererInfo, preferOutputDeviceChangeForRendererInfoCallback); 5445 5446audioRoutingManager.off('preferOutputDeviceChangeForRendererInfo', preferOutputDeviceChangeForRendererInfoCallback); 5447``` 5448 5449### getPreferredInputDeviceForCapturerInfo<sup>10+</sup> 5450 5451getPreferredInputDeviceForCapturerInfo(capturerInfo: AudioCapturerInfo, callback: AsyncCallback<AudioDeviceDescriptors>): void 5452 5453Obtains the input device with the highest priority based on the audio capturer information. This API uses an asynchronous callback to return the result. 5454 5455**System capability**: SystemCapability.Multimedia.Audio.Device 5456 5457**Parameters** 5458 5459| Name | Type | Mandatory| Description | 5460| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | 5461| capturerInfo | [AudioCapturerInfo](#audiocapturerinfo8) | Yes | Audio capturer information. | 5462| callback | AsyncCallback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the input device with the highest priority obtained; otherwise, **err** is an error object.| 5463 5464**Error codes** 5465 5466For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 5467 5468| ID| Error Message| 5469| ------- | --------------------------------------------| 5470| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 5471| 6800101 | Parameter verification failed. Return by callback.| 5472| 6800301 | System error. Return by callback. | 5473 5474**Example** 5475```ts 5476import { audio } from '@kit.AudioKit'; 5477import { BusinessError } from '@kit.BasicServicesKit'; 5478 5479let capturerInfo: audio.AudioCapturerInfo = { 5480 source: audio.SourceType.SOURCE_TYPE_MIC, // Audio source type: microphone. Set this parameter based on the service scenario. 5481 capturerFlags: 0 // AudioCapturer flag. 5482}; 5483 5484audioRoutingManager.getPreferredInputDeviceForCapturerInfo(capturerInfo, (err: BusinessError, desc: audio.AudioDeviceDescriptors) => { 5485 if (err) { 5486 console.error(`Result ERROR: ${err}`); 5487 } else { 5488 console.info(`device descriptor: ${desc}`); 5489 } 5490}); 5491``` 5492 5493### getPreferredInputDeviceForCapturerInfo<sup>10+</sup> 5494 5495getPreferredInputDeviceForCapturerInfo(capturerInfo: AudioCapturerInfo): Promise<AudioDeviceDescriptors> 5496 5497Obtains the input device with the highest priority based on the audio capturer information. This API uses a promise to return the result. 5498 5499**System capability**: SystemCapability.Multimedia.Audio.Device 5500 5501**Parameters** 5502 5503| Name | Type | Mandatory| Description | 5504| ----------------------| ------------------------------------------------------------ | ---- | ------------------------- | 5505| capturerInfo | [AudioCapturerInfo](#audiocapturerinfo8) | Yes | Audio capturer information. | 5506 5507**Return value** 5508 5509| Type | Description | 5510| --------------------- | --------------------------- | 5511| Promise<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Promise used to return the information about the input device with the highest priority.| 5512 5513**Error codes** 5514 5515For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 5516 5517| ID| Error Message| 5518| ------- | --------------------------------------------| 5519| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 5520| 6800101 | Parameter verification failed. Return by promise. | 5521| 6800301 | System error. Return by promise. | 5522 5523**Example** 5524 5525```ts 5526import { audio } from '@kit.AudioKit'; 5527import { BusinessError } from '@kit.BasicServicesKit'; 5528 5529let capturerInfo: audio.AudioCapturerInfo = { 5530 source: audio.SourceType.SOURCE_TYPE_MIC, // Audio source type: microphone. Set this parameter based on the service scenario. 5531 capturerFlags: 0 // AudioCapturer flag. 5532}; 5533 5534audioRoutingManager.getPreferredInputDeviceForCapturerInfo(capturerInfo).then((desc: audio.AudioDeviceDescriptors) => { 5535 console.info(`device descriptor: ${desc}`); 5536}).catch((err: BusinessError) => { 5537 console.error(`Result ERROR: ${err}`); 5538}); 5539``` 5540 5541### getPreferredInputDeviceForCapturerInfoSync<sup>10+</sup> 5542 5543getPreferredInputDeviceForCapturerInfoSync(capturerInfo: AudioCapturerInfo): AudioDeviceDescriptors 5544 5545Obtains the input device with the highest priority based on the audio capturer information. This API returns the result synchronously. 5546 5547**System capability**: SystemCapability.Multimedia.Audio.Device 5548 5549**Parameters** 5550 5551| Name | Type | Mandatory| Description | 5552| ----------------------| ------------------------------------------------------------ | ---- | ------------------------- | 5553| capturerInfo | [AudioCapturerInfo](#audiocapturerinfo8) | Yes | Audio capturer information. | 5554 5555**Return value** 5556 5557| Type | Description | 5558| --------------------- | --------------------------- | 5559| [AudioDeviceDescriptors](#audiodevicedescriptors) | Information about the input device with the highest priority.| 5560 5561**Error codes** 5562 5563For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 5564 5565| ID| Error Message| 5566| ------- | --------------------------------------------| 5567| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 5568| 6800101 | Parameter verification failed. | 5569 5570**Example** 5571 5572```ts 5573import { audio } from '@kit.AudioKit'; 5574import { BusinessError } from '@kit.BasicServicesKit'; 5575 5576let capturerInfo: audio.AudioCapturerInfo = { 5577 source: audio.SourceType.SOURCE_TYPE_MIC, // Audio source type: microphone. Set this parameter based on the service scenario. 5578 capturerFlags: 0 // AudioCapturer flag. 5579}; 5580 5581try { 5582 let desc: audio.AudioDeviceDescriptors = audioRoutingManager.getPreferredInputDeviceForCapturerInfoSync(capturerInfo); 5583 console.info(`device descriptor: ${desc}`); 5584} catch (err) { 5585 let error = err as BusinessError; 5586 console.error(`Result ERROR: ${error}`); 5587} 5588``` 5589 5590### on('preferredInputDeviceChangeForCapturerInfo')<sup>10+</sup> 5591 5592on(type: 'preferredInputDeviceChangeForCapturerInfo', capturerInfo: AudioCapturerInfo, callback: Callback<AudioDeviceDescriptors\>): void 5593 5594Subscribes to the change event of the input device with the highest priority, which is triggered when the input device with the highest priority is changed. This API uses an asynchronous callback to return the result. 5595 5596**System capability**: SystemCapability.Multimedia.Audio.Device 5597 5598**Parameters** 5599 5600| Name | Type | Mandatory| Description | 5601| :------- | :--------------------------------------------------- | :--- | :----------------------------------------- | 5602| type | string | Yes | Event type. The event **'preferredInputDeviceChangeForCapturerInfo'** is triggered when the input device with the highest priority is changed.| 5603| capturerInfo | [AudioCapturerInfo](#audiocapturerinfo8) | Yes | Audio capturer information. | 5604| callback | Callback<[AudioDeviceDescriptors](#audiodevicedescriptors)\> | Yes | Callback used to return the information about the input device with the highest priority.| 5605 5606**Error codes** 5607 5608For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 5609 5610| ID| Error Message| 5611| ------- | --------------------------------------------| 5612| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 5613| 6800101 | Parameter verification failed. | 5614 5615**Example** 5616 5617```ts 5618import { audio } from '@kit.AudioKit'; 5619 5620let capturerInfo: audio.AudioCapturerInfo = { 5621 source: audio.SourceType.SOURCE_TYPE_MIC, // Audio source type: microphone. Set this parameter based on the service scenario. 5622 capturerFlags: 0 // AudioCapturer flag. 5623}; 5624 5625audioRoutingManager.on('preferredInputDeviceChangeForCapturerInfo', capturerInfo, (desc: audio.AudioDeviceDescriptors) => { 5626 console.info(`device descriptor: ${desc}`); 5627}); 5628``` 5629 5630### off('preferredInputDeviceChangeForCapturerInfo')<sup>10+</sup> 5631 5632off(type: 'preferredInputDeviceChangeForCapturerInfo', callback?: Callback<AudioDeviceDescriptors\>): void 5633 5634Unsubscribes from the change event of the input device with the highest priority. This API uses an asynchronous callback to return the result. 5635 5636**System capability**: SystemCapability.Multimedia.Audio.Device 5637 5638**Parameters** 5639 5640| Name | Type | Mandatory| Description | 5641| -------- | --------------------------------------------------- | ---- | ------------------------------------------ | 5642| type | string | Yes | Event type. The event **'preferredInputDeviceChangeForCapturerInfo'** is triggered when the input device with the highest priority is changed.| 5643| callback | Callback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | No | Callback used to return the information about the input device with the highest priority.| 5644 5645**Error codes** 5646 5647For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 5648 5649| ID| Error Message| 5650| ------- | --------------------------------------------| 5651| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 5652| 6800101 | Parameter verification failed. | 5653 5654**Example** 5655 5656```ts 5657// Cancel all subscriptions to the event. 5658audioRoutingManager.off('preferredInputDeviceChangeForCapturerInfo'); 5659 5660// For the same event, if the callback parameter passed to the off API is the same as that passed to the on API, the off API cancels the subscription registered with the specified callback parameter. 5661let preferredInputDeviceChangeForCapturerInfoCallback = (desc: audio.AudioDeviceDescriptors) => { 5662 console.info(`device descriptor: ${desc}`); 5663}; 5664let capturerInfo: audio.AudioCapturerInfo = { 5665 source: audio.SourceType.SOURCE_TYPE_MIC, // Audio source type: microphone. Set this parameter based on the service scenario. 5666 capturerFlags: 0 // AudioCapturer flag. 5667}; 5668 5669audioRoutingManager.on('preferredInputDeviceChangeForCapturerInfo', capturerInfo, preferredInputDeviceChangeForCapturerInfoCallback); 5670 5671audioRoutingManager.off('preferredInputDeviceChangeForCapturerInfo', preferredInputDeviceChangeForCapturerInfoCallback); 5672``` 5673 5674## AudioSessionManager<sup>12+</sup> 5675 5676Manages audio sessions. 5677 5678Before calling any API in AudioSessionManager, you must use [getSessionManager](#getsessionmanager12) to obtain an AudioSessionManager instance. 5679 5680### activateAudioSession<sup>12+</sup> 5681 5682activateAudioSession(strategy: AudioSessionStrategy): Promise\<void> 5683 5684Activates an audio session. This API uses a promise to return the result. 5685 5686**System capability**: SystemCapability.Multimedia.Audio.Core 5687 5688**Parameters** 5689 5690| Name| Type | Mandatory| Description | 5691| ------ |-------------------------------------------------| ---- | ------------ | 5692| strategy | [AudioSessionStrategy](#audiosessionstrategy12) | Yes | Audio session strategy.| 5693 5694**Return value** 5695 5696| Type | Description | 5697| -------------- | ------------------------- | 5698| Promise\<void> | Promise that returns no value.| 5699 5700**Error codes** 5701 5702For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 5703 5704| ID| Error Message| 5705| ------- | ---------------------------------------------| 5706| 401 | Parameter error. Possible causes: 1.Mandatory parameters unspecified. 2.Incorrect parameter types. | 5707| 6800101 | Parameter verification failed.| 5708| 6800301 | System error. Returned by promise. | 5709 5710**Example** 5711 5712```ts 5713import { BusinessError } from '@kit.BasicServicesKit'; 5714 5715let strategy: audio.AudioSessionStrategy = { 5716 concurrencyMode: audio.AudioConcurrencyMode.CONCURRENCY_MIX_WITH_OTHERS 5717}; 5718 5719audioSessionManager.activateAudioSession(strategy).then(() => { 5720 console.info('activateAudioSession SUCCESS'); 5721}).catch((err: BusinessError) => { 5722 console.error(`ERROR: ${err}`); 5723}); 5724``` 5725 5726### deactivateAudioSession<sup>12+</sup> 5727 5728deactivateAudioSession(): Promise\<void> 5729 5730Deactivates this audio session. This API uses a promise to return the result. 5731 5732**System capability**: SystemCapability.Multimedia.Audio.Core 5733 5734**Return value** 5735 5736| Type | Description | 5737| -------------- | ------------------------- | 5738| Promise\<void> | Promise that returns no value.| 5739 5740**Error codes** 5741 5742For details about the error codes, see [Audio Error Codes](errorcode-audio.md). 5743 5744| ID| Error Message| 5745| ------- | ---------------------------------------------| 5746| 6800301 | System error. Returned by promise. | 5747 5748**Example** 5749 5750```ts 5751import { BusinessError } from '@kit.BasicServicesKit'; 5752 5753audioSessionManager.deactivateAudioSession().then(() => { 5754 console.info('deactivateAudioSession SUCCESS'); 5755}).catch((err: BusinessError) => { 5756 console.error(`ERROR: ${err}`); 5757}); 5758``` 5759 5760### isAudioSessionActivated<sup>12+</sup> 5761 5762isAudioSessionActivated(): boolean 5763 5764Checks whether this audio session is activated. 5765 5766**System capability**: SystemCapability.Multimedia.Audio.Core 5767 5768**Return value** 5769 5770| Type | Description | 5771| ------------------------------------------------- |---------------------------------------| 5772| boolean | Check result. The value **true** means that the audio session is activated, and **false** means the opposite.| 5773 5774**Example** 5775 5776```ts 5777let isActivated = audioSessionManager.isAudioSessionActivated(); 5778``` 5779 5780### on('audioSessionDeactivated')<sup>12+</sup> 5781 5782on(type: 'audioSessionDeactivated', callback: Callback\<AudioSessionDeactivatedEvent>): void 5783 5784Subscribes to the audio session deactivation event, which is triggered when an audio session is deactivated. This API uses an asynchronous callback to return the result. 5785 5786**System capability**: SystemCapability.Multimedia.Audio.Core 5787 5788**Parameters** 5789 5790| Name | Type | Mandatory| Description | 5791| -------- |---------------------------------------------------------------------------| ---- | ------------------------------------------------------------ | 5792| type | string | Yes | Event type. The event **'audioSessionDeactivated'** is triggered when the audio session is deactivated.| 5793| callback | Callback<[AudioSessionDeactivatedEvent](#audiosessiondeactivatedevent12)> | Yes | Callback used to return the reason why the audio session is deactivated.| 5794 5795**Error codes** 5796 5797For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 5798 5799| ID| Error Message| 5800| ------- | --------------------------------------------| 5801| 401 | Parameter error. Possible causes: 1.Mandatory parameters unspecified. 2.Incorrect parameter types. | 5802| 6800101 | Parameter verification failed. | 5803 5804**Example** 5805 5806```ts 5807audioSessionManager.on('audioSessionDeactivated', (audioSessionDeactivatedEvent: audio.AudioSessionDeactivatedEvent) => { 5808 console.info(`reason of audioSessionDeactivated: ${audioSessionDeactivatedEvent.reason} `); 5809}); 5810``` 5811 5812### off('audioSessionDeactivated')<sup>12+</sup> 5813 5814off(type: 'audioSessionDeactivated', callback?: Callback\<AudioSessionDeactivatedEvent>): void 5815 5816Unsubscribes from the audio session deactivation event. This API uses an asynchronous callback to return the result. 5817 5818**System capability**: SystemCapability.Multimedia.Audio.Core 5819 5820**Parameters** 5821 5822| Name | Type | Mandatory| Description | 5823| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | 5824| type | string | Yes | Event type. The event **'audioSessionDeactivated'** is triggered when the audio session is deactivated.| 5825| callback |Callback<[AudioSessionDeactivatedEvent](#audiosessiondeactivatedevent12)> | No | Callback used to return the reason why the audio session is deactivated.| 5826 5827**Error codes** 5828 5829For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 5830 5831| ID| Error Message| 5832| ------- | --------------------------------------------| 5833| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 5834| 6800101 | Parameter verification failed. | 5835 5836**Example** 5837 5838```ts 5839// Cancel all subscriptions to the event. 5840audioSessionManager.off('audioSessionDeactivated'); 5841 5842// For the same event, if the callback parameter passed to the off API is the same as that passed to the on API, the off API cancels the subscription registered with the specified callback parameter. 5843let audioSessionDeactivatedCallback = (audioSessionDeactivatedEvent: audio.AudioSessionDeactivatedEvent) => { 5844 console.info(`reason of audioSessionDeactivated: ${audioSessionDeactivatedEvent.reason} `); 5845}; 5846 5847audioSessionManager.on('audioSessionDeactivated', audioSessionDeactivatedCallback); 5848 5849audioSessionManager.off('audioSessionDeactivated', audioSessionDeactivatedCallback); 5850``` 5851 5852## AudioSpatializationManager<sup>18+</sup> 5853 5854Implements spatial audio management. 5855 5856Before calling any API in AudioSpatializationManager, you must use [getSpatializationManager](#getspatializationmanager18) to obtain an AudioSpatializationManager instance. 5857 5858### isSpatializationEnabledForCurrentDevice<sup>18+</sup> 5859 5860isSpatializationEnabledForCurrentDevice(): boolean 5861 5862Checks whether spatial audio rendering is enabled for the current device. This API returns the result synchronously. 5863 5864**System capability**: SystemCapability.Multimedia.Audio.Spatialization 5865 5866**Return value** 5867 5868| Type | Description | 5869| ---------------------- | ------------------------------------------------------------ | 5870| boolean | Check result. The value **true** means that spatial audio rendering is enabled, and **false** means the opposite.| 5871 5872**Example** 5873 5874```ts 5875import { audio } from '@kit.AudioKit'; 5876 5877let isSpatializationEnabledForCurrentDevice: boolean = audioSpatializationManager.isSpatializationEnabledForCurrentDevice(); 5878console.info(`AudioSpatializationManager isSpatializationEnabledForCurrentDevice: ${isSpatializationEnabledForCurrentDevice}`); 5879``` 5880 5881### on('spatializationEnabledChangeForCurrentDevice')<sup>18+</sup> 5882 5883on(type: 'spatializationEnabledChangeForCurrentDevice', callback: Callback<boolean\>): void 5884 5885Subscribes to the spatial audio rendering status change event of the current device. This API uses an asynchronous callback to return the result. 5886 5887**System capability**: SystemCapability.Multimedia.Audio.Spatialization 5888 5889**Parameters** 5890 5891| Name | Type | Mandatory| Description | 5892| :------- | :--------------------------------------------------- | :--- |:---------------------------------------------| 5893| type | string | Yes | Event type. The event **'spatializationEnabledChangeForCurrentDevice'** is triggered when the spatial audio rendering status is changed.| 5894| callback | Callback<boolean\> | Yes | Callback used to return the result. The value **true** means that spatial audio rendering is enabled, and **false** means the opposite. | 5895 5896**Error codes** 5897 5898For details about the error codes, see [Audio Error Codes](errorcode-audio.md). 5899 5900| ID| Error Message| 5901| ------- | --------------------------------------------| 5902| 6800101 | Parameter verification failed. | 5903 5904**Example** 5905 5906```ts 5907import { audio } from '@kit.AudioKit'; 5908 5909audioSpatializationManager.on('spatializationEnabledChangeForCurrentDevice', (isSpatializationEnabledForCurrentDevice: boolean) => { 5910 console.info(`isSpatializationEnabledForCurrentDevice: ${isSpatializationEnabledForCurrentDevice}`); 5911}); 5912``` 5913 5914### off('spatializationEnabledChangeForCurrentDevice')<sup>18+</sup> 5915 5916off(type: 'spatializationEnabledChangeForCurrentDevice', callback?: Callback<boolean\>): void 5917 5918Unsubscribes from the spatial audio rendering status change event of the current device. This API uses an asynchronous callback to return the result. 5919 5920**System capability**: SystemCapability.Multimedia.Audio.Spatialization 5921 5922**Parameters** 5923 5924| Name | Type | Mandatory| Description | 5925| -------- | --------------------------------------------------- | ---- | ------------------------------------------ | 5926| type | string | Yes | Event type. The event **'spatializationEnabledChangeForCurrentDevice'** is triggered when the spatial audio rendering status is changed.| 5927| callback | Callback<boolean\> | No | Callback used to return the result. The value **true** means that spatial audio rendering is enabled, and **false** means the opposite. | 5928 5929**Error codes** 5930 5931For details about the error codes, see [Audio Error Codes](errorcode-audio.md). 5932 5933| ID| Error Message| 5934| ------- | --------------------------------------------| 5935| 6800101 | Parameter verification failed. | 5936 5937**Example** 5938 5939```ts 5940import { audio } from '@kit.AudioKit'; 5941audioSpatializationManager.off('spatializationEnabledChangeForCurrentDevice'); 5942``` 5943 5944## AudioRendererChangeInfoArray<sup>9+</sup> 5945 5946type AudioRendererChangeInfoArray = Array<Readonly<AudioRendererChangeInfo>> 5947 5948Defines an **AudioRenderChangeInfo** array, which is read-only. 5949 5950**System capability**: SystemCapability.Multimedia.Audio.Renderer 5951 5952| Type | Description | 5953|---------|---------------------------------------------------------------| 5954| Array<Readonly<AudioRendererChangeInfo>> | Defines an [AudioRenderChangeInfo](#audiorendererchangeinfo9) array, which is read-only.| 5955 5956## AudioRendererChangeInfo<sup>9+</sup> 5957 5958Describes the audio renderer change event. 5959 5960**System capability**: SystemCapability.Multimedia.Audio.Renderer 5961 5962| Name | Type | Readable| Writable| Description | 5963| -------------------| ----------------------------------------- | ---- | ---- | ---------------------------- | 5964| streamId | number | Yes | No | Unique ID of an audio stream. | 5965| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | Yes | No | Audio renderer information. | 5966| deviceDescriptors | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | No | Audio device description.| 5967 5968**Example** 5969 5970```ts 5971import { audio } from '@kit.AudioKit'; 5972 5973const audioManager = audio.getAudioManager(); 5974let audioStreamManager = audioManager.getStreamManager(); 5975 5976audioStreamManager.on('audioRendererChange', (AudioRendererChangeInfoArray) => { 5977 for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { 5978 console.info(`## RendererChange on is called for ${i} ##`); 5979 console.info(`StreamId for ${i} is: ${AudioRendererChangeInfoArray[i].streamId}`); 5980 console.info(`Content for ${i} is: ${AudioRendererChangeInfoArray[i].rendererInfo.content}`); 5981 console.info(`Stream for ${i} is: ${AudioRendererChangeInfoArray[i].rendererInfo.usage}`); 5982 console.info(`Flag ${i} is: ${AudioRendererChangeInfoArray[i].rendererInfo.rendererFlags}`); 5983 let devDescriptor = AudioRendererChangeInfoArray[i].deviceDescriptors; 5984 for (let j = 0; j < AudioRendererChangeInfoArray[i].deviceDescriptors.length; j++) { 5985 console.info(`Id: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].id}`); 5986 console.info(`Type: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].deviceType}`); 5987 console.info(`Role: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); 5988 console.info(`Name: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].name}`); 5989 console.info(`Addr: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].address}`); 5990 console.info(`SR: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); 5991 console.info(`C ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); 5992 console.info(`CM: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].channelMasks[0]}`); 5993 } 5994 } 5995}); 5996``` 5997 5998 5999## AudioCapturerChangeInfoArray<sup>9+</sup> 6000 6001type AudioCapturerChangeInfoArray = Array<Readonly<AudioCapturerChangeInfo>> 6002 6003Defines an **AudioCapturerChangeInfo** array, which is read-only. 6004 6005**System capability**: SystemCapability.Multimedia.Audio.Capturer 6006 6007| Type | Description | 6008|---------|-----------------------------------------------------------------| 6009| Array<Readonly<AudioCapturerChangeInfo>> | An [AudioCapturerChangeInfo](#audiocapturerchangeinfo9) array, which is read-only.| 6010 6011## AudioCapturerChangeInfo<sup>9+</sup> 6012 6013Describes the audio capturer change event. 6014 6015**System capability**: SystemCapability.Multimedia.Audio.Capturer 6016 6017| Name | Type | Readable| Writable| Description | 6018| -------------------| ----------------------------------------- | ---- | ---- | ---------------------------- | 6019| streamId | number | Yes | No | Unique ID of an audio stream. | 6020| capturerInfo | [AudioCapturerInfo](#audiocapturerinfo8) | Yes | No | Audio capturer information. | 6021| deviceDescriptors | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | No | Audio device information.| 6022| muted<sup>11+</sup> | boolean | Yes | No | Whether the audio capturer is muted. The value **true** means that the audio capturer is muted, and **false** means the opposite.| 6023 6024**Example** 6025 6026```ts 6027import { audio } from '@kit.AudioKit'; 6028 6029const audioManager = audio.getAudioManager(); 6030let audioStreamManager = audioManager.getStreamManager(); 6031 6032audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) => { 6033 for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { 6034 console.info(`## CapChange on is called for element ${i} ##`); 6035 console.info(`StrId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); 6036 console.info(`Src for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); 6037 console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); 6038 let devDescriptor = AudioCapturerChangeInfoArray[i].deviceDescriptors; 6039 for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { 6040 console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); 6041 console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); 6042 console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); 6043 console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); 6044 console.info(`Addr: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); 6045 console.info(`SR: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); 6046 console.info(`C ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); 6047 console.info(`CM ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks[0]}`); 6048 } 6049 } 6050}); 6051``` 6052 6053## AudioEffectInfoArray<sup>10+</sup> 6054 6055type AudioEffectInfoArray = Array<Readonly<AudioEffectMode>> 6056 6057Defines an array that contains the audio effect mode corresponding to a specific audio content type (specified by **ContentType**) and audio stream usage (specified by **StreamUsage**). The [AudioEffectMode](#audioeffectmode10) array is read-only. 6058 6059**System capability**: SystemCapability.Multimedia.Audio.Renderer 6060 6061| Type | Description | 6062|---------|---------------------------------------------------------------| 6063| Array<Readonly<AudioEffectMode>> | Defines an array that contains the audio effect mode corresponding to a specific audio content type (specified by **ContentType**) and audio stream usage (specified by **StreamUsage**). The [AudioEffectMode](#audioeffectmode10) array is read-only.| 6064 6065## AudioDeviceDescriptors 6066 6067type AudioDeviceDescriptors = Array<Readonly<AudioDeviceDescriptor>> 6068 6069Defines an [AudioDeviceDescriptor](#audiodevicedescriptor) array, which is read-only. 6070 6071**Atomic service API**: This API can be used in atomic services since API version 12. 6072 6073**System capability**: SystemCapability.Multimedia.Audio.Device 6074 6075| Type | Description | 6076|---------|---------------------------------------------------------------| 6077| Array<Readonly<AudioDeviceDescriptor>> | Defines an [AudioDeviceDescriptor](#audiodevicedescriptor) array, which is read-only.| 6078 6079## AudioDeviceDescriptor 6080 6081Describes an audio device. 6082 6083| Name | Type | Readable| Writable| Description | 6084| ----------------------------- | -------------------------- | ---- | ---- | ---------- | 6085| deviceRole | [DeviceRole](#devicerole) | Yes | No | Device role.<br> **System capability**: SystemCapability.Multimedia.Audio.Device<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 6086| deviceType | [DeviceType](#devicetype) | Yes | No | Device type.<br> **System capability**: SystemCapability.Multimedia.Audio.Device<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 6087| id<sup>9+</sup> | number | Yes | No | Unique device ID.<br> **System capability**: SystemCapability.Multimedia.Audio.Device<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 6088| name<sup>9+</sup> | string | Yes | No | Device name.<br>For a Bluetooth device, you must request the ohos.permission.USE_BLUETOOTH permission.<br> **System capability**: SystemCapability.Multimedia.Audio.Device<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 6089| address<sup>9+</sup> | string | Yes | No | Device address.<br>For a Bluetooth device, you must request the ohos.permission.USE_BLUETOOTH permission.<br> **System capability**: SystemCapability.Multimedia.Audio.Device<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 6090| sampleRates<sup>9+</sup> | Array<number> | Yes | No | Supported sampling rates.<br> **System capability**: SystemCapability.Multimedia.Audio.Device<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 6091| channelCounts<sup>9+</sup> | Array<number> | Yes | No | Number of channels supported.<br> **System capability**: SystemCapability.Multimedia.Audio.Device<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 6092| channelMasks<sup>9+</sup> | Array<number> | Yes | No | Supported channel masks.<br> **System capability**: SystemCapability.Multimedia.Audio.Device<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 6093| displayName<sup>10+</sup> | string | Yes | No | Display name of the device.<br> **System capability**: SystemCapability.Multimedia.Audio.Device<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 6094| encodingTypes<sup>11+</sup> | Array<[AudioEncodingType](#audioencodingtype8)> | Yes | No | Supported encoding types.<br> **System capability**: SystemCapability.Multimedia.Audio.Core<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 6095| spatializationSupported<sup>18+</sup> | boolean | Yes | No | Whether the device supports spatial audio rendering. The value **true** means that the device supports spatial audio rendering, and **false** means the opposite.<br> **System capability**: SystemCapability.Multimedia.Audio.Spatialization| 6096 6097**Example** 6098 6099```ts 6100import { audio } from '@kit.AudioKit'; 6101 6102function displayDeviceProp(value: audio.AudioDeviceDescriptor) { 6103 deviceRoleValue = value.deviceRole; 6104 deviceTypeValue = value.deviceType; 6105} 6106 6107let deviceRoleValue: audio.DeviceRole | undefined = undefined; 6108let deviceTypeValue: audio.DeviceType | undefined = undefined; 6109audio.getAudioManager().getRoutingManager().getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((value: audio.AudioDeviceDescriptors) => { 6110 console.info('AudioFrameworkTest: Promise: getDevices OUTPUT_DEVICES_FLAG'); 6111 value.forEach(displayDeviceProp); 6112 if (deviceTypeValue != undefined && deviceRoleValue != undefined){ 6113 console.info('AudioFrameworkTest: Promise: getDevices : OUTPUT_DEVICES_FLAG : PASS'); 6114 } else { 6115 console.error('AudioFrameworkTest: Promise: getDevices : OUTPUT_DEVICES_FLAG : FAIL'); 6116 } 6117}); 6118``` 6119## AudioDataCallbackResult<sup>12+</sup> 6120 6121Enumerates the audio data callback results. 6122 6123**System capability**: SystemCapability.Multimedia.Audio.Core 6124 6125| Name | Value | Description | 6126| ---------------------| --------| ----------------- | 6127| INVALID | -1 | The callback data is invalid. | 6128| VALID | 0 | The callback data is valid. | 6129 6130## AudioRendererWriteDataCallback<sup>12+</sup> 6131 6132type AudioRendererWriteDataCallback = (data: ArrayBuffer) => AudioDataCallbackResult | void 6133 6134Defines the callback function used to write data to the audio renderer. Once the callback function finishes its execution, the audio service queues the data pointed to by **data** for playback. Therefore, do not change the data outside the callback. It is crucial to fill **data** with the exact length of data designated for playback; otherwise, noises may occur during playback. 6135 6136**System capability**: SystemCapability.Multimedia.Audio.Renderer 6137 6138**Parameters** 6139 6140| Name | Type |Mandatory | Description | 6141| :--------------| :--------| :----- | :------------ | 6142| data | ArrayBuffer | Yes| Data to be written to the buffer.| 6143 6144**Return value** 6145 6146| Type | Description | 6147|--------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------| 6148| [AudioDataCallbackResult](#audiodatacallbackresult12) \| void | If **void** or **AudioDataCallbackResult.VALID** is returned, the data is valid and the audio data is played. If **AudioDataCallbackResult.INVALID** is returned, the data is invalid and the audio data is not played.| 6149 6150## AudioTimestampInfo<sup>19+</sup> 6151 6152Describes the information about the audio stream timestamp and the current data frame position. 6153 6154**System capability**: SystemCapability.Multimedia.Audio.Core 6155 6156| Name| Type| Read-Only| Optional| Description | 6157| ---------| ------ | ---- | ---- |-----------------------------------| 6158| framePos | number | Yes | No | Position of the current data frame for playback or recording. | 6159| timestamp | number | Yes | No | Timestamp corresponding to the current data frame position during playback or recording.| 6160 6161## AudioRenderer<sup>8+</sup> 6162 6163Provides APIs for audio rendering. 6164 6165Before calling any API in AudioRenderer, you must use [createAudioRenderer](#audiocreateaudiorenderer8) to create an AudioRenderer instance. 6166 6167### Attributes 6168 6169**System capability**: SystemCapability.Multimedia.Audio.Renderer 6170 6171| Name | Type | Readable| Writable| Description | 6172| ----- | -------------------------- | ---- | ---- | ------------------ | 6173| state<sup>8+</sup> | [AudioState](#audiostate8) | Yes | No | Audio renderer state.| 6174 6175**Example** 6176 6177```ts 6178import { audio } from '@kit.AudioKit'; 6179 6180let state: audio.AudioState = audioRenderer.state; 6181``` 6182 6183### getRendererInfo<sup>8+</sup> 6184 6185getRendererInfo(callback: AsyncCallback<AudioRendererInfo\>): void 6186 6187Obtains the information about this audio renderer. This API uses an asynchronous callback to return the result. 6188 6189**System capability**: SystemCapability.Multimedia.Audio.Renderer 6190 6191**Parameters** 6192 6193| Name | Type | Mandatory| Description | 6194| :------- | :------------------------------------------------------- | :--- | :--------------------- | 6195| callback | AsyncCallback<[AudioRendererInfo](#audiorendererinfo8)\> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the audio renderer information obtained; otherwise, **err** is an error object.| 6196 6197**Example** 6198 6199```ts 6200import { BusinessError } from '@kit.BasicServicesKit'; 6201 6202audioRenderer.getRendererInfo((err: BusinessError, rendererInfo: audio.AudioRendererInfo) => { 6203 console.info('Renderer GetRendererInfo:'); 6204 console.info(`Renderer content: ${rendererInfo.content}`); 6205 console.info(`Renderer usage: ${rendererInfo.usage}`); 6206 console.info(`Renderer flags: ${rendererInfo.rendererFlags}`); 6207}); 6208``` 6209 6210### getRendererInfo<sup>8+</sup> 6211 6212getRendererInfo(): Promise<AudioRendererInfo\> 6213 6214Obtains the information about this audio renderer. This API uses a promise to return the result. 6215 6216**System capability**: SystemCapability.Multimedia.Audio.Renderer 6217 6218**Return value** 6219 6220| Type | Description | 6221| -------------------------------------------------- | ------------------------------- | 6222| Promise<[AudioRendererInfo](#audiorendererinfo8)\> | Promise used to return the audio renderer information.| 6223 6224**Example** 6225 6226```ts 6227import { BusinessError } from '@kit.BasicServicesKit'; 6228 6229audioRenderer.getRendererInfo().then((rendererInfo: audio.AudioRendererInfo) => { 6230 console.info('Renderer GetRendererInfo:'); 6231 console.info(`Renderer content: ${rendererInfo.content}`); 6232 console.info(`Renderer usage: ${rendererInfo.usage}`); 6233 console.info(`Renderer flags: ${rendererInfo.rendererFlags}`) 6234}).catch((err: BusinessError) => { 6235 console.error(`AudioFrameworkRenderLog: RendererInfo :ERROR: ${err}`); 6236}); 6237``` 6238 6239### getRendererInfoSync<sup>10+</sup> 6240 6241getRendererInfoSync(): AudioRendererInfo 6242 6243Obtains the information about this audio renderer. This API returns the result synchronously. 6244 6245**System capability**: SystemCapability.Multimedia.Audio.Renderer 6246 6247**Return value** 6248 6249| Type | Description | 6250| -------------------------------------------------- | ------------------------------- | 6251| [AudioRendererInfo](#audiorendererinfo8) | Audio renderer information.| 6252 6253**Example** 6254 6255```ts 6256import { BusinessError } from '@kit.BasicServicesKit'; 6257 6258try { 6259 let rendererInfo: audio.AudioRendererInfo = audioRenderer.getRendererInfoSync(); 6260 console.info(`Renderer content: ${rendererInfo.content}`); 6261 console.info(`Renderer usage: ${rendererInfo.usage}`); 6262 console.info(`Renderer flags: ${rendererInfo.rendererFlags}`) 6263} catch (err) { 6264 let error = err as BusinessError; 6265 console.error(`AudioFrameworkRenderLog: RendererInfo :ERROR: ${error}`); 6266} 6267``` 6268 6269### getStreamInfo<sup>8+</sup> 6270 6271getStreamInfo(callback: AsyncCallback<AudioStreamInfo\>): void 6272 6273Obtains the stream information of this audio renderer. This API uses an asynchronous callback to return the result. 6274 6275**System capability**: SystemCapability.Multimedia.Audio.Renderer 6276 6277**Parameters** 6278 6279| Name | Type | Mandatory| Description | 6280| :------- | :--------------------------------------------------- | :--- | :------------------- | 6281| callback | AsyncCallback<[AudioStreamInfo](#audiostreaminfo8)\> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the stream information obtained; otherwise, **err** is an error object.| 6282 6283**Example** 6284 6285```ts 6286import { BusinessError } from '@kit.BasicServicesKit'; 6287 6288audioRenderer.getStreamInfo((err: BusinessError, streamInfo: audio.AudioStreamInfo) => { 6289 console.info('Renderer GetStreamInfo:'); 6290 console.info(`Renderer sampling rate: ${streamInfo.samplingRate}`); 6291 console.info(`Renderer channel: ${streamInfo.channels}`); 6292 console.info(`Renderer format: ${streamInfo.sampleFormat}`); 6293 console.info(`Renderer encoding type: ${streamInfo.encodingType}`); 6294}); 6295``` 6296 6297### getStreamInfo<sup>8+</sup> 6298 6299getStreamInfo(): Promise<AudioStreamInfo\> 6300 6301Obtains the stream information of this audio renderer. This API uses a promise to return the result. 6302 6303**System capability**: SystemCapability.Multimedia.Audio.Renderer 6304 6305**Return value** 6306 6307| Type | Description | 6308| :--------------------------------------------- | :--------------------- | 6309| Promise<[AudioStreamInfo](#audiostreaminfo8)\> | Promise used to return the stream information.| 6310 6311**Example** 6312 6313```ts 6314import { BusinessError } from '@kit.BasicServicesKit'; 6315 6316audioRenderer.getStreamInfo().then((streamInfo: audio.AudioStreamInfo) => { 6317 console.info('Renderer GetStreamInfo:'); 6318 console.info(`Renderer sampling rate: ${streamInfo.samplingRate}`); 6319 console.info(`Renderer channel: ${streamInfo.channels}`); 6320 console.info(`Renderer format: ${streamInfo.sampleFormat}`); 6321 console.info(`Renderer encoding type: ${streamInfo.encodingType}`); 6322}).catch((err: BusinessError) => { 6323 console.error(`ERROR: ${err}`); 6324}); 6325``` 6326 6327### getStreamInfoSync<sup>10+</sup> 6328 6329getStreamInfoSync(): AudioStreamInfo 6330 6331Obtains the stream information of this audio renderer. This API returns the result synchronously. 6332 6333**System capability**: SystemCapability.Multimedia.Audio.Renderer 6334 6335**Return value** 6336 6337| Type | Description | 6338| :--------------------------------------------- | :--------------------- | 6339| [AudioStreamInfo](#audiostreaminfo8) | Stream information.| 6340 6341**Example** 6342 6343```ts 6344import { BusinessError } from '@kit.BasicServicesKit'; 6345 6346try { 6347 let streamInfo: audio.AudioStreamInfo = audioRenderer.getStreamInfoSync(); 6348 console.info(`Renderer sampling rate: ${streamInfo.samplingRate}`); 6349 console.info(`Renderer channel: ${streamInfo.channels}`); 6350 console.info(`Renderer format: ${streamInfo.sampleFormat}`); 6351 console.info(`Renderer encoding type: ${streamInfo.encodingType}`); 6352} catch (err) { 6353 let error = err as BusinessError; 6354 console.error(`ERROR: ${error}`); 6355} 6356``` 6357 6358### getAudioStreamId<sup>9+</sup> 6359 6360getAudioStreamId(callback: AsyncCallback<number\>): void 6361 6362Obtains the stream ID of this audio renderer. This API uses an asynchronous callback to return the result. 6363 6364**System capability**: SystemCapability.Multimedia.Audio.Renderer 6365 6366**Parameters** 6367 6368| Name | Type | Mandatory| Description | 6369| :------- | :--------------------------------------------------- | :--- | :------------------- | 6370| callback | AsyncCallback<number\> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the stream ID obtained; otherwise, **err** is an error object.| 6371 6372**Example** 6373 6374```ts 6375import { BusinessError } from '@kit.BasicServicesKit'; 6376 6377audioRenderer.getAudioStreamId((err: BusinessError, streamId: number) => { 6378 console.info(`Renderer GetStreamId: ${streamId}`); 6379}); 6380``` 6381 6382### getAudioStreamId<sup>9+</sup> 6383 6384getAudioStreamId(): Promise<number\> 6385 6386Obtains the stream ID of this audio renderer. This API uses a promise to return the result. 6387 6388**System capability**: SystemCapability.Multimedia.Audio.Renderer 6389 6390**Return value** 6391 6392| Type | Description | 6393| :--------------------------------------------- | :--------------------- | 6394| Promise<number\> | Promise used to return the stream ID.| 6395 6396**Example** 6397 6398```ts 6399import { BusinessError } from '@kit.BasicServicesKit'; 6400 6401audioRenderer.getAudioStreamId().then((streamId: number) => { 6402 console.info(`Renderer getAudioStreamId: ${streamId}`); 6403}).catch((err: BusinessError) => { 6404 console.error(`ERROR: ${err}`); 6405}); 6406``` 6407 6408### getAudioStreamIdSync<sup>10+</sup> 6409 6410getAudioStreamIdSync(): number 6411 6412Obtains the stream ID of this audio renderer. This API returns the result synchronously. 6413 6414**System capability**: SystemCapability.Multimedia.Audio.Renderer 6415 6416**Return value** 6417 6418| Type | Description | 6419| :--------------------------------------------- | :--------------------- | 6420| number | Stream ID.| 6421 6422**Example** 6423 6424```ts 6425import { BusinessError } from '@kit.BasicServicesKit'; 6426 6427try { 6428 let streamId: number = audioRenderer.getAudioStreamIdSync(); 6429 console.info(`Renderer getAudioStreamIdSync: ${streamId}`); 6430} catch (err) { 6431 let error = err as BusinessError; 6432 console.error(`ERROR: ${error}`); 6433} 6434``` 6435 6436### setAudioEffectMode<sup>10+</sup> 6437 6438setAudioEffectMode(mode: AudioEffectMode, callback: AsyncCallback\<void>): void 6439 6440Sets an audio effect mode. This API uses an asynchronous callback to return the result. 6441 6442**System capability**: SystemCapability.Multimedia.Audio.Renderer 6443 6444**Parameters** 6445 6446| Name | Type | Mandatory| Description | 6447| -------- | ---------------------------------------- | ---- | ------------------------ | 6448| mode | [AudioEffectMode](#audioeffectmode10) | Yes | Audio effect mode to set. | 6449| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 6450 6451**Error codes** 6452 6453For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 6454 6455| ID| Error Message| 6456| ------- | ----------------------------------------------| 6457| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 6458| 6800101 | Parameter verification failed. Return by callback. | 6459 6460**Example** 6461 6462```ts 6463import { BusinessError } from '@kit.BasicServicesKit'; 6464 6465audioRenderer.setAudioEffectMode(audio.AudioEffectMode.EFFECT_DEFAULT, (err: BusinessError) => { 6466 if (err) { 6467 console.error('Failed to set params'); 6468 } else { 6469 console.info('Callback invoked to indicate a successful audio effect mode setting.'); 6470 } 6471}); 6472``` 6473 6474### setAudioEffectMode<sup>10+</sup> 6475 6476setAudioEffectMode(mode: AudioEffectMode): Promise\<void> 6477 6478Sets an audio effect mode. This API uses a promise to return the result. 6479 6480**System capability**: SystemCapability.Multimedia.Audio.Renderer 6481 6482**Parameters** 6483 6484| Name| Type | Mandatory| Description | 6485| ------ | ---------------------------------------- | ---- | ------------ | 6486| mode | [AudioEffectMode](#audioeffectmode10) | Yes | Audio effect mode to set.| 6487 6488**Return value** 6489 6490| Type | Description | 6491| -------------- | ------------------------- | 6492| Promise\<void> | Promise that returns no value.| 6493 6494**Error codes** 6495 6496For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 6497 6498| ID| Error Message| 6499| ------- | ---------------------------------------------| 6500| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 6501| 6800101 | Parameter verification failed. Return by promise. | 6502 6503**Example** 6504 6505```ts 6506import { BusinessError } from '@kit.BasicServicesKit'; 6507 6508audioRenderer.setAudioEffectMode(audio.AudioEffectMode.EFFECT_DEFAULT).then(() => { 6509 console.info('setAudioEffectMode SUCCESS'); 6510}).catch((err: BusinessError) => { 6511 console.error(`ERROR: ${err}`); 6512}); 6513``` 6514 6515### getAudioEffectMode<sup>10+</sup> 6516 6517getAudioEffectMode(callback: AsyncCallback\<AudioEffectMode>): void 6518 6519Obtains the audio effect mode in use. This API uses an asynchronous callback to return the result. 6520 6521**System capability**: SystemCapability.Multimedia.Audio.Renderer 6522 6523**Parameters** 6524 6525| Name | Type | Mandatory| Description | 6526| -------- | ------------------------------------------------------- | ---- | ------------------ | 6527| callback | AsyncCallback<[AudioEffectMode](#audioeffectmode10)> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the audio effect mode obtained; otherwise, **err** is an error object.| 6528 6529**Example** 6530 6531```ts 6532import { BusinessError } from '@kit.BasicServicesKit'; 6533 6534audioRenderer.getAudioEffectMode((err: BusinessError, effectMode: audio.AudioEffectMode) => { 6535 if (err) { 6536 console.error('Failed to get params'); 6537 } else { 6538 console.info(`getAudioEffectMode: ${effectMode}`); 6539 } 6540}); 6541``` 6542 6543### getAudioEffectMode<sup>10+</sup> 6544 6545getAudioEffectMode(): Promise\<AudioEffectMode> 6546 6547Obtains the audio effect mode in use. This API uses a promise to return the result. 6548 6549**System capability**: SystemCapability.Multimedia.Audio.Renderer 6550 6551**Return value** 6552 6553| Type | Description | 6554| ------------------------------------------------- | ------------------------- | 6555| Promise<[AudioEffectMode](#audioeffectmode10)> | Promise used to return the audio effect mode.| 6556 6557**Example** 6558 6559```ts 6560import { BusinessError } from '@kit.BasicServicesKit'; 6561 6562audioRenderer.getAudioEffectMode().then((effectMode: audio.AudioEffectMode) => { 6563 console.info(`getAudioEffectMode: ${effectMode}`); 6564}).catch((err: BusinessError) => { 6565 console.error(`ERROR: ${err}`); 6566}); 6567``` 6568 6569### start<sup>8+</sup> 6570 6571start(callback: AsyncCallback<void\>): void 6572 6573Starts this audio renderer. This API uses an asynchronous callback to return the result. 6574 6575**System capability**: SystemCapability.Multimedia.Audio.Renderer 6576 6577**Parameters** 6578 6579| Name | Type | Mandatory| Description | 6580| -------- | -------------------- | ---- | ---------- | 6581| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object. If the operation fails, an error object with one of the following error codes is returned:<br>Error code 6800301: indicates abnormal status, focus preemption failure, and abnormal system processing. For details, see system logs.| 6582 6583**Example** 6584 6585```ts 6586import { BusinessError } from '@kit.BasicServicesKit'; 6587 6588audioRenderer.start((err: BusinessError) => { 6589 if (err) { 6590 console.error('Renderer start failed.'); 6591 } else { 6592 console.info('Renderer start success.'); 6593 } 6594}); 6595``` 6596 6597### start<sup>8+</sup> 6598 6599start(): Promise<void\> 6600 6601Starts this audio renderer. This API uses a promise to return the result. 6602 6603**System capability**: SystemCapability.Multimedia.Audio.Renderer 6604 6605**Return value** 6606 6607| Type | Description | 6608| -------------- | ------------------------- | 6609| Promise\<void> | Promise object, which indicates that the renderer is started successfully. If the operation fails, an error object with one of the following error codes is returned:<br>Error code 6800301: indicates abnormal status, focus preemption failure, and abnormal system processing. For details, see system logs.| 6610 6611**Example** 6612 6613```ts 6614import { BusinessError } from '@kit.BasicServicesKit'; 6615 6616audioRenderer.start().then(() => { 6617 console.info('Renderer started'); 6618}).catch((err: BusinessError) => { 6619 console.error(`ERROR: ${err}`); 6620}); 6621``` 6622 6623### pause<sup>8+</sup> 6624 6625pause(callback: AsyncCallback\<void>): void 6626 6627Pauses this audio renderer. This API uses an asynchronous callback to return the result. 6628 6629**System capability**: SystemCapability.Multimedia.Audio.Renderer 6630 6631**Parameters** 6632 6633| Name | Type | Mandatory| Description | 6634| -------- | -------------------- | ---- | ---------------- | 6635| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 6636 6637**Example** 6638 6639```ts 6640import { BusinessError } from '@kit.BasicServicesKit'; 6641 6642audioRenderer.pause((err: BusinessError) => { 6643 if (err) { 6644 console.error('Renderer pause failed'); 6645 } else { 6646 console.info('Renderer paused.'); 6647 } 6648}); 6649``` 6650 6651### pause<sup>8+</sup> 6652 6653pause(): Promise\<void> 6654 6655Pauses this audio renderer. This API uses a promise to return the result. 6656 6657**System capability**: SystemCapability.Multimedia.Audio.Renderer 6658 6659**Return value** 6660 6661| Type | Description | 6662| -------------- | ------------------------- | 6663| Promise\<void> | Promise that returns no value.| 6664 6665**Example** 6666 6667```ts 6668import { BusinessError } from '@kit.BasicServicesKit'; 6669 6670audioRenderer.pause().then(() => { 6671 console.info('Renderer paused'); 6672}).catch((err: BusinessError) => { 6673 console.error(`ERROR: ${err}`); 6674}); 6675``` 6676 6677### drain<sup>8+</sup> 6678 6679drain(callback: AsyncCallback\<void>): void 6680 6681Drains the playback buffer. This API uses an asynchronous callback to return the result. 6682 6683**System capability**: SystemCapability.Multimedia.Audio.Renderer 6684 6685**Parameters** 6686 6687| Name | Type | Mandatory| Description | 6688| -------- | -------------------- | ---- | ---------------- | 6689| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 6690 6691**Example** 6692 6693```ts 6694import { BusinessError } from '@kit.BasicServicesKit'; 6695 6696audioRenderer.drain((err: BusinessError) => { 6697 if (err) { 6698 console.error('Renderer drain failed'); 6699 } else { 6700 console.info('Renderer drained.'); 6701 } 6702}); 6703``` 6704 6705### drain<sup>8+</sup> 6706 6707drain(): Promise\<void> 6708 6709Drains the playback buffer. This API uses a promise to return the result. 6710 6711**System capability**: SystemCapability.Multimedia.Audio.Renderer 6712 6713**Return value** 6714 6715| Type | Description | 6716| -------------- | ------------------------- | 6717| Promise\<void> | Promise that returns no value.| 6718 6719**Example** 6720 6721```ts 6722import { BusinessError } from '@kit.BasicServicesKit'; 6723 6724audioRenderer.drain().then(() => { 6725 console.info('Renderer drained successfully'); 6726}).catch((err: BusinessError) => { 6727 console.error(`ERROR: ${err}`); 6728}); 6729``` 6730 6731### flush<sup>11+</sup> 6732 6733flush(): Promise\<void> 6734 6735Flushes the buffer. This API is available when [AudioState](#audiostate8) is **STATE_RUNNING**, **STATE_PAUSED**, or **STATE_STOPPED**. This API uses a promise to return the result. 6736 6737**System capability**: SystemCapability.Multimedia.Audio.Renderer 6738 6739**Return value** 6740 6741| Type | Description | 6742| -------------- | ------------------------- | 6743| Promise\<void> | Promise that returns no value.| 6744 6745**Error codes** 6746 6747For details about the error codes, see [Audio Error Codes](errorcode-audio.md). 6748 6749| ID| Error Message| 6750| ------- | --------------------------------------------| 6751| 6800103 | Operation not permit at current state. Return by promise. | 6752 6753**Example** 6754 6755```ts 6756import { BusinessError } from '@kit.BasicServicesKit'; 6757 6758audioRenderer.flush().then(() => { 6759 console.info('Renderer flushed successfully'); 6760}).catch((err: BusinessError) => { 6761 console.error(`ERROR: ${err}`); 6762}); 6763``` 6764 6765### stop<sup>8+</sup> 6766 6767stop(callback: AsyncCallback\<void>): void 6768 6769Stops this audio renderer. This API uses an asynchronous callback to return the result. 6770 6771**System capability**: SystemCapability.Multimedia.Audio.Renderer 6772 6773**Parameters** 6774 6775| Name | Type | Mandatory| Description | 6776| -------- | -------------------- | ---- | ---------------- | 6777| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 6778 6779**Example** 6780 6781```ts 6782import { BusinessError } from '@kit.BasicServicesKit'; 6783 6784audioRenderer.stop((err: BusinessError) => { 6785 if (err) { 6786 console.error('Renderer stop failed'); 6787 } else { 6788 console.info('Renderer stopped.'); 6789 } 6790}); 6791``` 6792 6793### stop<sup>8+</sup> 6794 6795stop(): Promise\<void> 6796 6797Stops this audio renderer. This API uses a promise to return the result. 6798 6799**System capability**: SystemCapability.Multimedia.Audio.Renderer 6800 6801**Return value** 6802 6803| Type | Description | 6804| -------------- | ------------------------- | 6805| Promise\<void> | Promise that returns no value.| 6806 6807**Example** 6808 6809```ts 6810import { BusinessError } from '@kit.BasicServicesKit'; 6811 6812audioRenderer.stop().then(() => { 6813 console.info('Renderer stopped successfully'); 6814}).catch((err: BusinessError) => { 6815 console.error(`ERROR: ${err}`); 6816}); 6817``` 6818 6819### release<sup>8+</sup> 6820 6821release(callback: AsyncCallback\<void>): void 6822 6823Releases the renderer. This API uses an asynchronous callback to return the result. 6824 6825**System capability**: SystemCapability.Multimedia.Audio.Renderer 6826 6827**Parameters** 6828 6829| Name | Type | Mandatory| Description | 6830| -------- | -------------------- | ---- | ---------------- | 6831| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 6832 6833**Example** 6834 6835```ts 6836import { BusinessError } from '@kit.BasicServicesKit'; 6837 6838audioRenderer.release((err: BusinessError) => { 6839 if (err) { 6840 console.error('Renderer release failed'); 6841 } else { 6842 console.info('Renderer released.'); 6843 } 6844}); 6845``` 6846 6847### release<sup>8+</sup> 6848 6849release(): Promise\<void> 6850 6851Releases the renderer. This API uses a promise to return the result. 6852 6853**System capability**: SystemCapability.Multimedia.Audio.Renderer 6854 6855**Return value** 6856 6857| Type | Description | 6858| -------------- | ------------------------- | 6859| Promise\<void> | Promise that returns no value.| 6860 6861**Example** 6862 6863```ts 6864import { BusinessError } from '@kit.BasicServicesKit'; 6865 6866audioRenderer.release().then(() => { 6867 console.info('Renderer released successfully'); 6868}).catch((err: BusinessError) => { 6869 console.error(`ERROR: ${err}`); 6870}); 6871``` 6872 6873### write<sup>8+(deprecated)</sup> 6874 6875write(buffer: ArrayBuffer, callback: AsyncCallback\<number>): void 6876 6877Writes the buffer. This API uses an asynchronous callback to return the result. 6878 6879> **NOTE** 6880> 6881> This API is supported since API version 8 and deprecated since API version 11. You are advised to use [on('writeData')](#onwritedata11) instead. 6882 6883**System capability**: SystemCapability.Multimedia.Audio.Renderer 6884 6885**Parameters** 6886 6887| Name | Type | Mandatory| Description | 6888| -------- | ---------------------- | ---- | --------------------------------------------------- | 6889| buffer | ArrayBuffer | Yes | Data to be written to the buffer. | 6890| callback | AsyncCallback\<number> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the number of bytes written; otherwise, **err** is an error object.| 6891 6892**Example** 6893 6894```ts 6895import { BusinessError } from '@kit.BasicServicesKit'; 6896import { fileIo as fs } from '@kit.CoreFileKit'; 6897import { common } from '@kit.AbilityKit'; 6898 6899let bufferSize: number; 6900class Options { 6901 offset?: number; 6902 length?: number; 6903} 6904audioRenderer.getBufferSize().then((data: number)=> { 6905 console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`); 6906 bufferSize = data; 6907 console.info(`Buffer size: ${bufferSize}`); 6908 // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. 6909 let context = this.getUIContext().getHostContext() as common.UIAbilityContext; 6910 let path = context.cacheDir; 6911 let filePath = path + '/StarWars10s-2C-48000-4SW.pcm'; 6912 let file: fs.File = fs.openSync(filePath, fs.OpenMode.READ_ONLY); 6913 fs.stat(filePath).then(async (stat: fs.Stat) => { 6914 let buf = new ArrayBuffer(bufferSize); 6915 let len = stat.size % bufferSize == 0 ? Math.floor(stat.size / bufferSize) : Math.floor(stat.size / bufferSize + 1); 6916 for (let i = 0;i < len; i++) { 6917 let options: Options = { 6918 offset: i * bufferSize, 6919 length: bufferSize 6920 }; 6921 let readSize: number = await fs.read(file.fd, buf, options); 6922 let writeSize: number = await new Promise((resolve,reject)=>{ 6923 audioRenderer.write(buf,(err: BusinessError, writeSize: number)=>{ 6924 if(err){ 6925 reject(err) 6926 }else{ 6927 resolve(writeSize) 6928 } 6929 }) 6930 }) 6931 } 6932 }); 6933 }).catch((err: BusinessError) => { 6934 console.error(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`); 6935}); 6936``` 6937 6938### write<sup>8+(deprecated)</sup> 6939 6940write(buffer: ArrayBuffer): Promise\<number> 6941 6942Writes the buffer. This API uses a promise to return the result. 6943 6944> **NOTE** 6945> 6946> This API is supported since API version 8 and deprecated since API version 11. You are advised to use [on('writeData')](#onwritedata11) instead. 6947 6948**System capability**: SystemCapability.Multimedia.Audio.Renderer 6949 6950**Parameters** 6951 6952| Name | Type | Mandatory| Description | 6953| -------- | ---------------------- | ---- | --------------------------------------------------- | 6954| buffer | ArrayBuffer | Yes | Data to be written to the buffer. | 6955 6956**Return value** 6957 6958| Type | Description | 6959| ---------------- | ------------------------------------------------------------ | 6960| Promise\<number> | Promise used to return the number of written bytes.| 6961 6962**Example** 6963 6964```ts 6965import { BusinessError } from '@kit.BasicServicesKit'; 6966import { fileIo as fs } from '@kit.CoreFileKit'; 6967import { common } from '@kit.AbilityKit'; 6968 6969let bufferSize: number; 6970class Options { 6971 offset?: number; 6972 length?: number; 6973} 6974audioRenderer.getBufferSize().then((data: number) => { 6975 console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`); 6976 bufferSize = data; 6977 console.info(`BufferSize: ${bufferSize}`); 6978 // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. 6979 let context = this.getUIContext().getHostContext() as common.UIAbilityContext; 6980 let path = context.cacheDir; 6981 let filePath = path + '/StarWars10s-2C-48000-4SW.pcm'; 6982 let file: fs.File = fs.openSync(filePath, fs.OpenMode.READ_ONLY); 6983 fs.stat(filePath).then(async (stat: fs.Stat) => { 6984 let buf = new ArrayBuffer(bufferSize); 6985 let len = stat.size % bufferSize == 0 ? Math.floor(stat.size / bufferSize) : Math.floor(stat.size / bufferSize + 1); 6986 for (let i = 0;i < len; i++) { 6987 let options: Options = { 6988 offset: i * bufferSize, 6989 length: bufferSize 6990 }; 6991 let readSize: number = await fs.read(file.fd, buf, options); 6992 try{ 6993 let writeSize: number = await audioRenderer.write(buf); 6994 } catch(err) { 6995 let error = err as BusinessError; 6996 console.error(`audioRenderer.write err: ${error}`); 6997 } 6998 } 6999 }); 7000}).catch((err: BusinessError) => { 7001 console.error(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`); 7002}); 7003``` 7004 7005### getAudioTime<sup>8+</sup> 7006 7007getAudioTime(callback: AsyncCallback\<number>): void 7008 7009Obtains the timestamp of the current playback position, measured in nanoseconds from the Unix epoch (January 1, 1970). This API uses an asynchronous callback to return the result. 7010 7011**System capability**: SystemCapability.Multimedia.Audio.Renderer 7012 7013**Parameters** 7014 7015| Name | Type | Mandatory| Description | 7016| -------- | ---------------------- | ---- | ---------------- | 7017| callback | AsyncCallback\<number> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the number of nanoseconds obtained; otherwise, **err** is an error object.| 7018 7019**Example** 7020 7021```ts 7022import { BusinessError } from '@kit.BasicServicesKit'; 7023 7024audioRenderer.getAudioTime((err: BusinessError, timestamp: number) => { 7025 console.info(`Current timestamp: ${timestamp}`); 7026}); 7027``` 7028 7029### getAudioTime<sup>8+</sup> 7030 7031getAudioTime(): Promise\<number> 7032 7033Obtains the timestamp of the current playback position, measured in nanoseconds from the Unix epoch (January 1, 1970). This API uses a promise to return the result. 7034 7035**System capability**: SystemCapability.Multimedia.Audio.Renderer 7036 7037**Return value** 7038 7039| Type | Description | 7040| ---------------- | ----------------------- | 7041| Promise\<number> | Promise used to return the timestamp.| 7042 7043**Example** 7044 7045```ts 7046import { BusinessError } from '@kit.BasicServicesKit'; 7047 7048audioRenderer.getAudioTime().then((timestamp: number) => { 7049 console.info(`Current timestamp: ${timestamp}`); 7050}).catch((err: BusinessError) => { 7051 console.error(`ERROR: ${err}`); 7052}); 7053``` 7054 7055### getAudioTimeSync<sup>10+</sup> 7056 7057getAudioTimeSync(): number 7058 7059Obtains the timestamp of the current playback position, measured in nanoseconds from the Unix epoch (January 1, 1970). This API returns the result synchronously. 7060 7061**System capability**: SystemCapability.Multimedia.Audio.Renderer 7062 7063**Return value** 7064 7065| Type | Description | 7066| ---------------- | ----------------------- | 7067| number | Timestamp.| 7068 7069**Example** 7070 7071```ts 7072import { BusinessError } from '@kit.BasicServicesKit'; 7073 7074try { 7075 let timestamp: number = audioRenderer.getAudioTimeSync(); 7076 console.info(`Current timestamp: ${timestamp}`); 7077} catch (err) { 7078 let error = err as BusinessError; 7079 console.error(`ERROR: ${error}`); 7080} 7081``` 7082 7083### getAudioTimestampInfo<sup>19+</sup> 7084 7085getAudioTimestampInfo(): Promise\<AudioTimestampInfo> 7086 7087Obtains the information about the audio stream timestamp and the current data frame position. This API uses a promise to return the result. 7088 7089**System capability**: SystemCapability.Multimedia.Audio.Renderer 7090 7091**Return value** 7092 7093| Type | Description | 7094|-------------------------------------------------------| ----------------------- | 7095| Promise\<[AudioTimestampInfo](#audiotimestampinfo19)> | Promise used to return the audio stream timestamp and the current data frame position.| 7096 7097**Error codes** 7098 7099For details about the error codes, see [Audio Error Codes](errorcode-audio.md). 7100 7101| ID| Error Message| 7102| ------- | --------------------------------------------| 7103| 6800103 | Operation not permit at current state. | 7104 7105**Example** 7106 7107```ts 7108import { BusinessError } from '@kit.BasicServicesKit'; 7109 7110audioRenderer.getAudioTimestampInfo().then((audioTimestampInfo: audio.AudioTimestampInfo) => { 7111 console.info(`Current timestamp: ${audioTimestampInfo.timestamp}`); 7112}).catch((err: BusinessError) => { 7113 console.error(`ERROR: ${err}`); 7114}); 7115``` 7116 7117### getAudioTimestampInfoSync<sup>19+</sup> 7118 7119getAudioTimestampInfoSync(): AudioTimestampInfo 7120 7121Obtains the information about the audio stream timestamp and the current data frame position. This API returns the result synchronously. 7122 7123**System capability**: SystemCapability.Multimedia.Audio.Renderer 7124 7125**Return value** 7126 7127| Type | Description | 7128| ---------------- | ----------------------- | 7129| [AudioTimestampInfo](#audiotimestampinfo19) | Information about the audio stream timestamp and the current data frame position.| 7130 7131**Error codes** 7132 7133For details about the error codes, see [Audio Error Codes](errorcode-audio.md). 7134 7135| ID| Error Message| 7136| ------- | --------------------------------------------| 7137| 6800103 | Operation not permit at current state. | 7138 7139**Example** 7140 7141```ts 7142import { BusinessError } from '@kit.BasicServicesKit'; 7143 7144try { 7145 let audioTimestampInfo: audio.AudioTimestampInfo = audioRenderer.getAudioTimestampInfoSync(); 7146 console.info(`Current timestamp: ${audioTimestampInfo.timestamp}`); 7147} catch (err) { 7148 let error = err as BusinessError; 7149 console.error(`ERROR: ${error}`); 7150} 7151``` 7152 7153### getBufferSize<sup>8+</sup> 7154 7155getBufferSize(callback: AsyncCallback\<number>): void 7156 7157Obtains a reasonable minimum buffer size in bytes for rendering. This API uses an asynchronous callback to return the result. 7158 7159**System capability**: SystemCapability.Multimedia.Audio.Renderer 7160 7161**Parameters** 7162 7163| Name | Type | Mandatory| Description | 7164| -------- | ---------------------- | ---- | -------------------- | 7165| callback | AsyncCallback\<number> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the minimum buffer size obtained; otherwise, **err** is an error object.| 7166 7167**Example** 7168 7169```ts 7170import { BusinessError } from '@kit.BasicServicesKit'; 7171 7172let bufferSize: number; 7173 7174audioRenderer.getBufferSize((err: BusinessError, data: number) => { 7175 if (err) { 7176 console.error('getBufferSize error'); 7177 } else { 7178 console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`); 7179 bufferSize = data; 7180 } 7181}); 7182``` 7183 7184### getBufferSize<sup>8+</sup> 7185 7186getBufferSize(): Promise\<number> 7187 7188Obtains a reasonable minimum buffer size in bytes for rendering. This API uses a promise to return the result. 7189 7190**System capability**: SystemCapability.Multimedia.Audio.Renderer 7191 7192**Return value** 7193 7194| Type | Description | 7195| ---------------- | --------------------------- | 7196| Promise\<number> | Promise used to return the buffer size.| 7197 7198**Example** 7199 7200```ts 7201import { BusinessError } from '@kit.BasicServicesKit'; 7202 7203let bufferSize: number; 7204 7205audioRenderer.getBufferSize().then((data: number) => { 7206 console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`); 7207 bufferSize = data; 7208}).catch((err: BusinessError) => { 7209 console.error(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`); 7210}); 7211``` 7212 7213### getBufferSizeSync<sup>10+</sup> 7214 7215getBufferSizeSync(): number 7216 7217Obtains a reasonable minimum buffer size in bytes for rendering. This API returns the result synchronously. 7218 7219**System capability**: SystemCapability.Multimedia.Audio.Renderer 7220 7221**Return value** 7222 7223| Type | Description | 7224| ---------------- | --------------------------- | 7225| number | Buffer size.| 7226 7227**Example** 7228 7229```ts 7230import { BusinessError } from '@kit.BasicServicesKit'; 7231 7232let bufferSize: number = 0; 7233 7234try { 7235 bufferSize = audioRenderer.getBufferSizeSync(); 7236 console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${bufferSize}`); 7237} catch (err) { 7238 let error = err as BusinessError; 7239 console.error(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${error}`); 7240} 7241``` 7242 7243### setRenderRate<sup>8+(deprecated)</sup> 7244 7245setRenderRate(rate: AudioRendererRate, callback: AsyncCallback\<void>): void 7246 7247Sets the render rate. This API uses an asynchronous callback to return the result. 7248 7249> **NOTE** 7250> 7251> This API is supported since API version 8 and deprecated since API version 11. You are advised to use [uninitialize][setSpeed](#setspeed11) instead. 7252 7253**System capability**: SystemCapability.Multimedia.Audio.Renderer 7254 7255**Parameters** 7256 7257| Name | Type | Mandatory| Description | 7258| -------- | ---------------------------------------- | ---- | ------------------------ | 7259| rate | [AudioRendererRate](#audiorendererrate8) | Yes | Audio render rate. | 7260| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 7261 7262**Example** 7263 7264```ts 7265import { BusinessError } from '@kit.BasicServicesKit'; 7266 7267audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL, (err: BusinessError) => { 7268 if (err) { 7269 console.error('Failed to set params'); 7270 } else { 7271 console.info('Callback invoked to indicate a successful render rate setting.'); 7272 } 7273}); 7274``` 7275 7276### setRenderRate<sup>8+(deprecated)</sup> 7277 7278setRenderRate(rate: AudioRendererRate): Promise\<void> 7279 7280Sets the render rate. This API uses a promise to return the result. 7281 7282> **NOTE** 7283> 7284> This API is supported since API version 8 and deprecated since API version 11. You are advised to use [uninitialize][setSpeed](#setspeed11) instead. 7285 7286**System capability**: SystemCapability.Multimedia.Audio.Renderer 7287 7288**Parameters** 7289 7290| Name| Type | Mandatory| Description | 7291| ------ | ---------------------------------------- | ---- | ------------ | 7292| rate | [AudioRendererRate](#audiorendererrate8) | Yes | Audio render rate.| 7293 7294**Return value** 7295 7296| Type | Description | 7297| -------------- | ------------------------- | 7298| Promise\<void> | Promise that returns no value.| 7299 7300**Example** 7301 7302```ts 7303import { BusinessError } from '@kit.BasicServicesKit'; 7304 7305audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL).then(() => { 7306 console.info('setRenderRate SUCCESS'); 7307}).catch((err: BusinessError) => { 7308 console.error(`ERROR: ${err}`); 7309}); 7310``` 7311 7312### setSpeed<sup>11+</sup> 7313 7314setSpeed(speed: number): void 7315 7316Sets the playback speed. 7317 7318**System capability**: SystemCapability.Multimedia.Audio.Renderer 7319 7320**Parameters** 7321 7322| Name| Type | Mandatory| Description | 7323| ------ | ---------------------------------------- | ---- |----------------------| 7324| speed | number | Yes | Playback speed, which ranges from 0.125 to 4.0.| 7325 7326**Error codes** 7327 7328For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 7329 7330| ID| Error Message| 7331| ------- | --------------------------------------------| 7332| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 7333| 6800101 | Parameter verification failed. | 7334 7335**Example** 7336 7337```ts 7338audioRenderer.setSpeed(1.5); 7339``` 7340 7341### getRenderRate<sup>8+(deprecated)</sup> 7342 7343getRenderRate(callback: AsyncCallback\<AudioRendererRate>): void 7344 7345Obtains the audio renderer rate. This API uses an asynchronous callback to return the result. 7346 7347> **NOTE** 7348> 7349> This API is supported since API version 8 and deprecated since API version 11. You are advised to use [getSpeed](#getspeed11) instead. 7350 7351**System capability**: SystemCapability.Multimedia.Audio.Renderer 7352 7353**Parameters** 7354 7355| Name | Type | Mandatory| Description | 7356| -------- | ------------------------------------------------------- | ---- | ------------------ | 7357| callback | AsyncCallback<[AudioRendererRate](#audiorendererrate8)> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the render rate obtained; otherwise, **err** is an error object.| 7358 7359**Example** 7360 7361```ts 7362import { BusinessError } from '@kit.BasicServicesKit'; 7363 7364audioRenderer.getRenderRate((err: BusinessError, renderRate: audio.AudioRendererRate) => { 7365 console.info(`getRenderRate: ${renderRate}`); 7366}); 7367``` 7368 7369### getRenderRate<sup>8+(deprecated)</sup> 7370 7371getRenderRate(): Promise\<AudioRendererRate> 7372 7373Obtains the audio renderer rate. This API uses a promise to return the result. 7374 7375> **NOTE** 7376> 7377> This API is supported since API version 8 and deprecated since API version 11. You are advised to use [getSpeed](#getspeed11) instead. 7378 7379**System capability**: SystemCapability.Multimedia.Audio.Renderer 7380 7381**Return value** 7382 7383| Type | Description | 7384| ------------------------------------------------- | ------------------------- | 7385| Promise<[AudioRendererRate](#audiorendererrate8)> | Promise used to return the render rate.| 7386 7387**Example** 7388 7389```ts 7390import { BusinessError } from '@kit.BasicServicesKit'; 7391 7392audioRenderer.getRenderRate().then((renderRate: audio.AudioRendererRate) => { 7393 console.info(`getRenderRate: ${renderRate}`); 7394}).catch((err: BusinessError) => { 7395 console.error(`ERROR: ${err}`); 7396}); 7397``` 7398 7399### getRenderRateSync<sup>10+(deprecated)</sup> 7400 7401getRenderRateSync(): AudioRendererRate 7402 7403Obtains the audio renderer rate. This API returns the result synchronously. 7404 7405> **NOTE** 7406> 7407> This API is supported since API version 10 and deprecated since API version 11. You are advised to use [getSpeed](#getspeed11) instead. 7408 7409**System capability**: SystemCapability.Multimedia.Audio.Renderer 7410 7411**Return value** 7412 7413| Type | Description | 7414| ------------------------------------------------- | ------------------------- | 7415| [AudioRendererRate](#audiorendererrate8) | Audio render rate.| 7416 7417**Example** 7418 7419```ts 7420import { BusinessError } from '@kit.BasicServicesKit'; 7421 7422try { 7423 let renderRate: audio.AudioRendererRate = audioRenderer.getRenderRateSync(); 7424 console.info(`getRenderRate: ${renderRate}`); 7425} catch (err) { 7426 let error = err as BusinessError; 7427 console.error(`ERROR: ${error}`); 7428} 7429``` 7430 7431### getSpeed<sup>11+</sup> 7432 7433getSpeed(): number 7434 7435Obtains the playback speed. 7436 7437**System capability**: SystemCapability.Multimedia.Audio.Renderer 7438 7439**Return value** 7440 7441| Type | Description | 7442| ------------------------------------------------- |-----------| 7443| number | Playback speed.| 7444 7445**Example** 7446 7447```ts 7448let speed = audioRenderer.getSpeed(); 7449``` 7450 7451### setInterruptMode<sup>9+</sup> 7452 7453setInterruptMode(mode: InterruptMode): Promise<void> 7454 7455Sets the audio interruption mode for the application. This API uses a promise to return the result. 7456 7457**System capability**: SystemCapability.Multimedia.Audio.Interrupt 7458 7459**Parameters** 7460 7461| Name | Type | Mandatory | Description | 7462| ---------- | ---------------------------------- | ------ | ---------- | 7463| mode | [InterruptMode](#interruptmode9) | Yes | Audio interruption mode. | 7464 7465**Return value** 7466 7467| Type | Description | 7468| ------------------- | ----------------------------- | 7469| Promise<void> | Promise that returns no value.| 7470 7471**Example** 7472 7473```ts 7474import { BusinessError } from '@kit.BasicServicesKit'; 7475 7476let mode = 0; 7477 7478audioRenderer.setInterruptMode(mode).then(() => { 7479 console.info('setInterruptMode Success!'); 7480}).catch((err: BusinessError) => { 7481 console.error(`setInterruptMode Fail: ${err}`); 7482}); 7483``` 7484### setInterruptMode<sup>9+</sup> 7485 7486setInterruptMode(mode: InterruptMode, callback: AsyncCallback\<void>): void 7487 7488Sets the audio interruption mode for the application. This API uses an asynchronous callback to return the result. 7489 7490**System capability**: SystemCapability.Multimedia.Audio.Interrupt 7491 7492**Parameters** 7493 7494| Name | Type | Mandatory | Description | 7495| ------- | ----------------------------------- | ------ | -------------- | 7496|mode | [InterruptMode](#interruptmode9) | Yes | Audio interruption mode.| 7497|callback | AsyncCallback\<void> | Yes |Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 7498 7499**Example** 7500 7501```ts 7502import { BusinessError } from '@kit.BasicServicesKit'; 7503 7504let mode = 1; 7505 7506audioRenderer.setInterruptMode(mode, (err: BusinessError) => { 7507 if(err){ 7508 console.error(`setInterruptMode Fail: ${err}`); 7509 } 7510 console.info('setInterruptMode Success!'); 7511}); 7512``` 7513 7514### setInterruptModeSync<sup>10+</sup> 7515 7516setInterruptModeSync(mode: InterruptMode): void 7517 7518Sets the audio interruption mode for the application. This API returns the result synchronously. 7519 7520**System capability**: SystemCapability.Multimedia.Audio.Interrupt 7521 7522**Parameters** 7523 7524| Name | Type | Mandatory | Description | 7525| ---------- | ---------------------------------- | ------ | ---------- | 7526| mode | [InterruptMode](#interruptmode9) | Yes | Audio interruption mode. | 7527 7528**Error codes** 7529 7530For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 7531 7532| ID| Error Message| 7533| ------- | --------------------------------------------| 7534| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 7535| 6800101 | Parameter verification failed. | 7536 7537**Example** 7538 7539```ts 7540import { BusinessError } from '@kit.BasicServicesKit'; 7541 7542try { 7543 audioRenderer.setInterruptModeSync(0); 7544 console.info('setInterruptMode Success!'); 7545} catch (err) { 7546 let error = err as BusinessError; 7547 console.error(`setInterruptMode Fail: ${error}`); 7548} 7549``` 7550 7551### setVolume<sup>9+</sup> 7552 7553setVolume(volume: number): Promise<void> 7554 7555Sets the volume for the audio stream. This API uses a promise to return the result. 7556 7557**System capability**: SystemCapability.Multimedia.Audio.Renderer 7558 7559**Parameters** 7560 7561| Name | Type | Mandatory | Description | 7562| ---------- | ------- | ------ | ------------------- | 7563| volume | number | Yes | Volume to set, which is in the range [0.0, 1.0].| 7564 7565**Return value** 7566 7567| Type | Description | 7568| ------------------- | ----------------------------- | 7569| Promise<void> | Promise that returns no value.| 7570 7571**Example** 7572 7573```ts 7574import { BusinessError } from '@kit.BasicServicesKit'; 7575 7576audioRenderer.setVolume(0.5).then(() => { 7577 console.info('setVolume Success!'); 7578}).catch((err: BusinessError) => { 7579 console.error(`setVolume Fail: ${err}`); 7580}); 7581``` 7582### setVolume<sup>9+</sup> 7583 7584setVolume(volume: number, callback: AsyncCallback\<void>): void 7585 7586Sets the volume for the audio stream. This API uses an asynchronous callback to return the result. 7587 7588**System capability**: SystemCapability.Multimedia.Audio.Renderer 7589 7590**Parameters** 7591 7592| Name | Type | Mandatory | Description | 7593| ------- | -----------| ------ | ------------------- | 7594|volume | number | Yes | Volume to set, which is in the range [0.0, 1.0].| 7595|callback | AsyncCallback\<void> | Yes |Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 7596 7597**Example** 7598 7599```ts 7600import { BusinessError } from '@kit.BasicServicesKit'; 7601 7602audioRenderer.setVolume(0.5, (err: BusinessError) => { 7603 if(err){ 7604 console.error(`setVolume Fail: ${err}`); 7605 return; 7606 } 7607 console.info('setVolume Success!'); 7608}); 7609``` 7610### getVolume<sup>12+</sup> 7611 7612getVolume(): number 7613 7614Obtains the volume of the audio stream. This API returns the result synchronously. 7615 7616**System capability**: SystemCapability.Multimedia.Audio.Renderer 7617 7618**Return value** 7619 7620| Type | Description | 7621| ---------------- | --------------------------- | 7622| number | Volume, in the range [0.0, 1.0].| 7623 7624**Example** 7625 7626```ts 7627import { BusinessError } from '@kit.BasicServicesKit'; 7628 7629try { 7630 let value: number = audioRenderer.getVolume(); 7631 console.info(`Indicate that the volume is obtained ${value}.`); 7632} catch (err) { 7633 let error = err as BusinessError; 7634 console.error(`Failed to obtain the volume, error ${error}.`); 7635} 7636``` 7637 7638### getMinStreamVolume<sup>10+</sup> 7639 7640getMinStreamVolume(callback: AsyncCallback<number>): void 7641 7642Obtains the minimum volume of the audio stream. This API uses an asynchronous callback to return the result. 7643 7644**System capability**: SystemCapability.Multimedia.Audio.Renderer 7645 7646**Parameters** 7647 7648| Name | Type | Mandatory | Description | 7649| ------- | -----------| ------ | ------------------- | 7650|callback |AsyncCallback<number> | Yes |Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the minimum volume (range [0, 1]) obtained; otherwise, **err** is an error object.| 7651 7652**Example** 7653 7654```ts 7655import { BusinessError } from '@kit.BasicServicesKit'; 7656 7657audioRenderer.getMinStreamVolume((err: BusinessError, minVolume: number) => { 7658 if (err) { 7659 console.error(`getMinStreamVolume error: ${err}`); 7660 } else { 7661 console.info(`getMinStreamVolume Success! ${minVolume}`); 7662 } 7663}); 7664``` 7665### getMinStreamVolume<sup>10+</sup> 7666 7667getMinStreamVolume(): Promise<number> 7668 7669Obtains the minimum volume of the audio stream. This API uses a promise to return the result. 7670 7671**System capability**: SystemCapability.Multimedia.Audio.Renderer 7672 7673**Return value** 7674 7675| Type | Description | 7676| ------------------- | ----------------------------- | 7677| Promise<number>| Promise used to return the minimum volume, which is in the range [0, 1].| 7678 7679**Example** 7680 7681```ts 7682import { BusinessError } from '@kit.BasicServicesKit'; 7683 7684audioRenderer.getMinStreamVolume().then((value: number) => { 7685 console.info(`Get min stream volume Success! ${value}`); 7686}).catch((err: BusinessError) => { 7687 console.error(`Get min stream volume Fail: ${err}`); 7688}); 7689``` 7690 7691### getMinStreamVolumeSync<sup>10+</sup> 7692 7693getMinStreamVolumeSync(): number 7694 7695Obtains the minimum volume of the audio stream. This API returns the result synchronously. 7696 7697**System capability**: SystemCapability.Multimedia.Audio.Renderer 7698 7699**Return value** 7700 7701| Type | Description | 7702| ------------------- | ----------------------------- | 7703| number| Minimum volume, which is in the range [0, 1].| 7704 7705**Example** 7706 7707```ts 7708import { BusinessError } from '@kit.BasicServicesKit'; 7709 7710try { 7711 let value: number = audioRenderer.getMinStreamVolumeSync(); 7712 console.info(`Get min stream volume Success! ${value}`); 7713} catch (err) { 7714 let error = err as BusinessError; 7715 console.error(`Get min stream volume Fail: ${error}`); 7716} 7717``` 7718 7719### getMaxStreamVolume<sup>10+</sup> 7720 7721getMaxStreamVolume(callback: AsyncCallback<number>): void 7722 7723Obtains the maximum volume of the audio stream. This API uses an asynchronous callback to return the result. 7724 7725**System capability**: SystemCapability.Multimedia.Audio.Renderer 7726 7727**Parameters** 7728 7729| Name | Type | Mandatory | Description | 7730| ------- | -----------| ------ | ------------------- | 7731|callback | AsyncCallback<number> | Yes |Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the maximum volume (range [0, 1]) obtained; otherwise, **err** is an error object.| 7732 7733**Example** 7734 7735```ts 7736import { BusinessError } from '@kit.BasicServicesKit'; 7737 7738audioRenderer.getMaxStreamVolume((err: BusinessError, maxVolume: number) => { 7739 if (err) { 7740 console.error(`getMaxStreamVolume Fail: ${err}`); 7741 } else { 7742 console.info(`getMaxStreamVolume Success! ${maxVolume}`); 7743 } 7744}); 7745``` 7746### getMaxStreamVolume<sup>10+</sup> 7747 7748getMaxStreamVolume(): Promise<number> 7749 7750Obtains the maximum volume of the audio stream. This API uses a promise to return the result. 7751 7752**System capability**: SystemCapability.Multimedia.Audio.Renderer 7753 7754**Return value** 7755 7756| Type | Description | 7757| ------------------- | ----------------------------- | 7758| Promise<number>| Promise used to return the maximum volume, which is in the range [0, 1].| 7759 7760**Example** 7761 7762```ts 7763import { BusinessError } from '@kit.BasicServicesKit'; 7764 7765audioRenderer.getMaxStreamVolume().then((value: number) => { 7766 console.info(`Get max stream volume Success! ${value}`); 7767}).catch((err: BusinessError) => { 7768 console.error(`Get max stream volume Fail: ${err}`); 7769}); 7770``` 7771 7772### getMaxStreamVolumeSync<sup>10+</sup> 7773 7774getMaxStreamVolumeSync(): number 7775 7776Obtains the maximum volume of the audio stream. This API returns the result synchronously. 7777 7778**System capability**: SystemCapability.Multimedia.Audio.Renderer 7779 7780**Return value** 7781 7782| Type | Description | 7783| ------------------- | ----------------------------- | 7784| number| Maximum volume, which is in the range [0, 1].| 7785 7786**Example** 7787 7788```ts 7789import { BusinessError } from '@kit.BasicServicesKit'; 7790 7791try { 7792 let value: number = audioRenderer.getMaxStreamVolumeSync(); 7793 console.info(`Get max stream volume Success! ${value}`); 7794} catch (err) { 7795 let error = err as BusinessError; 7796 console.error(`Get max stream volume Fail: ${error}`); 7797} 7798``` 7799 7800### getUnderflowCount<sup>10+</sup> 7801 7802getUnderflowCount(callback: AsyncCallback<number>): void 7803 7804Obtains the number of underflow audio frames in the audio stream that is being played. This API uses an asynchronous callback to return the result. 7805 7806**System capability**: SystemCapability.Multimedia.Audio.Renderer 7807 7808**Parameters** 7809 7810| Name | Type | Mandatory | Description | 7811| ------- | -----------| ------ | ------------------- | 7812|callback | AsyncCallback<number> | Yes |Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the number of underloaded audio frames obtained; otherwise, **err** is an error object.| 7813 7814**Example** 7815 7816```ts 7817import { BusinessError } from '@kit.BasicServicesKit'; 7818 7819audioRenderer.getUnderflowCount((err: BusinessError, underflowCount: number) => { 7820 if (err) { 7821 console.error(`getUnderflowCount Fail: ${err}`); 7822 } else { 7823 console.info(`getUnderflowCount Success! ${underflowCount}`); 7824 } 7825}); 7826``` 7827### getUnderflowCount<sup>10+</sup> 7828 7829getUnderflowCount(): Promise<number> 7830 7831Obtains the number of underflow audio frames in the audio stream that is being played. This API uses a promise to return the result. 7832 7833**System capability**: SystemCapability.Multimedia.Audio.Renderer 7834 7835**Return value** 7836 7837| Type | Description | 7838| ------------------- | ----------------------------- | 7839| Promise<number>| Promise used to return the number of underflow audio frames.| 7840 7841**Example** 7842 7843```ts 7844import { BusinessError } from '@kit.BasicServicesKit'; 7845 7846audioRenderer.getUnderflowCount().then((value: number) => { 7847 console.info(`Get underflow count Success! ${value}`); 7848}).catch((err: BusinessError) => { 7849 console.error(`Get underflow count Fail: ${err}`); 7850}); 7851``` 7852 7853### getUnderflowCountSync<sup>10+</sup> 7854 7855getUnderflowCountSync(): number 7856 7857Obtains the number of underflow audio frames in the audio stream that is being played. This API returns the result synchronously. 7858 7859**System capability**: SystemCapability.Multimedia.Audio.Renderer 7860 7861**Return value** 7862 7863| Type | Description | 7864| ------------------- | ----------------------------- | 7865| number| Number of underflow audio frames.| 7866 7867**Example** 7868 7869```ts 7870import { BusinessError } from '@kit.BasicServicesKit'; 7871 7872try { 7873 let value: number = audioRenderer.getUnderflowCountSync(); 7874 console.info(`Get underflow count Success! ${value}`); 7875} catch (err) { 7876 let error = err as BusinessError; 7877 console.error(`Get underflow count Fail: ${error}`); 7878} 7879``` 7880 7881### getCurrentOutputDevices<sup>10+</sup> 7882 7883getCurrentOutputDevices(callback: AsyncCallback<AudioDeviceDescriptors>): void 7884 7885Obtains the output device information of the audio stream. This API uses an asynchronous callback to return the result. 7886 7887**System capability**: SystemCapability.Multimedia.Audio.Device 7888 7889**Parameters** 7890 7891| Name | Type | Mandatory | Description | 7892| ------- | -----------| ------ | ------------------- | 7893|callback | AsyncCallback\<[AudioDeviceDescriptors](#audiodevicedescriptors)>| Yes |Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the output device information obtained; otherwise, **err** is an error object.| 7894 7895**Example** 7896 7897```ts 7898import { BusinessError } from '@kit.BasicServicesKit'; 7899 7900audioRenderer.getCurrentOutputDevices((err: BusinessError, deviceInfo: audio.AudioDeviceDescriptors) => { 7901 if (err) { 7902 console.error(`getCurrentOutputDevices Fail: ${err}`); 7903 } else { 7904 for (let i = 0; i < deviceInfo.length; i++) { 7905 console.info(`DeviceInfo id: ${deviceInfo[i].id}`); 7906 console.info(`DeviceInfo type: ${deviceInfo[i].deviceType}`); 7907 console.info(`DeviceInfo role: ${deviceInfo[i].deviceRole}`); 7908 console.info(`DeviceInfo name: ${deviceInfo[i].name}`); 7909 console.info(`DeviceInfo address: ${deviceInfo[i].address}`); 7910 console.info(`DeviceInfo samplerate: ${deviceInfo[i].sampleRates[0]}`); 7911 console.info(`DeviceInfo channelcount: ${deviceInfo[i].channelCounts[0]}`); 7912 console.info(`DeviceInfo channelmask: ${deviceInfo[i].channelMasks[0]}`); 7913 } 7914 } 7915}); 7916``` 7917### getCurrentOutputDevices<sup>10+</sup> 7918 7919getCurrentOutputDevices(): Promise<AudioDeviceDescriptors> 7920 7921Obtains the output device information of the audio stream. This API uses a promise to return the result. 7922 7923**System capability**: SystemCapability.Multimedia.Audio.Device 7924 7925**Return value** 7926 7927| Type | Description | 7928| ------------------- | ----------------------------- | 7929| Promise<[AudioDeviceDescriptors](#audiodevicedescriptors)>| Promise used to return the output device information.| 7930 7931**Example** 7932 7933```ts 7934import { BusinessError } from '@kit.BasicServicesKit'; 7935 7936audioRenderer.getCurrentOutputDevices().then((deviceInfo: audio.AudioDeviceDescriptors) => { 7937 for (let i = 0; i < deviceInfo.length; i++) { 7938 console.info(`DeviceInfo id: ${deviceInfo[i].id}`); 7939 console.info(`DeviceInfo type: ${deviceInfo[i].deviceType}`); 7940 console.info(`DeviceInfo role: ${deviceInfo[i].deviceRole}`); 7941 console.info(`DeviceInfo name: ${deviceInfo[i].name}`); 7942 console.info(`DeviceInfo address: ${deviceInfo[i].address}`); 7943 console.info(`DeviceInfo samplerate: ${deviceInfo[i].sampleRates[0]}`); 7944 console.info(`DeviceInfo channelcount: ${deviceInfo[i].channelCounts[0]}`); 7945 console.info(`DeviceInfo channelmask: ${deviceInfo[i].channelMasks[0]}`); 7946 } 7947}).catch((err: BusinessError) => { 7948 console.error(`Get current output devices Fail: ${err}`); 7949}); 7950``` 7951 7952### getCurrentOutputDevicesSync<sup>10+</sup> 7953 7954getCurrentOutputDevicesSync(): AudioDeviceDescriptors 7955 7956Obtains the output device information of the audio stream. This API returns the result synchronously. 7957 7958**System capability**: SystemCapability.Multimedia.Audio.Device 7959 7960**Return value** 7961 7962| Type | Description | 7963| ------------------- | ----------------------------- | 7964| [AudioDeviceDescriptors](#audiodevicedescriptors) | Output device information.| 7965 7966**Example** 7967 7968```ts 7969import { BusinessError } from '@kit.BasicServicesKit'; 7970 7971try { 7972 let deviceInfo: audio.AudioDeviceDescriptors = audioRenderer.getCurrentOutputDevicesSync(); 7973 for (let i = 0; i < deviceInfo.length; i++) { 7974 console.info(`DeviceInfo id: ${deviceInfo[i].id}`); 7975 console.info(`DeviceInfo type: ${deviceInfo[i].deviceType}`); 7976 console.info(`DeviceInfo role: ${deviceInfo[i].deviceRole}`); 7977 console.info(`DeviceInfo name: ${deviceInfo[i].name}`); 7978 console.info(`DeviceInfo address: ${deviceInfo[i].address}`); 7979 console.info(`DeviceInfo samplerate: ${deviceInfo[i].sampleRates[0]}`); 7980 console.info(`DeviceInfo channelcount: ${deviceInfo[i].channelCounts[0]}`); 7981 console.info(`DeviceInfo channelmask: ${deviceInfo[i].channelMasks[0]}`); 7982 } 7983} catch (err) { 7984 let error = err as BusinessError; 7985 console.error(`Get current output devices Fail: ${error}`); 7986} 7987``` 7988### setChannelBlendMode<sup>11+</sup> 7989 7990setChannelBlendMode(mode: ChannelBlendMode): void 7991 7992Sets the audio channel blending mode. This API returns the result synchronously. 7993 7994**System capability**: SystemCapability.Multimedia.Audio.Renderer 7995 7996**Parameters** 7997 7998| Name | Type | Mandatory| Description | 7999| ---------- | ----------------------------------- | ---- | -------------------------------------------------------- | 8000| mode | [ChannelBlendMode](#channelblendmode11) | Yes | Audio channel blending mode. | 8001 8002**Error codes** 8003 8004For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 8005 8006| ID| Error Message| 8007| ------- | --------------------------------------------| 8008| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 8009| 6800101 | Parameter verification failed. | 8010| 6800103 | Operation not permit at current state. | 8011 8012**Example** 8013 8014```ts 8015let mode = audio.ChannelBlendMode.MODE_DEFAULT; 8016 8017audioRenderer.setChannelBlendMode(mode); 8018console.info(`BlendMode: ${mode}`); 8019``` 8020### setVolumeWithRamp<sup>11+</sup> 8021 8022setVolumeWithRamp(volume: number, duration: number): void 8023 8024Sets a volume ramp. This API returns the result synchronously. 8025 8026**System capability**: SystemCapability.Multimedia.Audio.Renderer 8027 8028**Parameters** 8029 8030| Name | Type | Mandatory| Description | 8031| ---------- | ----------------------------------- | ---- | -------------------------------------------------------- | 8032| volume | number | Yes | Target volume, within the range [0.0, 1.0]. | 8033| duration | number | Yes | Time range during which the ramp applies, in ms. | 8034 8035**Error codes** 8036 8037For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 8038 8039| ID| Error Message| 8040| ------- | --------------------------------------------| 8041| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 8042| 6800101 | Parameter verification failed. | 8043 8044**Example** 8045 8046```ts 8047let volume = 0.5; 8048let duration = 1000; 8049 8050audioRenderer.setVolumeWithRamp(volume, duration); 8051console.info(`setVolumeWithRamp: ${volume}`); 8052``` 8053 8054### setSilentModeAndMixWithOthers<sup>12+</sup> 8055 8056setSilentModeAndMixWithOthers(on: boolean): void 8057 8058Sets the silent mode in concurrent playback for the audio stream. 8059 8060If the silent mode in concurrent playback is enabled, the system mutes the audio stream and does not interrupt other audio streams. If the silent mode in concurrent playback is disabled, the audio stream can gain focus based on the system focus policy. 8061 8062**System capability**: SystemCapability.Multimedia.Audio.Renderer 8063 8064**Parameters** 8065 8066| Name| Type | Mandatory| Description | 8067| ------ | ---------------------------------------- | ---- |----------------------| 8068| on | boolean | Yes | Whether to enable or disable the silent mode in concurrent playback for the audio stream. The value **true** means to enable the silent mode in concurrent playback, and **false** means the opposite.| 8069 8070**Example** 8071 8072```ts 8073audioRenderer.setSilentModeAndMixWithOthers(true); 8074``` 8075 8076### getSilentModeAndMixWithOthers<sup>12+</sup> 8077 8078getSilentModeAndMixWithOthers(): boolean 8079 8080Obtains the silent mode in concurrent playback for the audio stream. 8081 8082**System capability**: SystemCapability.Multimedia.Audio.Renderer 8083 8084**Return value** 8085 8086| Type | Description | 8087| ------------------------------------------------- |-----------| 8088| boolean | Enabled status. The value **true** means that the silent mode in concurrent playback is enabled, and **false** means the opposite.| 8089 8090**Example** 8091 8092```ts 8093let on = audioRenderer.getSilentModeAndMixWithOthers(); 8094``` 8095 8096### setDefaultOutputDevice<sup>12+</sup> 8097 8098setDefaultOutputDevice(deviceType: DeviceType): Promise<void> 8099 8100Sets the default audio output device. This API uses a promise to return the result. 8101 8102> **NOTE** 8103> 8104> - This API applies only to the scenarios where [StreamUsage](#streamusage) is set to voice message, VoIP voice calls, or VoIP video calls. It supports only receivers, speakers, and system default devices. 8105> 8106> - This API can be called at any time after an AudioRenderer instance is created. The system records the device set by the application. When the application is started, if an external device such as a Bluetooth or wired headset is connected, the system preferentially uses the external device to play sound. Otherwise, the system uses this default device to play sound. 8107> 8108> - This API has a lower priority than [AVCastPicker](../apis-avsession-kit/ohos-multimedia-avcastpicker.md#avcastpicker). If you have already switched the audio device using AVCastPicker, using this API to switch devices again does not take effect. 8109 8110**System capability**: SystemCapability.Multimedia.Audio.Renderer 8111 8112**Parameters** 8113 8114| Name | Type | Mandatory | Description | 8115| ---------- |----------------| ------ |---------------------------------------------------------| 8116| deviceType | [DeviceType](#devicetype) | Yes | Device type.<br>The options are **EARPIECE**, **SPEAKER**, and **DEFAULT**.| 8117 8118**Return value** 8119 8120| Type | Description | 8121| ------------------- | ----------------------------- | 8122| Promise<void> | Promise that returns no value.| 8123 8124**Error codes** 8125 8126For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 8127 8128| ID| Error Message| 8129| ------- | --------------------------------------------| 8130| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 8131| 6800101 | Parameter verification failed. | 8132| 6800103 | Operation not permit at current state. | 8133 8134**Example** 8135 8136```ts 8137import { BusinessError } from '@kit.BasicServicesKit'; 8138 8139// This API can be called at any time after an AudioRenderer instance is created. 8140// If the API is called when no audio is being played, the system records the default device set by the application. When the application starts playing, the sound is played from this default device. 8141// If the API is called when audio is being played and no external device, such as a Bluetooth or wired headset, is connected, the system immediately switches to the default device. If an external device is connected, the system records the default device and switches to it once the external device is disconnected. 8142audioRenderer.setDefaultOutputDevice(audio.DeviceType.SPEAKER).then(() => { 8143 console.info('setDefaultOutputDevice Success!'); 8144}).catch((err: BusinessError) => { 8145 console.error(`setDefaultOutputDevice Fail: ${err}`); 8146}); 8147``` 8148 8149### on('audioInterrupt')<sup>9+</sup> 8150 8151on(type: 'audioInterrupt', callback: Callback\<InterruptEvent>): void 8152 8153Subscribes to the audio interruption event, which is triggered when the audio focus is changed. This API uses an asynchronous callback to return the result. 8154 8155The AudioRenderer instance proactively gains the focus when the **start** event occurs and releases the focus when the **pause** or **stop** event occurs. Therefore, you do not need to request to gain or release the focus. 8156 8157After this API is called, an [InterruptEvent](#interruptevent9) is received when the AudioRenderer instance fails to obtain the focus or an audio interruption event occurs (for example, the audio stream is interrupted by others). It is recommended that the application perform further processing based on the **InterruptEvent** information. For details, see [Introduction to Audio Focus and Audio Sessions](../../media/audio/audio-playback-concurrency.md). 8158 8159**System capability**: SystemCapability.Multimedia.Audio.Interrupt 8160 8161**Parameters** 8162 8163| Name | Type | Mandatory| Description | 8164| -------- | -------------------------------------------- | ---- | ----------------------------------------------------------- | 8165| type | string | Yes | Event type. The event **'audioInterrupt'** is triggered when the audio focus is changed.| 8166| callback | Callback\<[InterruptEvent](#interruptevent9)\> | Yes | Callback used to return the event information.| 8167 8168**Error codes** 8169 8170For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 8171 8172| ID| Error Message| 8173| ------- | --------------------------------------------| 8174| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 8175| 6800101 | Parameter verification failed. | 8176 8177**Example** 8178 8179```ts 8180import { audio } from '@kit.AudioKit'; 8181 8182let isPlaying: boolean; // An identifier specifying whether rendering is in progress. 8183let isDucked: boolean; // An identifier specifying whether the audio volume is reduced. 8184onAudioInterrupt(); 8185 8186async function onAudioInterrupt(){ 8187 audioRenderer.on('audioInterrupt', (interruptEvent: audio.InterruptEvent) => { 8188 // When an audio interruption event occurs, the AudioRenderer receives the interruptEvent callback and performs processing based on the content in the callback. 8189 // 1. (Optional) The AudioRenderer reads the value of interruptEvent.forceType to see whether the system has forcibly performed the operation. 8190 // Note: In the default focus policy, INTERRUPT_HINT_RESUME maps to the force type INTERRUPT_SHARE, and others map to INTERRUPT_FORCE. Therefore, the value of forceType does not need to be checked. 8191 // 2. (Mandatory) The AudioRenderer then reads the value of interruptEvent.hintType and performs corresponding processing. 8192 if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) { 8193 // The audio focus event has been forcibly executed by the system. The application needs to update its status and displayed content. 8194 switch (interruptEvent.hintType) { 8195 case audio.InterruptHint.INTERRUPT_HINT_PAUSE: 8196 // The audio stream has been paused and temporarily loses the focus. It will receive the interruptEvent corresponding to resume when it is able to regain the focus. 8197 console.info('Force paused. Update playing status and stop writing'); 8198 isPlaying = false; // A simplified processing indicating several operations for switching the application to the paused state. 8199 break; 8200 case audio.InterruptHint.INTERRUPT_HINT_STOP: 8201 // The audio stream has been stopped and permanently loses the focus. The user must manually trigger the operation to resume rendering. 8202 console.info('Force stopped. Update playing status and stop writing'); 8203 isPlaying = false; // A simplified processing indicating several operations for switching the application to the paused state. 8204 break; 8205 case audio.InterruptHint.INTERRUPT_HINT_DUCK: 8206 // The audio stream is rendered at a reduced volume. 8207 console.info('Force ducked. Update volume status'); 8208 isDucked = true; // A simplified processing indicating several operations for updating the volume status. 8209 break; 8210 case audio.InterruptHint.INTERRUPT_HINT_UNDUCK: 8211 // The audio stream is rendered at the normal volume. 8212 console.info('Force ducked. Update volume status'); 8213 isDucked = false; // A simplified processing indicating several operations for updating the volume status. 8214 break; 8215 default: 8216 console.info('Invalid interruptEvent'); 8217 break; 8218 } 8219 } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) { 8220 // The audio focus event needs to be operated by the application, which can choose the processing mode. It is recommended that the application process the event according to the value of InterruptHint. 8221 switch (interruptEvent.hintType) { 8222 case audio.InterruptHint.INTERRUPT_HINT_RESUME: 8223 // It is recommended that the application continue rendering. (The audio stream has been forcibly paused and temporarily lost the focus. It can resume rendering now.) 8224 // The INTERRUPT_HINT_RESUME operation must be proactively executed by the application and cannot be forcibly executed by the system. Therefore, the INTERRUPT_HINT_RESUME event must map to INTERRUPT_SHARE. 8225 console.info('Resume force paused renderer or ignore'); 8226 // To continue rendering, the application must perform the required operations. 8227 break; 8228 default: 8229 console.info('Invalid interruptEvent'); 8230 break; 8231 } 8232 } 8233 }); 8234} 8235``` 8236 8237### off('audioInterrupt')<sup>18+</sup> 8238 8239off(type: 'audioInterrupt', callback?: Callback<InterruptEvent>): void 8240 8241Unsubscribes from the audio interruption event. This API uses an asynchronous callback to return the result. 8242 8243**System capability**: SystemCapability.Multimedia.Audio.Interrupt 8244 8245**Parameters** 8246 8247| Name | Type | Mandatory| Description | 8248| -------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | 8249| type | string | Yes | Event type. The event **'audioInterrupt'** is triggered when the audio focus is changed.| 8250| callback | Callback\<[InterruptEvent](#interruptevent9)\> | No| Callback used to return the event information.| 8251 8252**Error codes** 8253 8254For details about the error codes, see [Audio Error Codes](errorcode-audio.md). 8255 8256| ID| Error Message| 8257| ------- | --------------------------------------------| 8258| 6800101 | Parameter verification failed. | 8259 8260**Example** 8261 8262```ts 8263// Cancel all subscriptions to the event. 8264audioRenderer.off('audioInterrupt'); 8265 8266// For the same event, if the callback parameter passed to the off API is the same as that passed to the on API, the off API cancels the subscription registered with the specified callback parameter. 8267let isPlaying: boolean; // An identifier specifying whether rendering is in progress. 8268let isDucked: boolean; // An identifier specifying whether the audio volume is reduced. 8269 8270let audioInterruptCallback = (interruptEvent: audio.InterruptEvent) => { 8271 // When an audio interruption event occurs, the AudioRenderer receives the interruptEvent callback and performs processing based on the content in the callback. 8272 // 1. (Optional) The AudioRenderer reads the value of interruptEvent.forceType to see whether the system has forcibly performed the operation. 8273 // Note: In the default focus policy, INTERRUPT_HINT_RESUME maps to the force type INTERRUPT_SHARE, and others map to INTERRUPT_FORCE. Therefore, the value of forceType does not need to be checked. 8274 // 2. (Mandatory) The AudioRenderer then reads the value of interruptEvent.hintType and performs corresponding processing. 8275 if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) { 8276 // The audio focus event has been forcibly executed by the system. The application needs to update its status and displayed content. 8277 switch (interruptEvent.hintType) { 8278 case audio.InterruptHint.INTERRUPT_HINT_PAUSE: 8279 // The audio stream has been paused and temporarily loses the focus. It will receive the interruptEvent corresponding to resume when it is able to regain the focus. 8280 console.info('Force paused. Update playing status and stop writing'); 8281 isPlaying = false; // A simplified processing indicating several operations for switching the application to the paused state. 8282 break; 8283 case audio.InterruptHint.INTERRUPT_HINT_STOP: 8284 // The audio stream has been stopped and permanently loses the focus. The user must manually trigger the operation to resume rendering. 8285 console.info('Force stopped. Update playing status and stop writing'); 8286 isPlaying = false; // A simplified processing indicating several operations for switching the application to the paused state. 8287 break; 8288 case audio.InterruptHint.INTERRUPT_HINT_DUCK: 8289 // The audio stream is rendered at a reduced volume. 8290 console.info('Force ducked. Update volume status'); 8291 isDucked = true; // A simplified processing indicating several operations for updating the volume status. 8292 break; 8293 case audio.InterruptHint.INTERRUPT_HINT_UNDUCK: 8294 // The audio stream is rendered at the normal volume. 8295 console.info('Force ducked. Update volume status'); 8296 isDucked = false; // A simplified processing indicating several operations for updating the volume status. 8297 break; 8298 default: 8299 console.info('Invalid interruptEvent'); 8300 break; 8301 } 8302 } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) { 8303 // The audio focus event needs to be operated by the application, which can choose the processing mode. It is recommended that the application process the event according to the value of InterruptHint. 8304 switch (interruptEvent.hintType) { 8305 case audio.InterruptHint.INTERRUPT_HINT_RESUME: 8306 // It is recommended that the application continue rendering. (The audio stream has been forcibly paused and temporarily lost the focus. It can resume rendering now.) 8307 // The INTERRUPT_HINT_RESUME operation must be proactively executed by the application and cannot be forcibly executed by the system. Therefore, the INTERRUPT_HINT_RESUME event must map to INTERRUPT_SHARE. 8308 console.info('Resume force paused renderer or ignore'); 8309 // To continue rendering, the application must perform the required operations. 8310 break; 8311 default: 8312 console.info('Invalid interruptEvent'); 8313 break; 8314 } 8315 } 8316}; 8317 8318audioRenderer.on('audioInterrupt', audioInterruptCallback); 8319 8320audioRenderer.off('audioInterrupt', audioInterruptCallback); 8321``` 8322 8323### on('markReach')<sup>8+</sup> 8324 8325on(type: 'markReach', frame: number, callback: Callback<number>): void 8326 8327Subscribes to the mark reached event, which is triggered (only once) when the number of frames rendered reaches the value of the **frame** parameter. This API uses an asynchronous callback to return the result. 8328 8329For example, if **frame** is set to **100**, the callback is invoked when the number of rendered frames reaches the 100th frame. 8330 8331**System capability**: SystemCapability.Multimedia.Audio.Renderer 8332 8333**Parameters** 8334 8335| Name | Type | Mandatory| Description | 8336| :------- | :----------------------- | :--- | :---------------------------------------- | 8337| type | string | Yes | Event type. The event **'markReach'** is triggered when the number of frames rendered reaches the value of the **frame** parameter.| 8338| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | 8339| callback | Callback\<number> | Yes | Callback used to return the value of the **frame** parameter.| 8340 8341**Example** 8342 8343```ts 8344audioRenderer.on('markReach', 1000, (position: number) => { 8345 if (position == 1000) { 8346 console.info('ON Triggered successfully'); 8347 } 8348}); 8349``` 8350 8351 8352### off('markReach')<sup>8+</sup> 8353 8354off(type: 'markReach', callback?: Callback<number>): void 8355 8356Unsubscribes from the mark reached event. This API uses an asynchronous callback to return the result. 8357 8358**System capability**: SystemCapability.Multimedia.Audio.Renderer 8359 8360**Parameters** 8361 8362| Name| Type | Mandatory| Description | 8363| :----- | :----- | :--- | :------------------------------------------------ | 8364| type | string | Yes | Event type. The event **'markReach'** is triggered when the number of frames rendered reaches the value of the **frame** parameter.| 8365| callback<sup>18+</sup> | Callback\<number> | No | Callback used to return the value of the **frame** parameter.| 8366 8367**Example** 8368 8369```ts 8370// Cancel all subscriptions to the event. 8371audioRenderer.off('markReach'); 8372 8373// For the same event, if the callback parameter passed to the off API is the same as that passed to the on API, the off API cancels the subscription registered with the specified callback parameter. 8374let markReachCallback = (position: number) => { 8375 if (position == 1000) { 8376 console.info('ON Triggered successfully'); 8377 } 8378}; 8379 8380audioRenderer.on('markReach', 1000, markReachCallback); 8381 8382audioRenderer.off('markReach', markReachCallback); 8383``` 8384 8385### on('periodReach')<sup>8+</sup> 8386 8387on(type: 'periodReach', frame: number, callback: Callback<number>): void 8388 8389Subscribes to the period reached event, which is triggered each time the number of frames rendered reaches the value of the **frame** parameter. In other words, the information is reported periodically. This API uses an asynchronous callback to return the result. 8390 8391For example, if **frame** is set to **10**, the callback is invoked each time 10 frames are rendered, for example, when the number of frames rendered reaches the 10th frame, 20th frame, and 30th frame. 8392 8393**System capability**: SystemCapability.Multimedia.Audio.Renderer 8394 8395**Parameters** 8396 8397| Name | Type | Mandatory| Description | 8398| :------- | :----------------------- | :--- | :------------------------------------------ | 8399| type | string | Yes | Event type. The event **'periodReach'** is triggered each time the number of frames rendered reaches the value of the **frame** parameter.| 8400| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | 8401| callback | Callback\<number> | Yes | Callback used to return the value of the **frame** parameter.| 8402 8403**Example** 8404 8405```ts 8406audioRenderer.on('periodReach', 1000, (position: number) => { 8407 if (position == 1000) { 8408 console.info('ON Triggered successfully'); 8409 } 8410}); 8411``` 8412 8413### off('periodReach')<sup>8+</sup> 8414 8415off(type: 'periodReach', callback?: Callback<number>): void 8416 8417Unsubscribes from the period reached event. This API uses an asynchronous callback to return the result. 8418 8419**System capability**: SystemCapability.Multimedia.Audio.Renderer 8420 8421**Parameters** 8422 8423| Name| Type | Mandatory| Description | 8424| :----- | :----- | :--- | :-------------------------------------------------- | 8425| type | string | Yes | Event type. The event **'periodReach'** is triggered each time the number of frames rendered reaches the value of the **frame** parameter.| 8426| callback<sup>18+</sup> | Callback\<number> | No | Callback used to return the value of the **frame** parameter.| 8427 8428**Example** 8429 8430```ts 8431// Cancel all subscriptions to the event. 8432audioRenderer.off('periodReach'); 8433 8434// For the same event, if the callback parameter passed to the off API is the same as that passed to the on API, the off API cancels the subscription registered with the specified callback parameter. 8435let periodReachCallback = (position: number) => { 8436 if (position == 1000) { 8437 console.info('ON Triggered successfully'); 8438 } 8439}; 8440 8441audioRenderer.on('periodReach', periodReachCallback); 8442 8443audioRenderer.off('periodReach', periodReachCallback); 8444``` 8445 8446### on('stateChange')<sup>8+</sup> 8447 8448on(type: 'stateChange', callback: Callback<AudioState\>): void 8449 8450Subscribes to the audio renderer state change event, which is triggered when the state of the audio renderer is changed. This API uses an asynchronous callback to return the result. 8451 8452**System capability**: SystemCapability.Multimedia.Audio.Renderer 8453 8454**Parameters** 8455 8456| Name | Type | Mandatory| Description | 8457| :------- | :------------------------- | :--- | :------------------------------------------ | 8458| type | string | Yes | Event type. The event **'stateChange'** is triggered when the state of the audio renderer is changed.| 8459| callback | Callback\<[AudioState](#audiostate8)> | Yes | Callback used to return the audio status.| 8460 8461**Example** 8462 8463```ts 8464audioRenderer.on('stateChange', (state: audio.AudioState) => { 8465 if (state == 1) { 8466 console.info('audio renderer state is: STATE_PREPARED'); 8467 } 8468 if (state == 2) { 8469 console.info('audio renderer state is: STATE_RUNNING'); 8470 } 8471}); 8472``` 8473 8474### off('stateChange')<sup>18+</sup> 8475 8476off(type: 'stateChange', callback?: Callback<AudioState>): void 8477 8478Unsubscribes from the audio renderer state change event. This API uses an asynchronous callback to return the result. 8479 8480**System capability**: SystemCapability.Multimedia.Audio.Renderer 8481 8482**Parameters** 8483 8484| Name| Type | Mandatory| Description | 8485| :----- | :----- | :--- | :-------------------------------------------------- | 8486| type | string | Yes | Event type. The event **'stateChange'** is triggered when the state of the audio renderer is changed.| 8487| callback | Callback\<[AudioState](#audiostate8)> | No| Callback used to return the audio status.| 8488 8489**Error codes** 8490 8491For details about the error codes, see [Audio Error Codes](errorcode-audio.md). 8492 8493| ID| Error Message| 8494| ------- | --------------------------------------------| 8495| 6800101 | Parameter verification failed. | 8496 8497**Example** 8498 8499```ts 8500// Cancel all subscriptions to the event. 8501audioRenderer.off('stateChange'); 8502 8503// For the same event, if the callback parameter passed to the off API is the same as that passed to the on API, the off API cancels the subscription registered with the specified callback parameter. 8504let stateChangeCallback = (state: audio.AudioState) => { 8505 if (state == 1) { 8506 console.info('audio renderer state is: STATE_PREPARED'); 8507 } 8508 if (state == 2) { 8509 console.info('audio renderer state is: STATE_RUNNING'); 8510 } 8511}; 8512 8513audioRenderer.on('stateChange', stateChangeCallback); 8514 8515audioRenderer.off('stateChange', stateChangeCallback); 8516``` 8517 8518### on('outputDeviceChange')<sup>10+</sup> 8519 8520on(type: 'outputDeviceChange', callback: Callback\<AudioDeviceDescriptors>): void 8521 8522Subscribes to the audio output device change event, which is triggered when an audio output device is changed. This API uses an asynchronous callback to return the result. 8523 8524**System capability**: SystemCapability.Multimedia.Audio.Device 8525 8526**Parameters** 8527 8528| Name | Type | Mandatory| Description | 8529| :------- | :------------------------- | :--- | :------------------------------------------ | 8530| type | string | Yes | Event type. The event **'outputDeviceChange'** is triggered when an audio output device is changed.| 8531| callback | Callback\<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Yes | Callback used to return the output device descriptor of the current audio stream.| 8532 8533**Error codes** 8534 8535For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 8536 8537| ID| Error Message| 8538| ------- | --------------------------------------------| 8539| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 8540| 6800101 | Parameter verification failed. | 8541 8542**Example** 8543 8544```ts 8545audioRenderer.on('outputDeviceChange', (deviceInfo: audio.AudioDeviceDescriptors) => { 8546 console.info(`DeviceInfo id: ${deviceInfo[0].id}`); 8547 console.info(`DeviceInfo name: ${deviceInfo[0].name}`); 8548 console.info(`DeviceInfo address: ${deviceInfo[0].address}`); 8549}); 8550``` 8551 8552### off('outputDeviceChange')<sup>10+</sup> 8553 8554off(type: 'outputDeviceChange', callback?: Callback\<AudioDeviceDescriptors>): void 8555 8556Unsubscribes from the audio output device change event. This API uses an asynchronous callback to return the result. 8557 8558**System capability**: SystemCapability.Multimedia.Audio.Device 8559 8560**Parameters** 8561 8562| Name | Type | Mandatory| Description | 8563| :------- | :------------------------- | :--- | :------------------------------------------ | 8564| type | string | Yes | Event type. The event **'outputDeviceChange'** is triggered when an audio output device is changed.| 8565| callback | Callback\<[AudioDeviceDescriptors](#audiodevicedescriptors)> | No | Callback used to return the output device descriptor of the current audio stream.| 8566 8567**Error codes** 8568 8569For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 8570 8571| ID| Error Message| 8572| ------- | --------------------------------------------| 8573| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 8574| 6800101 | Parameter verification failed. | 8575 8576**Example** 8577 8578```ts 8579// Cancel all subscriptions to the event. 8580audioRenderer.off('outputDeviceChange'); 8581 8582// For the same event, if the callback parameter passed to the off API is the same as that passed to the on API, the off API cancels the subscription registered with the specified callback parameter. 8583let outputDeviceChangeCallback = (deviceInfo: audio.AudioDeviceDescriptors) => { 8584 console.info(`DeviceInfo id: ${deviceInfo[0].id}`); 8585 console.info(`DeviceInfo name: ${deviceInfo[0].name}`); 8586 console.info(`DeviceInfo address: ${deviceInfo[0].address}`); 8587}; 8588 8589audioRenderer.on('outputDeviceChange', outputDeviceChangeCallback); 8590 8591audioRenderer.off('outputDeviceChange', outputDeviceChangeCallback); 8592``` 8593 8594### on('outputDeviceChangeWithInfo')<sup>11+</sup> 8595 8596on(type: 'outputDeviceChangeWithInfo', callback: Callback\<AudioStreamDeviceChangeInfo>): void 8597 8598Subscribes to the change event of audio output devices and reasons, which is triggered when an audio output device is changed, and the change reason is reported. This API uses an asynchronous callback to return the result. 8599 8600**System capability**: SystemCapability.Multimedia.Audio.Device 8601 8602**Parameters** 8603 8604| Name | Type | Mandatory| Description | 8605| :------- |:-------------------------------------------------------------------------| :--- |:--------------------------------------------| 8606| type | string | Yes | Event type. The event **'outputDeviceChangeWithInfo'** is triggered when an audio output device is changed, and the change reason is reported.| 8607| callback | Callback\<[AudioStreamDeviceChangeInfo](#audiostreamdevicechangeinfo11)> | Yes | Callback used to return the output device descriptor of the current audio stream and the change reason.| 8608 8609**Error codes** 8610 8611For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 8612 8613| ID| Error Message| 8614| ------- | --------------------------------------------| 8615| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 8616| 6800101 | Parameter verification failed. | 8617 8618**Example** 8619 8620```ts 8621audioRenderer.on('outputDeviceChangeWithInfo', (deviceChangeInfo: audio.AudioStreamDeviceChangeInfo) => { 8622 console.info(`DeviceInfo id: ${deviceChangeInfo.devices[0].id}`); 8623 console.info(`DeviceInfo name: ${deviceChangeInfo.devices[0].name}`); 8624 console.info(`DeviceInfo address: ${deviceChangeInfo.devices[0].address}`); 8625 console.info(`Device change reason: ${deviceChangeInfo.changeReason}`); 8626}); 8627``` 8628 8629### off('outputDeviceChangeWithInfo')<sup>11+</sup> 8630 8631off(type: 'outputDeviceChangeWithInfo', callback?: Callback\<AudioStreamDeviceChangeInfo>): void 8632 8633Unsubscribes from the change event of audio output devices and reasons. This API uses an asynchronous callback to return the result. 8634 8635**System capability**: SystemCapability.Multimedia.Audio.Device 8636 8637**Parameters** 8638 8639| Name | Type | Mandatory| Description | 8640| :------- |:-------------------------------------------------------------------------| :--- |:--------------------------------------------| 8641| type | string | Yes | Event type. The event **'outputDeviceChangeWithInfo'** is triggered when an audio output device is changed, and the change reason is reported.| 8642| callback | Callback\<[AudioStreamDeviceChangeInfo](#audiostreamdevicechangeinfo11)> | No | Callback used to return the output device descriptor of the current audio stream and the change reason.| 8643 8644**Error codes** 8645 8646For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 8647 8648| ID| Error Message| 8649| ------- | --------------------------------------------| 8650| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 8651| 6800101 | Parameter verification failed. | 8652 8653**Example** 8654 8655```ts 8656// Cancel all subscriptions to the event. 8657audioRenderer.off('outputDeviceChangeWithInfo'); 8658 8659// For the same event, if the callback parameter passed to the off API is the same as that passed to the on API, the off API cancels the subscription registered with the specified callback parameter. 8660let outputDeviceChangeWithInfoCallback = (deviceChangeInfo: audio.AudioStreamDeviceChangeInfo) => { 8661 console.info(`DeviceInfo id: ${deviceChangeInfo.devices[0].id}`); 8662 console.info(`DeviceInfo name: ${deviceChangeInfo.devices[0].name}`); 8663 console.info(`DeviceInfo address: ${deviceChangeInfo.devices[0].address}`); 8664 console.info(`Device change reason: ${deviceChangeInfo.changeReason}`); 8665}; 8666 8667audioRenderer.on('outputDeviceChangeWithInfo', outputDeviceChangeWithInfoCallback); 8668 8669audioRenderer.off('outputDeviceChangeWithInfo', outputDeviceChangeWithInfoCallback); 8670``` 8671 8672### on('writeData')<sup>11+</sup> 8673 8674on(type: 'writeData', callback: AudioRendererWriteDataCallback): void 8675 8676Subscribes to the audio data write event, which is triggered when audio data needs to be written. This API uses an asynchronous callback to return the result. 8677 8678The callback function is used only to write audio data. Do not call AudioRenderer APIs in it. 8679 8680**System capability**: SystemCapability.Multimedia.Audio.Renderer 8681 8682**Parameters** 8683 8684| Name | Type | Mandatory| Description | 8685| :------- |:--------------------------------| :--- |:--------------------------------------| 8686| type | string | Yes | Event type. The event **'writeData'** is triggered when audio data needs to be written.| 8687| callback | [AudioRendererWriteDataCallback](#audiorendererwritedatacallback12) | Yes | Callback used to write the data to the buffer.<br>API version 11 does not support the return of the callback result. API version 12 and later support the return of the callback result [AudioDataCallbackResult](#audiodatacallbackresult12). | 8688 8689**Error codes** 8690 8691For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 8692 8693| ID| Error Message| 8694| ------- | --------------------------------------------| 8695| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 8696| 6800101 | Parameter verification failed. | 8697 8698**Example** 8699 8700```ts 8701import { BusinessError } from '@kit.BasicServicesKit'; 8702import {fileIo as fs} from '@kit.CoreFileKit'; 8703import { common } from '@kit.AbilityKit'; 8704 8705class Options { 8706 offset?: number; 8707 length?: number; 8708} 8709 8710let bufferSize: number = 0; 8711// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. 8712let context = this.getUIContext().getHostContext() as common.UIAbilityContext; 8713let path = context.cacheDir; 8714// Ensure that the resource exists in the path. 8715let filePath = path + '/StarWars10s-2C-48000-4SW.pcm'; 8716let file: fs.File = fs.openSync(filePath, fs.OpenMode.READ_ONLY); 8717let writeDataCallback = (buffer: ArrayBuffer) => { 8718 let options: Options = { 8719 offset: bufferSize, 8720 length: buffer.byteLength 8721 }; 8722 8723 try { 8724 fs.readSync(file.fd, buffer, options); 8725 bufferSize += buffer.byteLength; 8726 // This API does not return a callback result in API version 11, but does so in API version 12 and later versions. 8727 return audio.AudioDataCallbackResult.VALID; 8728 } catch (error) { 8729 console.error('Error reading file:', error); 8730 // This API does not return a callback result in API version 11, but does so in API version 12 and later versions. 8731 return audio.AudioDataCallbackResult.INVALID; 8732 } 8733}; 8734 8735audioRenderer.on('writeData', writeDataCallback); 8736audioRenderer.start().then(() => { 8737 console.info('Renderer started'); 8738}).catch((err: BusinessError) => { 8739 console.error(`ERROR: ${err}`); 8740}); 8741``` 8742 8743### off('writeData')<sup>11+</sup> 8744 8745off(type: 'writeData', callback?: AudioRendererWriteDataCallback): void 8746 8747Unsubscribes from the audio data write event. This API uses an asynchronous callback to return the result. 8748 8749**System capability**: SystemCapability.Multimedia.Audio.Renderer 8750 8751**Parameters** 8752 8753| Name | Type | Mandatory| Description | 8754| :------- |:--------------------------------| :--- |:--------------------------------------| 8755| type | string | Yes | Event type. The event **'writeData'** is triggered when audio data needs to be written.| 8756| callback | [AudioRendererWriteDataCallback](#audiorendererwritedatacallback12) | No | Callback used to write the data to the buffer.<br>API version 11 does not support the return of the callback result. API version 12 and later support the return of the callback result [AudioDataCallbackResult](#audiodatacallbackresult12).| 8757 8758**Error codes** 8759 8760For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 8761 8762| ID| Error Message| 8763| ------- | --------------------------------------------| 8764| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | 8765| 6800101 | Parameter verification failed. | 8766 8767**Example** 8768 8769```ts 8770// Cancel all subscriptions to the event. 8771audioRenderer.off('writeData'); 8772 8773// For the same event, if the callback parameter passed to the off API is the same as that passed to the on API, the off API cancels the subscription registered with the specified callback parameter. 8774let writeDataCallback = (data: ArrayBuffer) => { 8775 console.info(`write data: ${data}`); 8776}; 8777 8778audioRenderer.on('writeData', writeDataCallback); 8779 8780audioRenderer.off('writeData', writeDataCallback); 8781``` 8782 8783## AudioCapturer<sup>8+</sup> 8784 8785Provides APIs for audio capture. 8786 8787Before calling any API in AudioCapturer, you must use [createAudioCapturer](#audiocreateaudiocapturer8) to create an AudioCapturer instance. 8788 8789### Attributes 8790 8791**System capability**: SystemCapability.Multimedia.Audio.Capturer 8792 8793| Name | Type | Readable| Writable| Description | 8794| :---- | :------------------------- | :--- | :--- | :--------------- | 8795| state<sup>8+</sup> | [AudioState](#audiostate8) | Yes| No | Audio capturer state.| 8796 8797**Example** 8798 8799```ts 8800import { audio } from '@kit.AudioKit'; 8801 8802let state: audio.AudioState = audioCapturer.state; 8803``` 8804 8805### getCapturerInfo<sup>8+</sup> 8806 8807getCapturerInfo(callback: AsyncCallback<AudioCapturerInfo\>): void 8808 8809Obtains the audio capturer information. This API uses an asynchronous callback to return the result. 8810 8811**System capability**: SystemCapability.Multimedia.Audio.Capturer 8812 8813**Parameters** 8814 8815| Name | Type | Mandatory| Description | 8816| :------- | :-------------------------------- | :--- | :----------------------------------- | 8817| callback | AsyncCallback<[AudioCapturerInfo](#audiocapturerinfo8)\> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the capturer information obtained; otherwise, **err** is an error object.| 8818 8819**Example** 8820 8821```ts 8822import { BusinessError } from '@kit.BasicServicesKit'; 8823 8824audioCapturer.getCapturerInfo((err: BusinessError, capturerInfo: audio.AudioCapturerInfo) => { 8825 if (err) { 8826 console.error('Failed to get capture info'); 8827 } else { 8828 console.info('Capturer getCapturerInfo:'); 8829 console.info(`Capturer source: ${capturerInfo.source}`); 8830 console.info(`Capturer flags: ${capturerInfo.capturerFlags}`); 8831 } 8832}); 8833``` 8834 8835 8836### getCapturerInfo<sup>8+</sup> 8837 8838getCapturerInfo(): Promise<AudioCapturerInfo\> 8839 8840Obtains the audio capturer information. This API uses a promise to return the result. 8841 8842**System capability**: SystemCapability.Multimedia.Audio.Capturer 8843 8844**Return value** 8845 8846| Type | Description | 8847| :------------------------------------------------ | :---------------------------------- | 8848| Promise<[AudioCapturerInfo](#audiocapturerinfo8)\> | Promise used to return the audio capturer information.| 8849 8850**Example** 8851 8852```ts 8853import { BusinessError } from '@kit.BasicServicesKit'; 8854 8855audioCapturer.getCapturerInfo().then((audioParamsGet: audio.AudioCapturerInfo) => { 8856 if (audioParamsGet != undefined) { 8857 console.info('AudioFrameworkRecLog: Capturer CapturerInfo:'); 8858 console.info(`AudioFrameworkRecLog: Capturer SourceType: ${audioParamsGet.source}`); 8859 console.info(`AudioFrameworkRecLog: Capturer capturerFlags: ${audioParamsGet.capturerFlags}`); 8860 } else { 8861 console.info(`AudioFrameworkRecLog: audioParamsGet is : ${audioParamsGet}`); 8862 console.info('AudioFrameworkRecLog: audioParams getCapturerInfo are incorrect'); 8863 } 8864}).catch((err: BusinessError) => { 8865 console.error(`AudioFrameworkRecLog: CapturerInfo :ERROR: ${err}`); 8866}) 8867``` 8868 8869### getCapturerInfoSync<sup>10+</sup> 8870 8871getCapturerInfoSync(): AudioCapturerInfo 8872 8873Obtains the audio capturer information. This API returns the result synchronously. 8874 8875**System capability**: SystemCapability.Multimedia.Audio.Capturer 8876 8877**Return value** 8878 8879| Type | Description | 8880| :------------------------------------------------ | :---------------------------------- | 8881| [AudioCapturerInfo](#audiocapturerinfo8) | Audio capturer information.| 8882 8883**Example** 8884 8885```ts 8886import { BusinessError } from '@kit.BasicServicesKit'; 8887 8888try { 8889 let audioParamsGet: audio.AudioCapturerInfo = audioCapturer.getCapturerInfoSync(); 8890 console.info(`AudioFrameworkRecLog: Capturer SourceType: ${audioParamsGet.source}`); 8891 console.info(`AudioFrameworkRecLog: Capturer capturerFlags: ${audioParamsGet.capturerFlags}`); 8892} catch (err) { 8893 let error = err as BusinessError; 8894 console.error(`AudioFrameworkRecLog: CapturerInfo :ERROR: ${error}`); 8895} 8896``` 8897 8898### getStreamInfo<sup>8+</sup> 8899 8900getStreamInfo(callback: AsyncCallback<AudioStreamInfo\>): void 8901 8902Obtains the stream information of this audio capturer. This API uses an asynchronous callback to return the result. 8903 8904**System capability**: SystemCapability.Multimedia.Audio.Capturer 8905 8906**Parameters** 8907 8908| Name | Type | Mandatory| Description | 8909| :------- | :--------------------------------------------------- | :--- | :------------------------------- | 8910| callback | AsyncCallback<[AudioStreamInfo](#audiostreaminfo8)\> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the stream information obtained; otherwise, **err** is an error object.| 8911 8912**Example** 8913 8914```ts 8915import { BusinessError } from '@kit.BasicServicesKit'; 8916 8917audioCapturer.getStreamInfo((err: BusinessError, streamInfo: audio.AudioStreamInfo) => { 8918 if (err) { 8919 console.error('Failed to get stream info'); 8920 } else { 8921 console.info('Capturer GetStreamInfo:'); 8922 console.info(`Capturer sampling rate: ${streamInfo.samplingRate}`); 8923 console.info(`Capturer channel: ${streamInfo.channels}`); 8924 console.info(`Capturer format: ${streamInfo.sampleFormat}`); 8925 console.info(`Capturer encoding type: ${streamInfo.encodingType}`); 8926 } 8927}); 8928``` 8929 8930### getStreamInfo<sup>8+</sup> 8931 8932getStreamInfo(): Promise<AudioStreamInfo\> 8933 8934Obtains the stream information of this audio capturer. This API uses a promise to return the result. 8935 8936**System capability**: SystemCapability.Multimedia.Audio.Capturer 8937 8938**Return value** 8939 8940| Type | Description | 8941| :--------------------------------------------- | :------------------------------ | 8942| Promise<[AudioStreamInfo](#audiostreaminfo8)\> | Promise used to return the stream information.| 8943 8944**Example** 8945 8946```ts 8947import { BusinessError } from '@kit.BasicServicesKit'; 8948 8949audioCapturer.getStreamInfo().then((audioParamsGet: audio.AudioStreamInfo) => { 8950 console.info('getStreamInfo:'); 8951 console.info(`sampleFormat: ${audioParamsGet.sampleFormat}`); 8952 console.info(`samplingRate: ${audioParamsGet.samplingRate}`); 8953 console.info(`channels: ${audioParamsGet.channels}`); 8954 console.info(`encodingType: ${audioParamsGet.encodingType}`); 8955}).catch((err: BusinessError) => { 8956 console.error(`getStreamInfo :ERROR: ${err}`); 8957}); 8958``` 8959 8960### getStreamInfoSync<sup>10+</sup> 8961 8962getStreamInfoSync(): AudioStreamInfo 8963 8964Obtains the stream information of this audio capturer. This API returns the result synchronously. 8965 8966**System capability**: SystemCapability.Multimedia.Audio.Capturer 8967 8968**Return value** 8969 8970| Type | Description | 8971| :--------------------------------------------- | :------------------------------ | 8972| [AudioStreamInfo](#audiostreaminfo8) | Stream information.| 8973 8974**Example** 8975 8976```ts 8977import { BusinessError } from '@kit.BasicServicesKit'; 8978 8979try { 8980 let audioParamsGet: audio.AudioStreamInfo = audioCapturer.getStreamInfoSync(); 8981 console.info(`sampleFormat: ${audioParamsGet.sampleFormat}`); 8982 console.info(`samplingRate: ${audioParamsGet.samplingRate}`); 8983 console.info(`channels: ${audioParamsGet.channels}`); 8984 console.info(`encodingType: ${audioParamsGet.encodingType}`); 8985} catch (err) { 8986 let error = err as BusinessError; 8987 console.error(`getStreamInfo :ERROR: ${error}`); 8988} 8989``` 8990 8991### getAudioStreamId<sup>9+</sup> 8992 8993getAudioStreamId(callback: AsyncCallback<number\>): void 8994 8995Obtains the stream ID of this audio capturer. This API uses an asynchronous callback to return the result. 8996 8997**System capability**: SystemCapability.Multimedia.Audio.Capturer 8998 8999**Parameters** 9000 9001| Name | Type | Mandatory| Description | 9002| :------- | :--------------------------------------------------- | :--- | :------------------- | 9003| callback | AsyncCallback<number\> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the stream ID obtained; otherwise, **err** is an error object.| 9004 9005**Example** 9006 9007```ts 9008import { BusinessError } from '@kit.BasicServicesKit'; 9009 9010audioCapturer.getAudioStreamId((err: BusinessError, streamId: number) => { 9011 console.info(`audioCapturer GetStreamId: ${streamId}`); 9012}); 9013``` 9014 9015### getAudioStreamId<sup>9+</sup> 9016 9017getAudioStreamId(): Promise<number\> 9018 9019Obtains the stream ID of this audio capturer. This API uses a promise to return the result. 9020 9021**System capability**: SystemCapability.Multimedia.Audio.Capturer 9022 9023**Return value** 9024 9025| Type | Description | 9026| :----------------| :--------------------- | 9027| Promise<number\> | Promise used to return the stream ID.| 9028 9029**Example** 9030 9031```ts 9032import { BusinessError } from '@kit.BasicServicesKit'; 9033 9034audioCapturer.getAudioStreamId().then((streamId: number) => { 9035 console.info(`audioCapturer getAudioStreamId: ${streamId}`); 9036}).catch((err: BusinessError) => { 9037 console.error(`ERROR: ${err}`); 9038}); 9039``` 9040 9041### getAudioStreamIdSync<sup>10+</sup> 9042 9043getAudioStreamIdSync(): number 9044 9045Obtains the stream ID of this audio capturer. This API returns the result synchronously. 9046 9047**System capability**: SystemCapability.Multimedia.Audio.Capturer 9048 9049**Return value** 9050 9051| Type | Description | 9052| :----------------| :--------------------- | 9053| number | Stream ID.| 9054 9055**Example** 9056 9057```ts 9058import { BusinessError } from '@kit.BasicServicesKit'; 9059 9060try { 9061 let streamId: number = audioCapturer.getAudioStreamIdSync(); 9062 console.info(`audioCapturer getAudioStreamIdSync: ${streamId}`); 9063} catch (err) { 9064 let error = err as BusinessError; 9065 console.error(`ERROR: ${error}`); 9066} 9067``` 9068 9069### start<sup>8+</sup> 9070 9071start(callback: AsyncCallback<void\>): void 9072 9073Starts capturing. This API uses an asynchronous callback to return the result. 9074 9075**System capability**: SystemCapability.Multimedia.Audio.Capturer 9076 9077**Parameters** 9078 9079| Name | Type | Mandatory| Description | 9080| :------- | :------------------- | :--- | :----------------------------- | 9081| callback | AsyncCallback<void\> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object. If the operation fails, an error object with the following error code is returned:<br>Error code 6800301: indicates abnormal status, focus preemption failure, and abnormal system processing. For details, see system logs.| 9082 9083**Example** 9084 9085```ts 9086import { BusinessError } from '@kit.BasicServicesKit'; 9087 9088audioCapturer.start((err: BusinessError) => { 9089 if (err) { 9090 console.error('Capturer start failed.'); 9091 } else { 9092 console.info('Capturer start success.'); 9093 } 9094}); 9095``` 9096 9097 9098### start<sup>8+</sup> 9099 9100start(): Promise<void\> 9101 9102Starts capturing. This API uses a promise to return the result. 9103 9104**System capability**: SystemCapability.Multimedia.Audio.Capturer 9105 9106**Return value** 9107 9108| Type | Description | 9109| :------------- | :---------------------------- | 9110| Promise<void\> | Promise object, which indicates that the capturer is started successfully. If the operation fails, an error object with one of the following error codes is returned:<br>Error code 6800301: indicates abnormal status, focus preemption failure, and abnormal system processing. For details, see system logs.| 9111 9112**Example** 9113 9114```ts 9115import { BusinessError } from '@kit.BasicServicesKit'; 9116 9117audioCapturer.start().then(() => { 9118 console.info('AudioFrameworkRecLog: ---------START---------'); 9119 console.info('AudioFrameworkRecLog: Capturer started: SUCCESS'); 9120 console.info(`AudioFrameworkRecLog: AudioCapturer: STATE: ${audioCapturer.state}`); 9121 console.info('AudioFrameworkRecLog: Capturer started: SUCCESS'); 9122 if ((audioCapturer.state == audio.AudioState.STATE_RUNNING)) { 9123 console.info('AudioFrameworkRecLog: AudioCapturer is in Running State'); 9124 } 9125}).catch((err: BusinessError) => { 9126 console.error(`AudioFrameworkRecLog: Capturer start :ERROR : ${err}`); 9127}); 9128``` 9129 9130### stop<sup>8+</sup> 9131 9132stop(callback: AsyncCallback<void\>): void 9133 9134Stops this audio capturer. This API uses an asynchronous callback to return the result. 9135 9136**System capability**: SystemCapability.Multimedia.Audio.Capturer 9137 9138**Parameters** 9139 9140| Name | Type | Mandatory| Description | 9141| :------- | :------------------- | :--- | :----------------------------- | 9142| callback | AsyncCallback<void\> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 9143 9144**Example** 9145 9146```ts 9147import { BusinessError } from '@kit.BasicServicesKit'; 9148 9149audioCapturer.stop((err: BusinessError) => { 9150 if (err) { 9151 console.error('Capturer stop failed'); 9152 } else { 9153 console.info('Capturer stopped.'); 9154 } 9155}); 9156``` 9157 9158 9159### stop<sup>8+</sup> 9160 9161stop(): Promise<void\> 9162 9163Stops this audio capturer. This API uses a promise to return the result. 9164 9165**System capability**: SystemCapability.Multimedia.Audio.Capturer 9166 9167**Return value** 9168 9169| Type | Description | 9170| :------------- | :---------------------------- | 9171| Promise<void\> | Promise that returns no value.| 9172 9173**Example** 9174 9175```ts 9176import { BusinessError } from '@kit.BasicServicesKit'; 9177 9178audioCapturer.stop().then(() => { 9179 console.info('AudioFrameworkRecLog: ---------STOP RECORD---------'); 9180 console.info('AudioFrameworkRecLog: Capturer stopped: SUCCESS'); 9181 if ((audioCapturer.state == audio.AudioState.STATE_STOPPED)){ 9182 console.info('AudioFrameworkRecLog: State is Stopped:'); 9183 } 9184}).catch((err: BusinessError) => { 9185 console.error(`AudioFrameworkRecLog: Capturer stop: ERROR: ${err}`); 9186}); 9187``` 9188 9189### release<sup>8+</sup> 9190 9191release(callback: AsyncCallback<void\>): void 9192 9193Releases this audio capturer. This API uses an asynchronous callback to return the result. 9194 9195**System capability**: SystemCapability.Multimedia.Audio.Capturer 9196 9197**Parameters** 9198 9199| Name | Type | Mandatory| Description | 9200| :------- | :------------------- | :--- | :---------------------------------- | 9201| callback | AsyncCallback<void\> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 9202 9203**Example** 9204 9205```ts 9206import { BusinessError } from '@kit.BasicServicesKit'; 9207 9208audioCapturer.release((err: BusinessError) => { 9209 if (err) { 9210 console.error('capturer release failed'); 9211 } else { 9212 console.info('capturer released.'); 9213 } 9214}); 9215``` 9216 9217 9218### release<sup>8+</sup> 9219 9220release(): Promise<void\> 9221 9222Releases this audio capturer. This API uses a promise to return the result. 9223 9224**System capability**: SystemCapability.Multimedia.Audio.Capturer 9225 9226**Return value** 9227 9228| Type | Description | 9229| :------------- | :---------------------------- | 9230| Promise<void\> | Promise that returns no value.| 9231 9232**Example** 9233 9234```ts 9235import { BusinessError } from '@kit.BasicServicesKit'; 9236 9237audioCapturer.release().then(() => { 9238 console.info('AudioFrameworkRecLog: ---------RELEASE RECORD---------'); 9239 console.info('AudioFrameworkRecLog: Capturer release : SUCCESS'); 9240 console.info(`AudioFrameworkRecLog: AudioCapturer : STATE : ${audioCapturer.state}`); 9241}).catch((err: BusinessError) => { 9242 console.error(`AudioFrameworkRecLog: Capturer stop: ERROR: ${err}`); 9243}); 9244``` 9245 9246### read<sup>8+(deprecated)</sup> 9247 9248read(size: number, isBlockingRead: boolean, callback: AsyncCallback<ArrayBuffer\>): void 9249 9250Reads the buffer. This API uses an asynchronous callback to return the result. 9251 9252> **NOTE** 9253> 9254> This API is supported since API version 8 and deprecated since API version 11. You are advised to use [on('readData')](#onreaddata11) instead. 9255 9256**System capability**: SystemCapability.Multimedia.Audio.Capturer 9257 9258**Parameters** 9259 9260| Name | Type | Mandatory| Description | 9261| :------------- | :-------------------------- | :--- | :------------------------------- | 9262| size | number | Yes | Number of bytes to read. | 9263| isBlockingRead | boolean | Yes | Whether to block the read operation. The value **true** means to block the read operation, and **false** means the opposite. | 9264| callback | AsyncCallback<ArrayBuffer\> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the buffer read; otherwise, **err** is an error object.| 9265 9266**Example** 9267 9268```ts 9269import { BusinessError } from '@kit.BasicServicesKit'; 9270 9271let bufferSize: number = 0; 9272 9273audioCapturer.getBufferSize().then((data: number) => { 9274 console.info(`AudioFrameworkRecLog: getBufferSize: SUCCESS ${data}`); 9275 bufferSize = data; 9276}).catch((err: BusinessError) => { 9277 console.error(`AudioFrameworkRecLog: getBufferSize: ERROR: ${err}`); 9278}); 9279 9280audioCapturer.read(bufferSize, true, (err: BusinessError, buffer: ArrayBuffer) => { 9281 if (!err) { 9282 console.info('Success in reading the buffer data'); 9283 } 9284}); 9285``` 9286 9287### read<sup>8+(deprecated)</sup> 9288 9289read(size: number, isBlockingRead: boolean): Promise<ArrayBuffer\> 9290 9291Reads the buffer. This API uses a promise to return the result. 9292 9293> **NOTE** 9294> 9295> This API is supported since API version 8 and deprecated since API version 11. You are advised to use [on('readData')](#onreaddata11) instead. 9296 9297**System capability**: SystemCapability.Multimedia.Audio.Capturer 9298 9299**Parameters** 9300 9301| Name | Type | Mandatory| Description | 9302| :------------- | :------ | :--- | :--------------- | 9303| size | number | Yes | Number of bytes to read. | 9304| isBlockingRead | boolean | Yes | Whether to block the read operation. The value **true** means to block the read operation, and **false** means the opposite.| 9305 9306**Return value** 9307 9308| Type | Description | 9309| :-------------------- | :----------------------------------------------------- | 9310| Promise<ArrayBuffer\> | Promise used to return the data read from the buffer.| 9311 9312**Example** 9313 9314```ts 9315import { BusinessError } from '@kit.BasicServicesKit'; 9316 9317let bufferSize: number = 0; 9318 9319audioCapturer.getBufferSize().then((data: number) => { 9320 console.info(`AudioFrameworkRecLog: getBufferSize: SUCCESS ${data}`); 9321 bufferSize = data; 9322}).catch((err: BusinessError) => { 9323 console.error(`AudioFrameworkRecLog: getBufferSize: ERROR ${err}`); 9324}); 9325console.info(`Buffer size: ${bufferSize}`); 9326 9327audioCapturer.read(bufferSize, true).then((buffer: ArrayBuffer) => { 9328 console.info('buffer read successfully'); 9329}).catch((err: BusinessError) => { 9330 console.error(`ERROR : ${err}`); 9331}); 9332``` 9333 9334### getAudioTime<sup>8+</sup> 9335 9336getAudioTime(callback: AsyncCallback<number\>): void 9337 9338Obtains the timestamp of the current recording position, measured in nanoseconds from the Unix epoch (January 1, 1970). This API uses an asynchronous callback to return the result. 9339 9340**System capability**: SystemCapability.Multimedia.Audio.Capturer 9341 9342**Parameters** 9343 9344| Name | Type | Mandatory| Description | 9345| :------- | :--------------------- | :--- | :----------------------------- | 9346| callback | AsyncCallback<number\> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the number of nanoseconds obtained; otherwise, **err** is an error object.| 9347 9348**Example** 9349 9350```ts 9351import { BusinessError } from '@kit.BasicServicesKit'; 9352 9353audioCapturer.getAudioTime((err: BusinessError, timestamp: number) => { 9354 console.info(`Current timestamp: ${timestamp}`); 9355}); 9356``` 9357 9358### getAudioTime<sup>8+</sup> 9359 9360getAudioTime(): Promise<number\> 9361 9362Obtains the timestamp of the current recording position, measured in nanoseconds from the Unix epoch (January 1, 1970). This API uses a promise to return the result. 9363 9364**System capability**: SystemCapability.Multimedia.Audio.Capturer 9365 9366**Return value** 9367 9368| Type | Description | 9369| :--------------- | :---------------------------- | 9370| Promise<number\> | Promise used to return the number of nanoseconds elapsed from the Unix epoch.| 9371 9372**Example** 9373 9374```ts 9375import { BusinessError } from '@kit.BasicServicesKit'; 9376 9377audioCapturer.getAudioTime().then((audioTime: number) => { 9378 console.info(`AudioFrameworkRecLog: AudioCapturer getAudioTime : Success ${audioTime}`); 9379}).catch((err: BusinessError) => { 9380 console.error(`AudioFrameworkRecLog: AudioCapturer Created : ERROR : ${err}`); 9381}); 9382``` 9383 9384### getAudioTimeSync<sup>10+</sup> 9385 9386getAudioTimeSync(): number 9387 9388Obtains the timestamp of the current recording position, measured in nanoseconds from the Unix epoch (January 1, 1970). This API returns the result synchronously. 9389 9390**System capability**: SystemCapability.Multimedia.Audio.Capturer 9391 9392**Return value** 9393 9394| Type | Description | 9395| :--------------- | :---------------------------- | 9396| number | Timestamp.| 9397 9398**Example** 9399 9400```ts 9401import { BusinessError } from '@kit.BasicServicesKit'; 9402 9403try { 9404 let audioTime: number = audioCapturer.getAudioTimeSync(); 9405 console.info(`AudioFrameworkRecLog: AudioCapturer getAudioTimeSync : Success ${audioTime}`); 9406} catch (err) { 9407 let error = err as BusinessError; 9408 console.error(`AudioFrameworkRecLog: AudioCapturer getAudioTimeSync : ERROR : ${error}`); 9409} 9410``` 9411 9412### getAudioTimestampInfo<sup>19+</sup> 9413 9414getAudioTimestampInfo(): Promise\<AudioTimestampInfo> 9415 9416Obtains the information about the audio stream timestamp and the current data frame position. This API uses a promise to return the result. 9417 9418**System capability**: SystemCapability.Multimedia.Audio.Capturer 9419 9420**Return value** 9421 9422| Type | Description | 9423|-------------------------------------------------------| ----------------------- | 9424| Promise\<[AudioTimestampInfo](#audiotimestampinfo19)> | Promise used to return the audio stream timestamp and the current data frame position.| 9425 9426**Error codes** 9427 9428For details about the error codes, see [Audio Error Codes](errorcode-audio.md). 9429 9430| ID| Error Message| 9431| ------- | --------------------------------------------| 9432| 6800103 | Operation not permit at current state. | 9433 9434**Example** 9435 9436```ts 9437import { BusinessError } from '@kit.BasicServicesKit'; 9438 9439audioCapturer.getAudioTimestampInfo().then((audioTimestampInfo: audio.AudioTimestampInfo) => { 9440 console.info(`Current timestamp: ${audioTimestampInfo.timestamp}`); 9441}).catch((err: BusinessError) => { 9442 console.error(`ERROR: ${err}`); 9443}); 9444``` 9445 9446### getAudioTimestampInfoSync<sup>19+</sup> 9447 9448getAudioTimestampInfoSync(): AudioTimestampInfo 9449 9450Obtains the information about the audio stream timestamp and the current data frame position. This API returns the result synchronously. 9451 9452**System capability**: SystemCapability.Multimedia.Audio.Capturer 9453 9454**Return value** 9455 9456| Type | Description | 9457| ---------------- | ----------------------- | 9458| [AudioTimestampInfo](#audiotimestampinfo19) | Information about the audio stream timestamp and the current data frame position.| 9459 9460**Error codes** 9461 9462For details about the error codes, see [Audio Error Codes](errorcode-audio.md). 9463 9464| ID| Error Message| 9465| ------- | --------------------------------------------| 9466| 6800103 | Operation not permit at current state. | 9467 9468**Example** 9469 9470```ts 9471import { BusinessError } from '@kit.BasicServicesKit'; 9472 9473try { 9474 let audioTimestampInfo: audio.AudioTimestampInfo = audioCapturer.getAudioTimestampInfoSync(); 9475 console.info(`Current timestamp: ${audioTimestampInfo.timestamp}`); 9476} catch (err) { 9477 let error = err as BusinessError; 9478 console.error(`ERROR: ${error}`); 9479} 9480``` 9481 9482### getBufferSize<sup>8+</sup> 9483 9484getBufferSize(callback: AsyncCallback<number\>): void 9485 9486Obtains a reasonable minimum buffer size in bytes for capturing. This API uses an asynchronous callback to return the result. 9487 9488**System capability**: SystemCapability.Multimedia.Audio.Capturer 9489 9490**Parameters** 9491 9492| Name | Type | Mandatory| Description | 9493| :------- | :--------------------- | :--- | :----------------------------------- | 9494| callback | AsyncCallback<number\> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the minimum buffer size obtained; otherwise, **err** is an error object.| 9495 9496**Example** 9497 9498```ts 9499import { BusinessError } from '@kit.BasicServicesKit'; 9500 9501audioCapturer.getBufferSize((err: BusinessError, bufferSize: number) => { 9502 if (!err) { 9503 console.info(`BufferSize : ${bufferSize}`); 9504 audioCapturer.read(bufferSize, true).then((buffer: ArrayBuffer) => { 9505 console.info(`Buffer read is ${buffer.byteLength}`); 9506 }).catch((err: BusinessError) => { 9507 console.error(`AudioFrameworkRecLog: AudioCapturer Created : ERROR : ${err}`); 9508 }); 9509 } 9510}); 9511``` 9512 9513### getBufferSize<sup>8+</sup> 9514 9515getBufferSize(): Promise<number\> 9516 9517Obtains a reasonable minimum buffer size in bytes for capturing. This API uses a promise to return the result. 9518 9519**System capability**: SystemCapability.Multimedia.Audio.Capturer 9520 9521**Return value** 9522 9523| Type | Description | 9524| :--------------- | :---------------------------------- | 9525| Promise<number\> | Promise used to return the buffer size.| 9526 9527**Example** 9528 9529```ts 9530import { BusinessError } from '@kit.BasicServicesKit'; 9531 9532let bufferSize: number = 0; 9533 9534audioCapturer.getBufferSize().then((data: number) => { 9535 console.info(`AudioFrameworkRecLog: getBufferSize :SUCCESS ${data}`); 9536 bufferSize = data; 9537}).catch((err: BusinessError) => { 9538 console.error(`AudioFrameworkRecLog: getBufferSize :ERROR : ${err}`); 9539}); 9540``` 9541 9542### getBufferSizeSync<sup>10+</sup> 9543 9544getBufferSizeSync(): number 9545 9546Obtains a reasonable minimum buffer size in bytes for capturing. This API returns the result synchronously. 9547 9548**System capability**: SystemCapability.Multimedia.Audio.Capturer 9549 9550**Return value** 9551 9552| Type | Description | 9553| :--------------- | :---------------------------------- | 9554| number | Buffer size.| 9555 9556**Example** 9557 9558```ts 9559import { BusinessError } from '@kit.BasicServicesKit'; 9560 9561let bufferSize: number = 0; 9562 9563try { 9564 bufferSize = audioCapturer.getBufferSizeSync(); 9565 console.info(`AudioFrameworkRecLog: getBufferSizeSync :SUCCESS ${bufferSize}`); 9566} catch (err) { 9567 let error = err as BusinessError; 9568 console.error(`AudioFrameworkRecLog: getBufferSizeSync :ERROR : ${error}`); 9569} 9570``` 9571 9572### getCurrentInputDevices<sup>11+</sup> 9573 9574getCurrentInputDevices(): AudioDeviceDescriptors 9575 9576Obtains the information of the current input devices. This API returns the result synchronously. 9577 9578**System capability**: SystemCapability.Multimedia.Audio.Device 9579 9580**Return value** 9581 9582| Type | Description | 9583| ---------------------- | ------------------------------------------------------ | 9584| [AudioDeviceDescriptors](#audiodevicedescriptors) | An array of the audio device descriptors.| 9585 9586**Example** 9587 9588```ts 9589let deviceDescriptors: audio.AudioDeviceDescriptors = audioCapturer.getCurrentInputDevices(); 9590console.info(`Device id: ${deviceDescriptors[0].id}`); 9591console.info(`Device type: ${deviceDescriptors[0].deviceType}`); 9592console.info(`Device role: ${deviceDescriptors[0].deviceRole}`); 9593console.info(`Device name: ${deviceDescriptors[0].name}`); 9594console.info(`Device address: ${deviceDescriptors[0].address}`); 9595console.info(`Device samplerates: ${deviceDescriptors[0].sampleRates[0]}`); 9596console.info(`Device channelcounts: ${deviceDescriptors[0].channelCounts[0]}`); 9597console.info(`Device channelmask: ${deviceDescriptors[0].channelMasks[0]}`); 9598if (deviceDescriptors[0].encodingTypes) { 9599 console.info(`Device encodingTypes: ${deviceDescriptors[0].encodingTypes[0]}`); 9600} 9601``` 9602 9603### getCurrentAudioCapturerChangeInfo<sup>11+</sup> 9604 9605getCurrentAudioCapturerChangeInfo(): AudioCapturerChangeInfo 9606 9607Obtains the configuration changes of the current audio capturer. This API returns the result synchronously. 9608 9609**System capability**: SystemCapability.Multimedia.Audio.Device 9610 9611**Return value** 9612 9613| Type | Description | 9614| :--------------- | :---------------------------------- | 9615| [AudioCapturerChangeInfo](#audiocapturerchangeinfo9) | Configuration changes of the audio capturer.| 9616 9617**Example** 9618 9619```ts 9620let info: audio.AudioCapturerChangeInfo = audioCapturer.getCurrentAudioCapturerChangeInfo(); 9621console.info(`Info streamId: ${info.streamId}`); 9622console.info(`Info source: ${info.capturerInfo.source}`); 9623console.info(`Info capturerFlags: ${info.capturerInfo.capturerFlags}`); 9624console.info(`Info muted: ${info.muted}`); 9625console.info(`Info type: ${info.deviceDescriptors[0].deviceType}`); 9626console.info(`Info role: ${info.deviceDescriptors[0].deviceRole}`); 9627console.info(`Info name: ${info.deviceDescriptors[0].name}`); 9628console.info(`Info address: ${info.deviceDescriptors[0].address}`); 9629console.info(`Info samplerates: ${info.deviceDescriptors[0].sampleRates[0]}`); 9630console.info(`Info channelcounts: ${info.deviceDescriptors[0].channelCounts[0]}`); 9631console.info(`Info channelmask: ${info.deviceDescriptors[0].channelMasks[0]}`); 9632if (info.deviceDescriptors[0].encodingTypes) { 9633 console.info(`Device encodingTypes: ${info.deviceDescriptors[0].encodingTypes[0]}`); 9634} 9635``` 9636 9637### on('audioInterrupt')<sup>10+</sup> 9638 9639on(type: 'audioInterrupt', callback: Callback\<InterruptEvent>): void 9640 9641Subscribes to the audio interruption event, which is triggered when the audio focus is changed. This API uses an asynchronous callback to return the result. 9642 9643The AudioCapturer instance proactively gains the focus when the **start** event occurs and releases the focus when the **pause** or **stop** event occurs. Therefore, you do not need to request to gain or release the focus. 9644 9645After this API is called, an [InterruptEvent](#interruptevent9) is received when the AudioCapturer instance fails to obtain the focus or an audio interruption event occurs (for example, the audio stream is interrupted by others). It is recommended that the application perform further processing based on the **InterruptEvent** information. For details, see [Introduction to Audio Focus and Audio Sessions](../../media/audio/audio-playback-concurrency.md). 9646 9647**System capability**: SystemCapability.Multimedia.Audio.Interrupt 9648 9649**Parameters** 9650 9651| Name | Type | Mandatory| Description | 9652| -------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | 9653| type | string | Yes | Event type. The event **'audioInterrupt'** is triggered when the audio focus is changed.| 9654| callback | Callback\<[InterruptEvent](#interruptevent9)\> | Yes | Callback used to return the event information.| 9655 9656**Error codes** 9657 9658For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 9659 9660| ID| Error Message| 9661| ------- | --------------------------------------------| 9662| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 9663| 6800101 | Parameter verification failed. | 9664 9665**Example** 9666 9667```ts 9668import { audio } from '@kit.AudioKit'; 9669 9670let isCapturing: boolean; // An identifier specifying whether capturing is in progress. 9671onAudioInterrupt(); 9672 9673async function onAudioInterrupt(){ 9674 audioCapturer.on('audioInterrupt', (interruptEvent: audio.InterruptEvent) => { 9675 // When an audio interruption event occurs, the AudioCapturer receives the interruptEvent callback and performs processing based on the content in the callback. 9676 // 1. (Optional) The AudioCapturer reads the value of interruptEvent.forceType to see whether the system has forcibly performed the operation. 9677 // Note: In the default focus policy, INTERRUPT_HINT_RESUME maps to the force type INTERRUPT_SHARE, and others map to INTERRUPT_FORCE. Therefore, the value of forceType does not need to be checked. 9678 // 2. (Mandatory) The AudioCapturer then reads the value of interruptEvent.hintType and performs corresponding processing. 9679 if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) { 9680 // The audio focus event has been forcibly executed by the system. The application needs to update its status and displayed content. 9681 switch (interruptEvent.hintType) { 9682 case audio.InterruptHint.INTERRUPT_HINT_PAUSE: 9683 // The audio stream has been paused and temporarily loses the focus. It will receive the interruptEvent corresponding to resume when it is able to regain the focus. 9684 console.info('Force paused. Update capturing status and stop reading'); 9685 isCapturing = false; // A simplified processing indicating several operations for switching the application to the paused state. 9686 break; 9687 case audio.InterruptHint.INTERRUPT_HINT_STOP: 9688 // The audio stream has been stopped and permanently loses the focus. The user must manually trigger the operation to resume capturing. 9689 console.info('Force stopped. Update capturing status and stop reading'); 9690 isCapturing = false; // A simplified processing indicating several operations for switching the application to the paused state. 9691 break; 9692 default: 9693 console.info('Invalid interruptEvent'); 9694 break; 9695 } 9696 } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) { 9697 // The audio focus event needs to be operated by the application, which can choose the processing mode. It is recommended that the application process the event according to the value of InterruptHint. 9698 switch (interruptEvent.hintType) { 9699 case audio.InterruptHint.INTERRUPT_HINT_RESUME: 9700 // It is recommended that the application continue capturing. (The audio stream has been forcibly paused and temporarily lost the focus. It can resume capturing now.) 9701 // The INTERRUPT_HINT_RESUME operation must be proactively executed by the application and cannot be forcibly executed by the system. Therefore, the INTERRUPT_HINT_RESUME event must map to INTERRUPT_SHARE. 9702 console.info('Resume force paused renderer or ignore'); 9703 // To continue capturing, the application must perform the required operations. 9704 break; 9705 default: 9706 console.info('Invalid interruptEvent'); 9707 break; 9708 } 9709 } 9710 }); 9711} 9712``` 9713 9714### off('audioInterrupt')<sup>10+</sup> 9715 9716off(type: 'audioInterrupt'): void 9717 9718Unsubscribes from the audio interruption event. 9719 9720**System capability**: SystemCapability.Multimedia.Audio.Interrupt 9721 9722**Parameters** 9723 9724| Name | Type | Mandatory| Description | 9725| -------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | 9726| type | string | Yes | Event type. The event **'audioInterrupt'** is triggered when the audio focus is changed.| 9727 9728**Error codes** 9729 9730For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 9731 9732| ID| Error Message| 9733| ------- | --------------------------------------------| 9734| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 9735| 6800101 | Parameter verification failed. | 9736 9737**Example** 9738 9739```ts 9740audioCapturer.off('audioInterrupt'); 9741``` 9742 9743### on('inputDeviceChange')<sup>11+</sup> 9744 9745on(type: 'inputDeviceChange', callback: Callback\<AudioDeviceDescriptors>): void 9746 9747Subscribes to the audio input device change event, which is triggered when an audio input device is changed. This API uses an asynchronous callback to return the result. 9748 9749**System capability**: SystemCapability.Multimedia.Audio.Device 9750 9751**Parameters** 9752 9753| Name | Type | Mandatory| Description | 9754| :------- | :------------------------- | :--- | :------------------------------------------ | 9755| type | string | Yes | Event type. The event **'inputDeviceChange'** is triggered when an audio input device is changed.| 9756| callback | Callback\<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Yes | Callback used to return the information about the new audio input device.| 9757 9758**Error codes** 9759 9760For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 9761 9762| ID| Error Message| 9763| ------- | --------------------------------------------| 9764| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 9765| 6800101 | Parameter verification failed. | 9766 9767**Example** 9768 9769```ts 9770audioCapturer.on('inputDeviceChange', (deviceChangeInfo: audio.AudioDeviceDescriptors) => { 9771 console.info(`inputDevice id: ${deviceChangeInfo[0].id}`); 9772 console.info(`inputDevice deviceRole: ${deviceChangeInfo[0].deviceRole}`); 9773 console.info(`inputDevice deviceType: ${deviceChangeInfo[0].deviceType}`); 9774}); 9775``` 9776### off('inputDeviceChange')<sup>11+</sup> 9777 9778off(type: 'inputDeviceChange', callback?: Callback\<AudioDeviceDescriptors>): void 9779 9780Unsubscribes from the audio input device change event. This API uses an asynchronous callback to return the result. 9781 9782**System capability**: SystemCapability.Multimedia.Audio.Device 9783 9784**Parameters** 9785 9786| Name | Type | Mandatory| Description | 9787| :------- | :------------------------- | :--- |:-----------------------------------------| 9788| type | string | Yes | Event type. The event **'inputDeviceChange'** is triggered when an audio input device is changed.| 9789| callback | Callback\<[AudioDeviceDescriptors](#audiodevicedescriptors)> | No | Callback used to return the information about the audio input device.| 9790 9791**Error codes** 9792 9793For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 9794 9795| ID| Error Message| 9796| ------- | --------------------------------------------| 9797| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 9798| 6800101 | Parameter verification failed. | 9799 9800**Example** 9801 9802```ts 9803// Cancel all subscriptions to the event. 9804audioCapturer.off('inputDeviceChange'); 9805 9806// For the same event, if the callback parameter passed to the off API is the same as that passed to the on API, the off API cancels the subscription registered with the specified callback parameter. 9807let inputDeviceChangeCallback = (deviceChangeInfo: audio.AudioDeviceDescriptors) => { 9808 console.info(`inputDevice id: ${deviceChangeInfo[0].id}`); 9809 console.info(`inputDevice deviceRole: ${deviceChangeInfo[0].deviceRole}`); 9810 console.info(`inputDevice deviceType: ${deviceChangeInfo[0].deviceType}`); 9811}; 9812 9813audioCapturer.on('inputDeviceChange', inputDeviceChangeCallback); 9814 9815audioCapturer.off('inputDeviceChange', inputDeviceChangeCallback); 9816``` 9817 9818### on('audioCapturerChange')<sup>11+</sup> 9819 9820on(type: 'audioCapturerChange', callback: Callback\<AudioCapturerChangeInfo>): void 9821 9822Subscribes to the audio capturer configuration change event, which is triggered when the audio recording stream status or device is changed. This API uses an asynchronous callback to return the result. The subscription is implemented asynchronously and the callback, which is triggered when the audio capturer configuration changes, may fail to reflect the actual condition. 9823 9824**System capability**: SystemCapability.Multimedia.Audio.Capturer 9825 9826**Parameters** 9827 9828| Name | Type | Mandatory| Description | 9829| :------- | :------------------------- | :--- | :------------------------------------------ | 9830| type | string | Yes | Event type. The event **'audioCapturerChange'** is triggered when the audio recording stream status or device is changed.| 9831| callback | Callback\<[AudioCapturerChangeInfo](#audiocapturerchangeinfo9)> | Yes | Callback used to return the current configuration and status information of the audio capturer.| 9832 9833**Error codes** 9834 9835For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 9836 9837| ID| Error Message| 9838| ------- | --------------------------------------------| 9839| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 9840| 6800101 | Parameter verification failed. | 9841 9842**Example** 9843 9844```ts 9845audioCapturer.on('audioCapturerChange', (capturerChangeInfo: audio.AudioCapturerChangeInfo) => { 9846 console.info(`audioCapturerChange id: ${capturerChangeInfo[0].id}`); 9847 console.info(`audioCapturerChange deviceRole: ${capturerChangeInfo[0].deviceRole}`); 9848 console.info(`audioCapturerChange deviceType: ${capturerChangeInfo[0].deviceType}`); 9849}); 9850``` 9851 9852### off('audioCapturerChange')<sup>11+</sup> 9853 9854off(type: 'audioCapturerChange', callback?: Callback\<AudioCapturerChangeInfo>): void 9855 9856Unsubscribes from the audio capturer configuration change event. This API uses an asynchronous callback to return the result. 9857 9858**System capability**: SystemCapability.Multimedia.Audio.Capturer 9859 9860**Parameters** 9861 9862| Name | Type | Mandatory| Description | 9863| :------- | :------------------------- | :--- | :------------------------------------------ | 9864| type | string | Yes | Event type. The event **'audioCapturerChange'** is triggered when the audio capturer configuration is changed.| 9865| callback | Callback\<[AudioCapturerChangeInfo](#audiocapturerchangeinfo9)> | No | Callback used for unsubscription.| 9866 9867**Error codes** 9868 9869For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 9870 9871| ID| Error Message| 9872| ------- | --------------------------------------------| 9873| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 9874| 6800101 | Parameter verification failed. | 9875 9876**Example** 9877 9878```ts 9879// Cancel all subscriptions to the event. 9880audioCapturer.off('audioCapturerChange'); 9881 9882// For the same event, if the callback parameter passed to the off API is the same as that passed to the on API, the off API cancels the subscription registered with the specified callback parameter. 9883let audioCapturerChangeCallback = (capturerChangeInfo: audio.AudioCapturerChangeInfo) => { 9884 console.info(`audioCapturerChange id: ${capturerChangeInfo[0].id}`); 9885 console.info(`audioCapturerChange deviceRole: ${capturerChangeInfo[0].deviceRole}`); 9886 console.info(`audioCapturerChange deviceType: ${capturerChangeInfo[0].deviceType}`); 9887}; 9888 9889audioCapturer.on('audioCapturerChange', audioCapturerChangeCallback); 9890 9891audioCapturer.off('audioCapturerChange', audioCapturerChangeCallback); 9892``` 9893 9894### on('markReach')<sup>8+</sup> 9895 9896on(type: 'markReach', frame: number, callback: Callback<number>): void 9897 9898Subscribes to the mark reached event, which is triggered (only once) when the number of frames captured reaches the value of the **frame** parameter. This API uses an asynchronous callback to return the result. 9899 9900For example, if **frame** is set to **100**, the callback is invoked when the number of captured frames reaches the 100th frame. 9901 9902**System capability**: SystemCapability.Multimedia.Audio.Capturer 9903 9904**Parameters** 9905 9906| Name | Type | Mandatory| Description | 9907| :------- | :---------------------- | :--- | :----------------------------------------- | 9908| type | string | Yes | Event type. The event **'markReach'** is triggered when the number of frames captured reaches the value of the **frame** parameter.| 9909| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | 9910| callback | Callback\<number> | Yes | Callback used to return the value of the **frame** parameter.| 9911 9912**Example** 9913 9914```ts 9915audioCapturer.on('markReach', 1000, (position: number) => { 9916 if (position == 1000) { 9917 console.info('ON Triggered successfully'); 9918 } 9919}); 9920``` 9921 9922### off('markReach')<sup>8+</sup> 9923 9924off(type: 'markReach', callback?: Callback<number>): void 9925 9926Unsubscribes from the mark reached event. This API uses an asynchronous callback to return the result. 9927 9928**System capability**: SystemCapability.Multimedia.Audio.Capturer 9929 9930**Parameters** 9931 9932| Name| Type | Mandatory| Description | 9933| :----- | :----- | :--- | :------------------------------------------------ | 9934| type | string | Yes | Event type. The event **'markReach'** is triggered when the number of frames rendered reaches the value of the **frame** parameter.| 9935| callback<sup>18+</sup> | Callback\<number> | No | Callback used to return the value of the **frame** parameter.| 9936 9937**Example** 9938 9939```ts 9940// Cancel all subscriptions to the event. 9941audioCapturer.off('markReach'); 9942 9943// For the same event, if the callback parameter passed to the off API is the same as that passed to the on API, the off API cancels the subscription registered with the specified callback parameter. 9944let markReachCallback = (position: number) => { 9945 if (position == 1000) { 9946 console.info('ON Triggered successfully'); 9947 } 9948}; 9949 9950audioCapturer.on('markReach', 1000, markReachCallback); 9951 9952audioCapturer.off('markReach', markReachCallback); 9953``` 9954 9955### on('periodReach')<sup>8+</sup> 9956 9957on(type: 'periodReach', frame: number, callback: Callback<number>): void 9958 9959Subscribes to the period reached event, which is triggered each time the number of frames captured reaches the value of the **frame** parameter. In other words, the information is reported periodically. This API uses an asynchronous callback to return the result. 9960 9961For example, if **frame** is set to **10**, the callback is invoked each time 10 frames are captured, for example, when the number of frames captured reaches the 10th frame, 20th frame, and 30th frame. 9962 9963**System capability**: SystemCapability.Multimedia.Audio.Capturer 9964 9965**Parameters** 9966 9967| Name | Type | Mandatory| Description | 9968| :------- | :----------------------- | :--- | :------------------------------------------ | 9969| type | string | Yes | Event type. The event **'periodReach'** is triggered each time the number of frames captured reaches the value of the **frame** parameter.| 9970| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | 9971| callback | Callback\<number> | Yes |Callback used to return the value of the **frame** parameter. | 9972 9973**Example** 9974 9975```ts 9976audioCapturer.on('periodReach', 1000, (position: number) => { 9977 if (position == 1000) { 9978 console.info('ON Triggered successfully'); 9979 } 9980}); 9981``` 9982 9983### off('periodReach')<sup>8+</sup> 9984 9985off(type: 'periodReach', callback?: Callback<number>): void 9986 9987Unsubscribes from the period reached event. This API uses an asynchronous callback to return the result. 9988 9989**System capability**: SystemCapability.Multimedia.Audio.Capturer 9990 9991**Parameters** 9992 9993| Name| Type | Mandatory| Description | 9994| :----- | :----- | :--- | :-------------------------------------------------- | 9995| type | string | Yes | Event type. The event **'periodReach'** is triggered each time the number of frames rendered reaches the value of the **frame** parameter.| 9996| callback<sup>18+</sup> | Callback\<number> | No | Callback used to return the value of the **frame** parameter.| 9997 9998**Example** 9999 10000```ts 10001// Cancel all subscriptions to the event. 10002audioCapturer.off('periodReach'); 10003 10004// For the same event, if the callback parameter passed to the off API is the same as that passed to the on API, the off API cancels the subscription registered with the specified callback parameter. 10005let periodReachCallback = (position: number) => { 10006 if (position == 1000) { 10007 console.info('ON Triggered successfully'); 10008 } 10009}; 10010 10011audioCapturer.on('periodReach', periodReachCallback); 10012 10013audioCapturer.off('periodReach', periodReachCallback); 10014``` 10015 10016### on('stateChange')<sup>8+</sup> 10017 10018on(type: 'stateChange', callback: Callback<AudioState\>): void 10019 10020Subscribes to the audio capturer state change event, which is triggered when the state of the audio capturer is changed. This API uses an asynchronous callback to return the result. 10021 10022**System capability**: SystemCapability.Multimedia.Audio.Capturer 10023 10024**Parameters** 10025 10026| Name | Type | Mandatory| Description | 10027| :------- | :------------------------- | :--- | :------------------------------------------ | 10028| type | string | Yes | Event type. The event **'stateChange'** is triggered when the state of the audio capturer is changed.| 10029| callback | Callback\<[AudioState](#audiostate8)> | Yes | Callback used to return the audio status.| 10030 10031**Example** 10032 10033```ts 10034audioCapturer.on('stateChange', (state: audio.AudioState) => { 10035 if (state == 1) { 10036 console.info('audio capturer state is: STATE_PREPARED'); 10037 } 10038 if (state == 2) { 10039 console.info('audio capturer state is: STATE_RUNNING'); 10040 } 10041}); 10042``` 10043 10044### off('stateChange')<sup>18+</sup> 10045 10046off(type: 'stateChange', callback?: Callback<AudioState>): void 10047 10048Unsubscribes from the audio capturer state change event. This API uses an asynchronous callback to return the result. 10049 10050**System capability**: SystemCapability.Multimedia.Audio.Capturer 10051 10052**Parameters** 10053 10054| Name| Type | Mandatory| Description | 10055| :----- | :----- | :--- | :-------------------------------------------------- | 10056| type | string | Yes | Event type. The event **'stateChange'** is triggered when the state of the audio capturer is changed.| 10057| callback | Callback\<[AudioState](#audiostate8)> | No| Callback used to return the audio status.| 10058 10059**Error codes** 10060 10061For details about the error codes, see [Audio Error Codes](errorcode-audio.md). 10062 10063| ID| Error Message| 10064| ------- | --------------------------------------------| 10065| 6800101 | Parameter verification failed. | 10066 10067**Example** 10068 10069```ts 10070// Cancel all subscriptions to the event. 10071audioCapturer.off('stateChange'); 10072 10073// For the same event, if the callback parameter passed to the off API is the same as that passed to the on API, the off API cancels the subscription registered with the specified callback parameter. 10074let stateChangeCallback = (state: audio.AudioState) => { 10075 if (state == 1) { 10076 console.info('audio renderer state is: STATE_PREPARED'); 10077 } 10078 if (state == 2) { 10079 console.info('audio renderer state is: STATE_RUNNING'); 10080 } 10081}; 10082 10083audioCapturer.on('stateChange', stateChangeCallback); 10084 10085audioCapturer.off('stateChange', stateChangeCallback); 10086``` 10087 10088### on('readData')<sup>11+</sup> 10089 10090on(type: 'readData', callback: Callback\<ArrayBuffer>): void 10091 10092Subscribes to the audio data read event, which is triggered when audio stream data needs to be read. This API uses an asynchronous callback to return the result. 10093 10094The callback function is used only to read audio data. Do not call AudioCapturer APIs in it. 10095 10096**System capability**: SystemCapability.Multimedia.Audio.Capturer 10097 10098**Parameters** 10099 10100| Name | Type | Mandatory| Description | 10101| :------- |:-----------------------| :--- |:--------------------------| 10102| type | string | Yes | Event type. The event **'readData'** is triggered when audio stream data needs to be read.| 10103| callback | Callback\<ArrayBuffer> | Yes | Callback used to return the buffer from which the data is read. | 10104 10105**Error codes** 10106 10107For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 10108 10109| ID| Error Message| 10110| ------- | --------------------------------------------| 10111| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 10112| 6800101 | Parameter verification failed. | 10113 10114**Example** 10115 10116```ts 10117import { BusinessError } from '@kit.BasicServicesKit'; 10118import { fileIo as fs } from '@kit.CoreFileKit'; 10119import { common } from '@kit.AbilityKit'; 10120 10121class Options { 10122 offset?: number; 10123 length?: number; 10124} 10125 10126let bufferSize: number = 0; 10127// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. 10128let context = this.getUIContext().getHostContext() as common.UIAbilityContext; 10129let path = context.cacheDir; 10130// Ensure that the resource exists in the path. 10131let filePath = path + '/StarWars10s-2C-48000-4SW.pcm'; 10132let file: fs.File = fs.openSync(filePath, fs.OpenMode.READ_WRITE); 10133let readDataCallback = (buffer: ArrayBuffer) => { 10134 let options: Options = { 10135 offset: bufferSize, 10136 length: buffer.byteLength 10137 }; 10138 fs.writeSync(file.fd, buffer, options); 10139 bufferSize += buffer.byteLength; 10140} 10141 10142audioCapturer.on('readData', readDataCallback); 10143 10144audioCapturer.start((err: BusinessError) => { 10145 if (err) { 10146 console.error('Capturer start failed.'); 10147 } else { 10148 console.info('Capturer start success.'); 10149 } 10150}); 10151``` 10152 10153### off('readData')<sup>11+</sup> 10154 10155off(type: 'readData', callback?: Callback\<ArrayBuffer>): void 10156 10157Unsubscribes from the audio data read event. This API uses an asynchronous callback to return the result. 10158 10159**System capability**: SystemCapability.Multimedia.Audio.Capturer 10160 10161**Parameters** 10162 10163| Name | Type | Mandatory| Description | 10164| :------- |:-----------------------| :--- |:-------------------------------------------| 10165| type | string | Yes | Event type. The event **'readData'** is triggered when audio stream data needs to be read.| 10166| callback | Callback\<ArrayBuffer> | No | Callback used to return the buffer from which the data is read. | 10167 10168**Error codes** 10169 10170For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 10171 10172| ID| Error Message| 10173| ------- | --------------------------------------------| 10174| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 10175| 6800101 | Parameter verification failed. | 10176 10177**Example** 10178 10179```ts 10180// Cancel all subscriptions to the event. 10181audioCapturer.off('readData'); 10182 10183// For the same event, if the callback parameter passed to the off API is the same as that passed to the on API, the off API cancels the subscription registered with the specified callback parameter. 10184let readDataCallback = (data: ArrayBuffer) => { 10185 console.info(`read data: ${data}`); 10186}; 10187 10188audioCapturer.on('readData', readDataCallback); 10189 10190audioCapturer.off('readData', readDataCallback); 10191``` 10192 10193### getOverflowCount<sup>12+</sup> 10194 10195getOverflowCount(): Promise<number> 10196 10197Obtains the number of overflow audio frames in the audio stream that is being captured. This API uses a promise to return the result. 10198 10199**System capability**: SystemCapability.Multimedia.Audio.Capturer 10200 10201**Return value** 10202 10203| Type | Description | 10204| ------------------- | ----------------------------- | 10205| Promise<number>| Promise used to return the number of overflow audio frames.| 10206 10207**Example** 10208 10209```ts 10210import { BusinessError } from '@kit.BasicServicesKit'; 10211 10212audioCapturer.getOverflowCount().then((value: number) => { 10213 console.info(`Get overflow count Success! ${value}`); 10214}).catch((err: BusinessError) => { 10215 console.error(`Get overflow count Fail: ${err}`); 10216}); 10217``` 10218 10219### getOverflowCountSync<sup>12+</sup> 10220 10221getOverflowCountSync(): number 10222 10223Obtains the number of overflow audio frames in the audio stream that is being captured. This API returns the result synchronously. 10224 10225**System capability**: SystemCapability.Multimedia.Audio.Capturer 10226 10227**Return value** 10228 10229| Type | Description | 10230| ------------------- | ----------------------------- | 10231| number| Number of overflow audio frames.| 10232 10233**Example** 10234 10235```ts 10236import { BusinessError } from '@kit.BasicServicesKit'; 10237 10238try { 10239 let value: number = audioCapturer.getOverflowCountSync(); 10240 console.info(`Get overflow count Success! ${value}`); 10241} catch (err) { 10242 let error = err as BusinessError; 10243 console.error(`Get overflow count Fail: ${error}`); 10244} 10245``` 10246 10247### setWillMuteWhenInterrupted<sup>20+</sup> 10248 10249setWillMuteWhenInterrupted(muteWhenInterrupted: boolean): Promise<void> 10250 10251Sets whether to mute the current audio recording stream when an audio interruption occurs. This API uses a promise to return the result. 10252 10253**System capability**: SystemCapability.Multimedia.Audio.Capturer 10254 10255**Parameters** 10256 10257| Name | Type | Mandatory | Description | 10258| ---------- |---------------- | ------ |---------------------------------------------------------| 10259| muteWhenInterrupted | boolean | Yes | Whether to mute the current audio recording stream during an audio interruption. The value **true** means to mute it, and **false** (default value) means the opposite.| 10260 10261**Return value** 10262 10263| Type | Description | 10264| ------------------- | ----------------------------- | 10265| Promise<void>| Promise that returns no value.| 10266 10267**Error codes** 10268 10269For details about the error codes, see [Audio Error Codes](errorcode-audio.md). 10270 10271| ID| Error Message| 10272| ------- | --------------------------------------------| 10273| 6800103 | Operation not permit at current state. | 10274 10275**Example** 10276 10277```ts 10278import { BusinessError } from '@kit.BasicServicesKit'; 10279 10280audioRenderer.setWillMuteWhenInterrupted(true).then(() => { 10281 console.info('setWillMuteWhenInterrupted Success!'); 10282}).catch((err: BusinessError) => { 10283 console.error(`setWillMuteWhenInterrupted Fail: ${err}`); 10284}); 10285``` 10286 10287## ActiveDeviceType<sup>(deprecated)</sup> 10288 10289Enumerates the active device types. 10290 10291> **NOTE** 10292> 10293> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [CommunicationDeviceType](#communicationdevicetype9) instead. 10294 10295**System capability**: SystemCapability.Multimedia.Audio.Device 10296 10297| Name | Value | Description | 10298| ------------- | ------ | ---------------------------------------------------- | 10299| SPEAKER | 2 | Speaker. | 10300| BLUETOOTH_SCO | 7 | Bluetooth device using Synchronous Connection Oriented (SCO) links.| 10301 10302## InterruptActionType<sup>(deprecated)</sup> 10303 10304Enumerates the returned event types for audio interruption events. 10305 10306> **NOTE** 10307> 10308> This API is supported since API version 7 and deprecated since API version 9. No substitute is provided. 10309 10310**System capability**: SystemCapability.Multimedia.Audio.Renderer 10311 10312| Name | Value | Description | 10313| -------------- | ------ | ------------------ | 10314| TYPE_ACTIVATED | 0 | Focus gain event.| 10315| TYPE_INTERRUPT | 1 | Audio interruption event.| 10316 10317## AudioInterrupt<sup>(deprecated)</sup> 10318 10319Describes input parameters of audio interruption events. 10320 10321> **NOTE** 10322> 10323> This API is supported since API version 7 and deprecated since API version 9. No substitute is provided. 10324 10325**System capability**: SystemCapability.Multimedia.Audio.Renderer 10326 10327| Name | Type | Mandatory| Description | 10328| --------------- | --------------------------- | ----| ------------------------------------------------------------ | 10329| streamUsage | [StreamUsage](#streamusage) | Yes | Audio stream usage. | 10330| contentType | [ContentType](#contenttypedeprecated) | Yes | Audio content type. | 10331| pauseWhenDucked | boolean | Yes | Whether audio playback can be paused during an audio interruption. The value **true** means that audio playback can be paused during an audio interruption, and **false** means the opposite.| 10332 10333## InterruptAction<sup>(deprecated)</sup> 10334 10335Describes the callback invoked for audio interruption or focus gain events. 10336 10337> **NOTE** 10338> 10339> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [InterruptEvent](#interruptevent9) instead. 10340 10341**System capability**: SystemCapability.Multimedia.Audio.Renderer 10342 10343| Name | Type | Mandatory| Description | 10344| ---------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | 10345| actionType | [InterruptActionType](#interruptactiontypedeprecated) | Yes | Returned event type. The value **TYPE_ACTIVATED** means the focus gain event, and **TYPE_INTERRUPT** means the audio interruption event.| 10346| type | [InterruptType](#interrupttype) | No | Type of the audio interruption event. | 10347| hint | [InterruptHint](#interrupthint) | No | Hint provided along with the audio interruption event. | 10348| activated | boolean | No | Whether the focus is gained or released. The value **true** means that the focus is gained or released, and **false** means that the focus fails to be gained or released.| 10349