1# Interface (AudioCapturer) 2 3> **NOTE** 4> 5> - 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. 6> - The initial APIs of this interface are supported since API version 8. 7 8This interface provides APIs for audio capture. 9 10Before calling any API in AudioCapturer, you must use [createAudioCapturer](arkts-apis-audio-f.md#audiocreateaudiocapturer8) to create an AudioCapturer instance. 11 12## Modules to Import 13 14```ts 15import { audio } from '@kit.AudioKit'; 16``` 17 18## Properties 19 20**System capability**: SystemCapability.Multimedia.Audio.Capturer 21 22| Name | Type | Read-Only| Optional| Description | 23| :---- | :------------------------- | :--- | :--- | :--------------- | 24| state<sup>8+</sup> | [AudioState](arkts-apis-audio-e.md#audiostate8) | Yes| No | Audio capturer state.| 25 26**Example** 27 28```ts 29import { audio } from '@kit.AudioKit'; 30 31let state: audio.AudioState = audioCapturer.state; 32``` 33 34## getCapturerInfo<sup>8+</sup> 35 36getCapturerInfo(callback: AsyncCallback<AudioCapturerInfo\>): void 37 38Obtains the audio capturer information. This API uses an asynchronous callback to return the result. 39 40**System capability**: SystemCapability.Multimedia.Audio.Capturer 41 42**Parameters** 43 44| Name | Type | Mandatory| Description | 45| :------- | :-------------------------------- | :--- | :----------------------------------- | 46| callback | AsyncCallback<[AudioCapturerInfo](arkts-apis-audio-i.md#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.| 47 48**Example** 49 50```ts 51import { BusinessError } from '@kit.BasicServicesKit'; 52 53audioCapturer.getCapturerInfo((err: BusinessError, capturerInfo: audio.AudioCapturerInfo) => { 54 if (err) { 55 console.error('Failed to get capture info'); 56 } else { 57 console.info('Capturer getCapturerInfo:'); 58 console.info(`Capturer source: ${capturerInfo.source}`); 59 console.info(`Capturer flags: ${capturerInfo.capturerFlags}`); 60 } 61}); 62``` 63 64 65## getCapturerInfo<sup>8+</sup> 66 67getCapturerInfo(): Promise<AudioCapturerInfo\> 68 69Obtains the audio capturer information. This API uses a promise to return the result. 70 71**System capability**: SystemCapability.Multimedia.Audio.Capturer 72 73**Return value** 74 75| Type | Description | 76| :------------------------------------------------ | :---------------------------------- | 77| Promise<[AudioCapturerInfo](arkts-apis-audio-i.md#audiocapturerinfo8)\> | Promise used to return the audio capturer information.| 78 79**Example** 80 81```ts 82import { BusinessError } from '@kit.BasicServicesKit'; 83 84audioCapturer.getCapturerInfo().then((audioParamsGet: audio.AudioCapturerInfo) => { 85 if (audioParamsGet != undefined) { 86 console.info('AudioFrameworkRecLog: Capturer CapturerInfo:'); 87 console.info(`AudioFrameworkRecLog: Capturer SourceType: ${audioParamsGet.source}`); 88 console.info(`AudioFrameworkRecLog: Capturer capturerFlags: ${audioParamsGet.capturerFlags}`); 89 } else { 90 console.info(`AudioFrameworkRecLog: audioParamsGet is : ${audioParamsGet}`); 91 console.info('AudioFrameworkRecLog: audioParams getCapturerInfo are incorrect'); 92 } 93}).catch((err: BusinessError) => { 94 console.error(`AudioFrameworkRecLog: CapturerInfo :ERROR: ${err}`); 95}) 96``` 97 98## getCapturerInfoSync<sup>10+</sup> 99 100getCapturerInfoSync(): AudioCapturerInfo 101 102Obtains the audio capturer information. This API returns the result synchronously. 103 104**System capability**: SystemCapability.Multimedia.Audio.Capturer 105 106**Return value** 107 108| Type | Description | 109| :------------------------------------------------ | :---------------------------------- | 110| [AudioCapturerInfo](arkts-apis-audio-i.md#audiocapturerinfo8) | Audio capturer information.| 111 112**Example** 113 114```ts 115import { BusinessError } from '@kit.BasicServicesKit'; 116 117try { 118 let audioParamsGet: audio.AudioCapturerInfo = audioCapturer.getCapturerInfoSync(); 119 console.info(`AudioFrameworkRecLog: Capturer SourceType: ${audioParamsGet.source}`); 120 console.info(`AudioFrameworkRecLog: Capturer capturerFlags: ${audioParamsGet.capturerFlags}`); 121} catch (err) { 122 let error = err as BusinessError; 123 console.error(`AudioFrameworkRecLog: CapturerInfo :ERROR: ${error}`); 124} 125``` 126 127## getStreamInfo<sup>8+</sup> 128 129getStreamInfo(callback: AsyncCallback<AudioStreamInfo\>): void 130 131Obtains the stream information of this audio capturer. This API uses an asynchronous callback to return the result. 132 133**System capability**: SystemCapability.Multimedia.Audio.Capturer 134 135**Parameters** 136 137| Name | Type | Mandatory| Description | 138| :------- | :--------------------------------------------------- | :--- | :------------------------------- | 139| callback | AsyncCallback<[AudioStreamInfo](arkts-apis-audio-i.md#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.| 140 141**Example** 142 143```ts 144import { BusinessError } from '@kit.BasicServicesKit'; 145 146audioCapturer.getStreamInfo((err: BusinessError, streamInfo: audio.AudioStreamInfo) => { 147 if (err) { 148 console.error('Failed to get stream info'); 149 } else { 150 console.info('Capturer GetStreamInfo:'); 151 console.info(`Capturer sampling rate: ${streamInfo.samplingRate}`); 152 console.info(`Capturer channel: ${streamInfo.channels}`); 153 console.info(`Capturer format: ${streamInfo.sampleFormat}`); 154 console.info(`Capturer encoding type: ${streamInfo.encodingType}`); 155 } 156}); 157``` 158 159## getStreamInfo<sup>8+</sup> 160 161getStreamInfo(): Promise<AudioStreamInfo\> 162 163Obtains the stream information of this audio capturer. This API uses a promise to return the result. 164 165**System capability**: SystemCapability.Multimedia.Audio.Capturer 166 167**Return value** 168 169| Type | Description | 170| :--------------------------------------------- | :------------------------------ | 171| Promise<[AudioStreamInfo](arkts-apis-audio-i.md#audiostreaminfo8)\> | Promise used to return the stream information.| 172 173**Example** 174 175```ts 176import { BusinessError } from '@kit.BasicServicesKit'; 177 178audioCapturer.getStreamInfo().then((audioParamsGet: audio.AudioStreamInfo) => { 179 console.info('getStreamInfo:'); 180 console.info(`sampleFormat: ${audioParamsGet.sampleFormat}`); 181 console.info(`samplingRate: ${audioParamsGet.samplingRate}`); 182 console.info(`channels: ${audioParamsGet.channels}`); 183 console.info(`encodingType: ${audioParamsGet.encodingType}`); 184}).catch((err: BusinessError) => { 185 console.error(`getStreamInfo :ERROR: ${err}`); 186}); 187``` 188 189## getStreamInfoSync<sup>10+</sup> 190 191getStreamInfoSync(): AudioStreamInfo 192 193Obtains the stream information of this audio capturer. This API returns the result synchronously. 194 195**System capability**: SystemCapability.Multimedia.Audio.Capturer 196 197**Return value** 198 199| Type | Description | 200| :--------------------------------------------- | :------------------------------ | 201| [AudioStreamInfo](arkts-apis-audio-i.md#audiostreaminfo8) | Stream information.| 202 203**Example** 204 205```ts 206import { BusinessError } from '@kit.BasicServicesKit'; 207 208try { 209 let audioParamsGet: audio.AudioStreamInfo = audioCapturer.getStreamInfoSync(); 210 console.info(`sampleFormat: ${audioParamsGet.sampleFormat}`); 211 console.info(`samplingRate: ${audioParamsGet.samplingRate}`); 212 console.info(`channels: ${audioParamsGet.channels}`); 213 console.info(`encodingType: ${audioParamsGet.encodingType}`); 214} catch (err) { 215 let error = err as BusinessError; 216 console.error(`getStreamInfo :ERROR: ${error}`); 217} 218``` 219 220## getAudioStreamId<sup>9+</sup> 221 222getAudioStreamId(callback: AsyncCallback<number\>): void 223 224Obtains the stream ID of this audio capturer. This API uses an asynchronous callback to return the result. 225 226**System capability**: SystemCapability.Multimedia.Audio.Capturer 227 228**Parameters** 229 230| Name | Type | Mandatory| Description | 231| :------- | :--------------------------------------------------- | :--- | :------------------- | 232| 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.| 233 234**Example** 235 236```ts 237import { BusinessError } from '@kit.BasicServicesKit'; 238 239audioCapturer.getAudioStreamId((err: BusinessError, streamId: number) => { 240 console.info(`audioCapturer GetStreamId: ${streamId}`); 241}); 242``` 243 244## getAudioStreamId<sup>9+</sup> 245 246getAudioStreamId(): Promise<number\> 247 248Obtains the stream ID of this audio capturer. This API uses a promise to return the result. 249 250**System capability**: SystemCapability.Multimedia.Audio.Capturer 251 252**Return value** 253 254| Type | Description | 255| :----------------| :--------------------- | 256| Promise<number\> | Promise used to return the stream ID.| 257 258**Example** 259 260```ts 261import { BusinessError } from '@kit.BasicServicesKit'; 262 263audioCapturer.getAudioStreamId().then((streamId: number) => { 264 console.info(`audioCapturer getAudioStreamId: ${streamId}`); 265}).catch((err: BusinessError) => { 266 console.error(`ERROR: ${err}`); 267}); 268``` 269 270## getAudioStreamIdSync<sup>10+</sup> 271 272getAudioStreamIdSync(): number 273 274Obtains the stream ID of this audio capturer. This API returns the result synchronously. 275 276**System capability**: SystemCapability.Multimedia.Audio.Capturer 277 278**Return value** 279 280| Type | Description | 281| :----------------| :--------------------- | 282| number | Stream ID.| 283 284**Example** 285 286```ts 287import { BusinessError } from '@kit.BasicServicesKit'; 288 289try { 290 let streamId: number = audioCapturer.getAudioStreamIdSync(); 291 console.info(`audioCapturer getAudioStreamIdSync: ${streamId}`); 292} catch (err) { 293 let error = err as BusinessError; 294 console.error(`ERROR: ${error}`); 295} 296``` 297 298## start<sup>8+</sup> 299 300start(callback: AsyncCallback<void\>): void 301 302Starts this audio capturer to start capturing audio data. This API uses an asynchronous callback to return the result. 303 304**System capability**: SystemCapability.Multimedia.Audio.Capturer 305 306**Parameters** 307 308| Name | Type | Mandatory| Description | 309| :------- | :------------------- | :--- | :----------------------------- | 310| 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.| 311 312**Example** 313 314```ts 315import { BusinessError } from '@kit.BasicServicesKit'; 316 317audioCapturer.start((err: BusinessError) => { 318 if (err) { 319 console.error('Capturer start failed.'); 320 } else { 321 console.info('Capturer start success.'); 322 } 323}); 324``` 325 326 327## start<sup>8+</sup> 328 329start(): Promise<void\> 330 331Starts this audio capturer to start capturing audio data. This API uses a promise to return the result. 332 333**System capability**: SystemCapability.Multimedia.Audio.Capturer 334 335**Return value** 336 337| Type | Description | 338| :------------- | :---------------------------- | 339| Promise<void\> | Promise object, which indicates that the capturer is started successfully. If the operation fails, an error object with 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.| 340 341**Example** 342 343```ts 344import { BusinessError } from '@kit.BasicServicesKit'; 345 346audioCapturer.start().then(() => { 347 console.info('AudioFrameworkRecLog: ---------START---------'); 348 console.info('AudioFrameworkRecLog: Capturer started: SUCCESS'); 349 console.info(`AudioFrameworkRecLog: AudioCapturer: STATE: ${audioCapturer.state}`); 350 console.info('AudioFrameworkRecLog: Capturer started: SUCCESS'); 351 if ((audioCapturer.state == audio.AudioState.STATE_RUNNING)) { 352 console.info('AudioFrameworkRecLog: AudioCapturer is in Running State'); 353 } 354}).catch((err: BusinessError) => { 355 console.error(`AudioFrameworkRecLog: Capturer start :ERROR : ${err}`); 356}); 357``` 358 359## stop<sup>8+</sup> 360 361stop(callback: AsyncCallback<void\>): void 362 363Stops this audio capturer, ceasing the input audio stream. This API uses an asynchronous callback to return the result. 364 365**System capability**: SystemCapability.Multimedia.Audio.Capturer 366 367**Parameters** 368 369| Name | Type | Mandatory| Description | 370| :------- | :------------------- | :--- | :----------------------------- | 371| callback | AsyncCallback<void\> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 372 373**Example** 374 375```ts 376import { BusinessError } from '@kit.BasicServicesKit'; 377 378audioCapturer.stop((err: BusinessError) => { 379 if (err) { 380 console.error('Capturer stop failed'); 381 } else { 382 console.info('Capturer stopped.'); 383 } 384}); 385``` 386 387 388## stop<sup>8+</sup> 389 390stop(): Promise<void\> 391 392Stops this audio capturer, ceasing the input audio stream. This API uses a promise to return the result. 393 394**System capability**: SystemCapability.Multimedia.Audio.Capturer 395 396**Return value** 397 398| Type | Description | 399| :------------- | :---------------------------- | 400| Promise<void\> | Promise that returns no value.| 401 402**Example** 403 404```ts 405import { BusinessError } from '@kit.BasicServicesKit'; 406 407audioCapturer.stop().then(() => { 408 console.info('AudioFrameworkRecLog: ---------STOP RECORD---------'); 409 console.info('AudioFrameworkRecLog: Capturer stopped: SUCCESS'); 410 if ((audioCapturer.state == audio.AudioState.STATE_STOPPED)){ 411 console.info('AudioFrameworkRecLog: State is Stopped:'); 412 } 413}).catch((err: BusinessError) => { 414 console.error(`AudioFrameworkRecLog: Capturer stop: ERROR: ${err}`); 415}); 416``` 417 418## release<sup>8+</sup> 419 420release(callback: AsyncCallback<void\>): void 421 422Releases this audio capturer. This API uses an asynchronous callback to return the result. 423 424**System capability**: SystemCapability.Multimedia.Audio.Capturer 425 426**Parameters** 427 428| Name | Type | Mandatory| Description | 429| :------- | :------------------- | :--- | :---------------------------------- | 430| callback | AsyncCallback<void\> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 431 432**Example** 433 434```ts 435import { BusinessError } from '@kit.BasicServicesKit'; 436 437audioCapturer.release((err: BusinessError) => { 438 if (err) { 439 console.error('capturer release failed'); 440 } else { 441 console.info('capturer released.'); 442 } 443}); 444``` 445 446 447## release<sup>8+</sup> 448 449release(): Promise<void\> 450 451Releases this audio capturer. This API uses a promise to return the result. 452 453**System capability**: SystemCapability.Multimedia.Audio.Capturer 454 455**Return value** 456 457| Type | Description | 458| :------------- | :---------------------------- | 459| Promise<void\> | Promise that returns no value.| 460 461**Example** 462 463```ts 464import { BusinessError } from '@kit.BasicServicesKit'; 465 466audioCapturer.release().then(() => { 467 console.info('AudioFrameworkRecLog: ---------RELEASE RECORD---------'); 468 console.info('AudioFrameworkRecLog: Capturer release : SUCCESS'); 469 console.info(`AudioFrameworkRecLog: AudioCapturer : STATE : ${audioCapturer.state}`); 470}).catch((err: BusinessError) => { 471 console.error(`AudioFrameworkRecLog: Capturer stop: ERROR: ${err}`); 472}); 473``` 474 475 476## getAudioTime<sup>8+</sup> 477 478getAudioTime(callback: AsyncCallback<number\>): void 479 480Obtains 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. 481 482**System capability**: SystemCapability.Multimedia.Audio.Capturer 483 484**Parameters** 485 486| Name | Type | Mandatory| Description | 487| :------- | :--------------------- | :--- | :----------------------------- | 488| 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.| 489 490**Example** 491 492```ts 493import { BusinessError } from '@kit.BasicServicesKit'; 494 495audioCapturer.getAudioTime((err: BusinessError, timestamp: number) => { 496 console.info(`Current timestamp: ${timestamp}`); 497}); 498``` 499 500## getAudioTime<sup>8+</sup> 501 502getAudioTime(): Promise<number\> 503 504Obtains 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. 505 506**System capability**: SystemCapability.Multimedia.Audio.Capturer 507 508**Return value** 509 510| Type | Description | 511| :--------------- | :---------------------------- | 512| Promise<number\> | Promise used to return the number of nanoseconds elapsed from the Unix epoch.| 513 514**Example** 515 516```ts 517import { BusinessError } from '@kit.BasicServicesKit'; 518 519audioCapturer.getAudioTime().then((audioTime: number) => { 520 console.info(`AudioFrameworkRecLog: AudioCapturer getAudioTime : Success ${audioTime}`); 521}).catch((err: BusinessError) => { 522 console.error(`AudioFrameworkRecLog: AudioCapturer Created : ERROR : ${err}`); 523}); 524``` 525 526## getAudioTimeSync<sup>10+</sup> 527 528getAudioTimeSync(): number 529 530Obtains the timestamp of the current recording position, measured in nanoseconds from the Unix epoch (January 1, 1970). This API returns the result synchronously. 531 532**System capability**: SystemCapability.Multimedia.Audio.Capturer 533 534**Return value** 535 536| Type | Description | 537| :--------------- | :---------------------------- | 538| number | Timestamp.| 539 540**Example** 541 542```ts 543import { BusinessError } from '@kit.BasicServicesKit'; 544 545try { 546 let audioTime: number = audioCapturer.getAudioTimeSync(); 547 console.info(`AudioFrameworkRecLog: AudioCapturer getAudioTimeSync : Success ${audioTime}`); 548} catch (err) { 549 let error = err as BusinessError; 550 console.error(`AudioFrameworkRecLog: AudioCapturer getAudioTimeSync : ERROR : ${error}`); 551} 552``` 553 554## getAudioTimestampInfo<sup>19+</sup> 555 556getAudioTimestampInfo(): Promise\<AudioTimestampInfo> 557 558Obtains the timestamp and position information of an input audio stream. 559 560This API obtains the actual recording position (specified by **framePosition**) of the audio channel and the timestamp when recording to that position (specified by **timestamp**, in nanoseconds). 561 562**System capability**: SystemCapability.Multimedia.Audio.Capturer 563 564**Return value** 565 566| Type | Description | 567|-------------------------------------------------------| ----------------------- | 568| Promise\<[AudioTimestampInfo](arkts-apis-audio-i.md#audiotimestampinfo19)> | Promise used to return the timestamp and position information.| 569 570**Error codes** 571 572For details about the error codes, see [Audio Error Codes](errorcode-audio.md). 573 574| ID| Error Message| 575| ------- | --------------------------------------------| 576| 6800103 | Operation not permit at current state. | 577 578**Example** 579 580```ts 581import { BusinessError } from '@kit.BasicServicesKit'; 582 583audioCapturer.getAudioTimestampInfo().then((audioTimestampInfo: audio.AudioTimestampInfo) => { 584 console.info(`Current timestamp: ${audioTimestampInfo.timestamp}`); 585}).catch((err: BusinessError) => { 586 console.error(`ERROR: ${err}`); 587}); 588``` 589 590## getAudioTimestampInfoSync<sup>19+</sup> 591 592getAudioTimestampInfoSync(): AudioTimestampInfo 593 594Obtains the timestamp and position information of an input audio stream. This API returns the result synchronously. 595 596**System capability**: SystemCapability.Multimedia.Audio.Capturer 597 598**Return value** 599 600| Type | Description | 601| ---------------- | ----------------------- | 602| [AudioTimestampInfo](arkts-apis-audio-i.md#audiotimestampinfo19) | Information about the timestamp and position information.| 603 604**Error codes** 605 606For details about the error codes, see [Audio Error Codes](errorcode-audio.md). 607 608| ID| Error Message| 609| ------- | --------------------------------------------| 610| 6800103 | Operation not permit at current state. | 611 612**Example** 613 614```ts 615import { BusinessError } from '@kit.BasicServicesKit'; 616 617try { 618 let audioTimestampInfo: audio.AudioTimestampInfo = audioCapturer.getAudioTimestampInfoSync(); 619 console.info(`Current timestamp: ${audioTimestampInfo.timestamp}`); 620} catch (err) { 621 let error = err as BusinessError; 622 console.error(`ERROR: ${error}`); 623} 624``` 625 626## getBufferSize<sup>8+</sup> 627 628getBufferSize(callback: AsyncCallback<number\>): void 629 630Obtains a reasonable minimum buffer size in bytes for capturing. This API uses an asynchronous callback to return the result. 631 632**System capability**: SystemCapability.Multimedia.Audio.Capturer 633 634**Parameters** 635 636| Name | Type | Mandatory| Description | 637| :------- | :--------------------- | :--- | :----------------------------------- | 638| 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.| 639 640**Example** 641 642```ts 643import { BusinessError } from '@kit.BasicServicesKit'; 644 645audioCapturer.getBufferSize((err: BusinessError, bufferSize: number) => { 646 if (!err) { 647 console.info(`BufferSize : ${bufferSize}`); 648 audioCapturer.read(bufferSize, true).then((buffer: ArrayBuffer) => { 649 console.info(`Buffer read is ${buffer.byteLength}`); 650 }).catch((err: BusinessError) => { 651 console.error(`AudioFrameworkRecLog: AudioCapturer Created : ERROR : ${err}`); 652 }); 653 } 654}); 655``` 656 657## getBufferSize<sup>8+</sup> 658 659getBufferSize(): Promise<number\> 660 661Obtains a reasonable minimum buffer size in bytes for capturing. This API uses a promise to return the result. 662 663**System capability**: SystemCapability.Multimedia.Audio.Capturer 664 665**Return value** 666 667| Type | Description | 668| :--------------- | :---------------------------------- | 669| Promise<number\> | Promise used to return the buffer size.| 670 671**Example** 672 673```ts 674import { BusinessError } from '@kit.BasicServicesKit'; 675 676let bufferSize: number = 0; 677 678audioCapturer.getBufferSize().then((data: number) => { 679 console.info(`AudioFrameworkRecLog: getBufferSize :SUCCESS ${data}`); 680 bufferSize = data; 681}).catch((err: BusinessError) => { 682 console.error(`AudioFrameworkRecLog: getBufferSize :ERROR : ${err}`); 683}); 684``` 685 686## getBufferSizeSync<sup>10+</sup> 687 688getBufferSizeSync(): number 689 690Obtains a reasonable minimum buffer size in bytes for capturing. This API returns the result synchronously. 691 692**System capability**: SystemCapability.Multimedia.Audio.Capturer 693 694**Return value** 695 696| Type | Description | 697| :--------------- | :---------------------------------- | 698| number | Buffer size.| 699 700**Example** 701 702```ts 703import { BusinessError } from '@kit.BasicServicesKit'; 704 705let bufferSize: number = 0; 706 707try { 708 bufferSize = audioCapturer.getBufferSizeSync(); 709 console.info(`AudioFrameworkRecLog: getBufferSizeSync :SUCCESS ${bufferSize}`); 710} catch (err) { 711 let error = err as BusinessError; 712 console.error(`AudioFrameworkRecLog: getBufferSizeSync :ERROR : ${error}`); 713} 714``` 715 716## getCurrentInputDevices<sup>11+</sup> 717 718getCurrentInputDevices(): AudioDeviceDescriptors 719 720Obtains the information of the current input devices. This API returns the result synchronously. 721 722**System capability**: SystemCapability.Multimedia.Audio.Device 723 724**Return value** 725 726| Type | Description | 727| ---------------------- | ------------------------------------------------------ | 728| [AudioDeviceDescriptors](arkts-apis-audio-t.md#audiodevicedescriptors) | An array of the audio device descriptors.| 729 730**Example** 731 732```ts 733let deviceDescriptors: audio.AudioDeviceDescriptors = audioCapturer.getCurrentInputDevices(); 734console.info(`Device id: ${deviceDescriptors[0].id}`); 735console.info(`Device type: ${deviceDescriptors[0].deviceType}`); 736console.info(`Device role: ${deviceDescriptors[0].deviceRole}`); 737console.info(`Device name: ${deviceDescriptors[0].name}`); 738console.info(`Device address: ${deviceDescriptors[0].address}`); 739console.info(`Device samplerates: ${deviceDescriptors[0].sampleRates[0]}`); 740console.info(`Device channelcounts: ${deviceDescriptors[0].channelCounts[0]}`); 741console.info(`Device channelmask: ${deviceDescriptors[0].channelMasks[0]}`); 742if (deviceDescriptors[0].encodingTypes) { 743 console.info(`Device encodingTypes: ${deviceDescriptors[0].encodingTypes[0]}`); 744} 745``` 746 747## getCurrentAudioCapturerChangeInfo<sup>11+</sup> 748 749getCurrentAudioCapturerChangeInfo(): AudioCapturerChangeInfo 750 751Obtains the configuration changes of the current audio capturer. This API returns the result synchronously. 752 753**System capability**: SystemCapability.Multimedia.Audio.Device 754 755**Return value** 756 757| Type | Description | 758| :--------------- | :---------------------------------- | 759| [AudioCapturerChangeInfo](arkts-apis-audio-i.md#audiocapturerchangeinfo9) | Configuration changes of the audio capturer.| 760 761**Example** 762 763```ts 764let info: audio.AudioCapturerChangeInfo = audioCapturer.getCurrentAudioCapturerChangeInfo(); 765console.info(`Info streamId: ${info.streamId}`); 766console.info(`Info source: ${info.capturerInfo.source}`); 767console.info(`Info capturerFlags: ${info.capturerInfo.capturerFlags}`); 768console.info(`Info muted: ${info.muted}`); 769console.info(`Info type: ${info.deviceDescriptors[0].deviceType}`); 770console.info(`Info role: ${info.deviceDescriptors[0].deviceRole}`); 771console.info(`Info name: ${info.deviceDescriptors[0].name}`); 772console.info(`Info address: ${info.deviceDescriptors[0].address}`); 773console.info(`Info samplerates: ${info.deviceDescriptors[0].sampleRates[0]}`); 774console.info(`Info channelcounts: ${info.deviceDescriptors[0].channelCounts[0]}`); 775console.info(`Info channelmask: ${info.deviceDescriptors[0].channelMasks[0]}`); 776if (info.deviceDescriptors[0].encodingTypes) { 777 console.info(`Device encodingTypes: ${info.deviceDescriptors[0].encodingTypes[0]}`); 778} 779``` 780 781## on('audioInterrupt')<sup>10+</sup> 782 783on(type: 'audioInterrupt', callback: Callback\<InterruptEvent>): void 784 785Subscribes to the audio interruption event, which is triggered when the audio focus is changed. This API uses an asynchronous callback to return the result. 786 787The 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. 788 789After this API is called, an [InterruptEvent](arkts-apis-audio-i.md#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). 790 791**System capability**: SystemCapability.Multimedia.Audio.Interrupt 792 793**Parameters** 794 795| Name | Type | Mandatory| Description | 796| -------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | 797| type | string | Yes | Event type. The event **'audioInterrupt'** is triggered when the audio focus is changed.| 798| callback | Callback\<[InterruptEvent](arkts-apis-audio-i.md#interruptevent9)\> | Yes | Callback used to return the event information.| 799 800**Error codes** 801 802For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 803 804| ID| Error Message| 805| ------- | --------------------------------------------| 806| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 807| 6800101 | Parameter verification failed. | 808 809**Example** 810 811```ts 812import { audio } from '@kit.AudioKit'; 813 814let isCapturing: boolean; // An identifier specifying whether capturing is in progress. 815onAudioInterrupt(); 816 817async function onAudioInterrupt(){ 818 audioCapturer.on('audioInterrupt', (interruptEvent: audio.InterruptEvent) => { 819 // When an audio interruption event occurs, the AudioCapturer receives the interruptEvent callback and performs processing based on the content in the callback. 820 // 1. (Optional) The AudioCapturer reads the value of interruptEvent.forceType to see whether the system has forcibly performed the operation. 821 // 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. 822 // 2. (Mandatory) The AudioCapturer then reads the value of interruptEvent.hintType and performs corresponding processing. 823 if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) { 824 // The audio focus event has been forcibly executed by the system. The application needs to update its status and displayed content. 825 switch (interruptEvent.hintType) { 826 case audio.InterruptHint.INTERRUPT_HINT_PAUSE: 827 // 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. 828 console.info('Force paused. Update capturing status and stop reading'); 829 isCapturing = false; // A simplified processing indicating several operations for switching the application to the paused state. 830 break; 831 case audio.InterruptHint.INTERRUPT_HINT_STOP: 832 // The audio stream has been stopped and permanently loses the focus. The user must manually trigger the operation to resume capturing. 833 console.info('Force stopped. Update capturing status and stop reading'); 834 isCapturing = false; // A simplified processing indicating several operations for switching the application to the paused state. 835 break; 836 default: 837 console.info('Invalid interruptEvent'); 838 break; 839 } 840 } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) { 841 // 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. 842 switch (interruptEvent.hintType) { 843 case audio.InterruptHint.INTERRUPT_HINT_RESUME: 844 // 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.) 845 // 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. 846 console.info('Resume force paused renderer or ignore'); 847 // To continue capturing, the application must perform the required operations. 848 break; 849 default: 850 console.info('Invalid interruptEvent'); 851 break; 852 } 853 } 854 }); 855} 856``` 857 858## off('audioInterrupt')<sup>10+</sup> 859 860off(type: 'audioInterrupt'): void 861 862Unsubscribes from the audio interruption event. 863 864**System capability**: SystemCapability.Multimedia.Audio.Interrupt 865 866**Parameters** 867 868| Name | Type | Mandatory| Description | 869| -------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | 870| type | string | Yes | Event type. The event **'audioInterrupt'** is triggered when the audio focus is changed.| 871 872**Error codes** 873 874For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 875 876| ID| Error Message| 877| ------- | --------------------------------------------| 878| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 879| 6800101 | Parameter verification failed. | 880 881**Example** 882 883```ts 884audioCapturer.off('audioInterrupt'); 885``` 886 887## on('inputDeviceChange')<sup>11+</sup> 888 889on(type: 'inputDeviceChange', callback: Callback\<AudioDeviceDescriptors>): void 890 891Subscribes 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. 892 893**System capability**: SystemCapability.Multimedia.Audio.Device 894 895**Parameters** 896 897| Name | Type | Mandatory| Description | 898| :------- | :------------------------- | :--- | :------------------------------------------ | 899| type | string | Yes | Event type. The event **'inputDeviceChange'** is triggered when an audio input device is changed.| 900| callback | Callback\<[AudioDeviceDescriptors](arkts-apis-audio-t.md#audiodevicedescriptors) > | Yes | Callback used to return the information about the new audio input device.| 901 902**Error codes** 903 904For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 905 906| ID| Error Message| 907| ------- | --------------------------------------------| 908| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 909| 6800101 | Parameter verification failed. | 910 911**Example** 912 913```ts 914audioCapturer.on('inputDeviceChange', (deviceChangeInfo: audio.AudioDeviceDescriptors) => { 915 console.info(`inputDevice id: ${deviceChangeInfo[0].id}`); 916 console.info(`inputDevice deviceRole: ${deviceChangeInfo[0].deviceRole}`); 917 console.info(`inputDevice deviceType: ${deviceChangeInfo[0].deviceType}`); 918}); 919``` 920## off('inputDeviceChange')<sup>11+</sup> 921 922off(type: 'inputDeviceChange', callback?: Callback\<AudioDeviceDescriptors>): void 923 924Unsubscribes from the audio input device change event. This API uses an asynchronous callback to return the result. 925 926**System capability**: SystemCapability.Multimedia.Audio.Device 927 928**Parameters** 929 930| Name | Type | Mandatory| Description | 931| :------- | :------------------------- | :--- |:-----------------------------------------| 932| type | string | Yes | Event type. The event **'inputDeviceChange'** is triggered when an audio input device is changed.| 933| callback | Callback\<[AudioDeviceDescriptors](arkts-apis-audio-t.md#audiodevicedescriptors) > | No | Callback used to return the information about the audio input device.| 934 935**Error codes** 936 937For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 938 939| ID| Error Message| 940| ------- | --------------------------------------------| 941| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 942| 6800101 | Parameter verification failed. | 943 944**Example** 945 946```ts 947// Cancel all subscriptions to the event. 948audioCapturer.off('inputDeviceChange'); 949 950// 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. 951let inputDeviceChangeCallback = (deviceChangeInfo: audio.AudioDeviceDescriptors) => { 952 console.info(`inputDevice id: ${deviceChangeInfo[0].id}`); 953 console.info(`inputDevice deviceRole: ${deviceChangeInfo[0].deviceRole}`); 954 console.info(`inputDevice deviceType: ${deviceChangeInfo[0].deviceType}`); 955}; 956 957audioCapturer.on('inputDeviceChange', inputDeviceChangeCallback); 958 959audioCapturer.off('inputDeviceChange', inputDeviceChangeCallback); 960``` 961 962## on('audioCapturerChange')<sup>11+</sup> 963 964on(type: 'audioCapturerChange', callback: Callback\<AudioCapturerChangeInfo>): void 965 966Subscribes 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. 967 968**System capability**: SystemCapability.Multimedia.Audio.Capturer 969 970**Parameters** 971 972| Name | Type | Mandatory| Description | 973| :------- | :------------------------- | :--- | :------------------------------------------ | 974| type | string | Yes | Event type. The event **'audioCapturerChange'** is triggered when the audio recording stream status or device is changed.| 975| callback | Callback\<[AudioCapturerChangeInfo](arkts-apis-audio-i.md#audiocapturerchangeinfo9)> | Yes | Callback used to return the current configuration and status information of the audio capturer.| 976 977**Error codes** 978 979For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 980 981| ID| Error Message| 982| ------- | --------------------------------------------| 983| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 984| 6800101 | Parameter verification failed. | 985 986**Example** 987 988```ts 989audioCapturer.on('audioCapturerChange', (capturerChangeInfo: audio.AudioCapturerChangeInfo) => { 990 console.info(`audioCapturerChange id: ${capturerChangeInfo[0].id}`); 991 console.info(`audioCapturerChange deviceRole: ${capturerChangeInfo[0].deviceRole}`); 992 console.info(`audioCapturerChange deviceType: ${capturerChangeInfo[0].deviceType}`); 993}); 994``` 995 996## off('audioCapturerChange')<sup>11+</sup> 997 998off(type: 'audioCapturerChange', callback?: Callback\<AudioCapturerChangeInfo>): void 999 1000Unsubscribes from the audio capturer configuration change event. This API uses an asynchronous callback to return the result. 1001 1002**System capability**: SystemCapability.Multimedia.Audio.Capturer 1003 1004**Parameters** 1005 1006| Name | Type | Mandatory| Description | 1007| :------- | :------------------------- | :--- | :------------------------------------------ | 1008| type | string | Yes | Event type. The event **'audioCapturerChange'** is triggered when the audio capturer configuration is changed.| 1009| callback | Callback\<[AudioCapturerChangeInfo](arkts-apis-audio-i.md#audiocapturerchangeinfo9)> | No | Callback used for unsubscription.| 1010 1011**Error codes** 1012 1013For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 1014 1015| ID| Error Message| 1016| ------- | --------------------------------------------| 1017| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 1018| 6800101 | Parameter verification failed. | 1019 1020**Example** 1021 1022```ts 1023// Cancel all subscriptions to the event. 1024audioCapturer.off('audioCapturerChange'); 1025 1026// 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. 1027let audioCapturerChangeCallback = (capturerChangeInfo: audio.AudioCapturerChangeInfo) => { 1028 console.info(`audioCapturerChange id: ${capturerChangeInfo[0].id}`); 1029 console.info(`audioCapturerChange deviceRole: ${capturerChangeInfo[0].deviceRole}`); 1030 console.info(`audioCapturerChange deviceType: ${capturerChangeInfo[0].deviceType}`); 1031}; 1032 1033audioCapturer.on('audioCapturerChange', audioCapturerChangeCallback); 1034 1035audioCapturer.off('audioCapturerChange', audioCapturerChangeCallback); 1036``` 1037 1038## on('markReach')<sup>8+</sup> 1039 1040on(type: 'markReach', frame: number, callback: Callback<number>): void 1041 1042Subscribes 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. 1043 1044For example, if **frame** is set to **100**, the callback is invoked when the number of captured frames reaches the 100th frame. 1045 1046**System capability**: SystemCapability.Multimedia.Audio.Capturer 1047 1048**Parameters** 1049 1050| Name | Type | Mandatory| Description | 1051| :------- | :---------------------- | :--- | :----------------------------------------- | 1052| type | string | Yes | Event type. The event **'markReach'** is triggered when the number of frames captured reaches the value of the **frame** parameter.| 1053| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | 1054| callback | Callback\<number> | Yes | Callback used to return the value of the **frame** parameter.| 1055 1056**Example** 1057 1058```ts 1059audioCapturer.on('markReach', 1000, (position: number) => { 1060 if (position == 1000) { 1061 console.info('ON Triggered successfully'); 1062 } 1063}); 1064``` 1065 1066## off('markReach')<sup>8+</sup> 1067 1068off(type: 'markReach', callback?: Callback<number>): void 1069 1070Unsubscribes from the mark reached event. This API uses an asynchronous callback to return the result. 1071 1072**System capability**: SystemCapability.Multimedia.Audio.Capturer 1073 1074**Parameters** 1075 1076| Name| Type | Mandatory| Description | 1077| :----- | :----- | :--- | :------------------------------------------------ | 1078| type | string | Yes | Event type. The event **'markReach'** is triggered when the number of frames captured reaches the value of the **frame** parameter.| 1079| callback<sup>18+</sup> | Callback\<number> | No | Callback used to return the value of the **frame** parameter.| 1080 1081**Example** 1082 1083```ts 1084// Cancel all subscriptions to the event. 1085audioCapturer.off('markReach'); 1086 1087// 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. 1088let markReachCallback = (position: number) => { 1089 if (position == 1000) { 1090 console.info('ON Triggered successfully'); 1091 } 1092}; 1093 1094audioCapturer.on('markReach', 1000, markReachCallback); 1095 1096audioCapturer.off('markReach', markReachCallback); 1097``` 1098 1099## on('periodReach')<sup>8+</sup> 1100 1101on(type: 'periodReach', frame: number, callback: Callback<number>): void 1102 1103Subscribes 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. 1104 1105For 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. 1106 1107**System capability**: SystemCapability.Multimedia.Audio.Capturer 1108 1109**Parameters** 1110 1111| Name | Type | Mandatory| Description | 1112| :------- | :----------------------- | :--- | :------------------------------------------ | 1113| type | string | Yes | Event type. The event **'periodReach'** is triggered each time the number of frames captured reaches the value of the **frame** parameter.| 1114| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | 1115| callback | Callback\<number> | Yes |Callback used to return the value of the **frame** parameter. | 1116 1117**Example** 1118 1119```ts 1120audioCapturer.on('periodReach', 1000, (position: number) => { 1121 if (position == 1000) { 1122 console.info('ON Triggered successfully'); 1123 } 1124}); 1125``` 1126 1127## off('periodReach')<sup>8+</sup> 1128 1129off(type: 'periodReach', callback?: Callback<number>): void 1130 1131Unsubscribes from the period reached event. This API uses an asynchronous callback to return the result. 1132 1133**System capability**: SystemCapability.Multimedia.Audio.Capturer 1134 1135**Parameters** 1136 1137| Name| Type | Mandatory| Description | 1138| :----- | :----- | :--- | :-------------------------------------------------- | 1139| type | string | Yes | Event type. The event **'periodReach'** is triggered each time the number of frames captured reaches the value of the **frame** parameter.| 1140| callback<sup>18+</sup> | Callback\<number> | No | Callback used to return the value of the **frame** parameter.| 1141 1142**Example** 1143 1144```ts 1145// Cancel all subscriptions to the event. 1146audioCapturer.off('periodReach'); 1147 1148// 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. 1149let periodReachCallback = (position: number) => { 1150 if (position == 1000) { 1151 console.info('ON Triggered successfully'); 1152 } 1153}; 1154 1155audioCapturer.on('periodReach', 1000, periodReachCallback); 1156 1157audioCapturer.off('periodReach', periodReachCallback); 1158``` 1159 1160## on('stateChange')<sup>8+</sup> 1161 1162on(type: 'stateChange', callback: Callback<AudioState\>): void 1163 1164Subscribes 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. 1165 1166**System capability**: SystemCapability.Multimedia.Audio.Capturer 1167 1168**Parameters** 1169 1170| Name | Type | Mandatory| Description | 1171| :------- | :------------------------- | :--- | :------------------------------------------ | 1172| type | string | Yes | Event type. The event **'stateChange'** is triggered when the state of the audio capturer is changed.| 1173| callback | Callback\<[AudioState](arkts-apis-audio-e.md#audiostate8)> | Yes | Callback used to return the audio status.| 1174 1175**Example** 1176 1177```ts 1178audioCapturer.on('stateChange', (state: audio.AudioState) => { 1179 if (state == 1) { 1180 console.info('audio capturer state is: STATE_PREPARED'); 1181 } 1182 if (state == 2) { 1183 console.info('audio capturer state is: STATE_RUNNING'); 1184 } 1185}); 1186``` 1187 1188## off('stateChange')<sup>18+</sup> 1189 1190off(type: 'stateChange', callback?: Callback<AudioState>): void 1191 1192Unsubscribes from the audio capturer state change event. This API uses an asynchronous callback to return the result. 1193 1194**System capability**: SystemCapability.Multimedia.Audio.Capturer 1195 1196**Parameters** 1197 1198| Name| Type | Mandatory| Description | 1199| :----- | :----- | :--- | :-------------------------------------------------- | 1200| type | string | Yes | Event type. The event **'stateChange'** is triggered when the state of the audio capturer is changed.| 1201| callback | Callback\<[AudioState](arkts-apis-audio-e.md#audiostate8)> | No| Callback used to return the audio status.| 1202 1203**Error codes** 1204 1205For details about the error codes, see [Audio Error Codes](errorcode-audio.md). 1206 1207| ID| Error Message| 1208| ------- | --------------------------------------------| 1209| 6800101 | Parameter verification failed. | 1210 1211**Example** 1212 1213```ts 1214// Cancel all subscriptions to the event. 1215audioCapturer.off('stateChange'); 1216 1217// 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. 1218let stateChangeCallback = (state: audio.AudioState) => { 1219 if (state == 1) { 1220 console.info('audio renderer state is: STATE_PREPARED'); 1221 } 1222 if (state == 2) { 1223 console.info('audio renderer state is: STATE_RUNNING'); 1224 } 1225}; 1226 1227audioCapturer.on('stateChange', stateChangeCallback); 1228 1229audioCapturer.off('stateChange', stateChangeCallback); 1230``` 1231 1232## on('readData')<sup>11+</sup> 1233 1234on(type: 'readData', callback: Callback\<ArrayBuffer>): void 1235 1236Subscribes 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. 1237 1238The callback function is used only to read audio data. Do not call AudioCapturer APIs in it. 1239 1240**System capability**: SystemCapability.Multimedia.Audio.Capturer 1241 1242**Parameters** 1243 1244| Name | Type | Mandatory| Description | 1245| :------- |:-----------------------| :--- |:--------------------------| 1246| type | string | Yes | Event type. The event **'readData'** is triggered when audio stream data needs to be read.| 1247| callback | Callback\<ArrayBuffer> | Yes | Callback used to return the buffer from which the data is read. | 1248 1249**Error codes** 1250 1251For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 1252 1253| ID| Error Message| 1254| ------- | --------------------------------------------| 1255| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 1256| 6800101 | Parameter verification failed. | 1257 1258**Example** 1259 1260```ts 1261import { BusinessError } from '@kit.BasicServicesKit'; 1262import { fileIo as fs } from '@kit.CoreFileKit'; 1263import { common } from '@kit.AbilityKit'; 1264 1265class Options { 1266 offset?: number; 1267 length?: number; 1268} 1269 1270let bufferSize: number = 0; 1271// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. 1272let context = this.getUIContext().getHostContext() as common.UIAbilityContext; 1273let path = context.cacheDir; 1274// Ensure that the resource exists in the path. 1275let filePath = path + '/StarWars10s-2C-48000-4SW.pcm'; 1276let file: fs.File = fs.openSync(filePath, fs.OpenMode.READ_WRITE); 1277let readDataCallback = (buffer: ArrayBuffer) => { 1278 let options: Options = { 1279 offset: bufferSize, 1280 length: buffer.byteLength 1281 }; 1282 fs.writeSync(file.fd, buffer, options); 1283 bufferSize += buffer.byteLength; 1284} 1285 1286audioCapturer.on('readData', readDataCallback); 1287 1288audioCapturer.start((err: BusinessError) => { 1289 if (err) { 1290 console.error('Capturer start failed.'); 1291 } else { 1292 console.info('Capturer start success.'); 1293 } 1294}); 1295``` 1296 1297## off('readData')<sup>11+</sup> 1298 1299off(type: 'readData', callback?: Callback\<ArrayBuffer>): void 1300 1301Unsubscribes from the audio data read event. This API uses an asynchronous callback to return the result. 1302 1303**System capability**: SystemCapability.Multimedia.Audio.Capturer 1304 1305**Parameters** 1306 1307| Name | Type | Mandatory| Description | 1308| :------- |:-----------------------| :--- |:-------------------------------------------| 1309| type | string | Yes | Event type. The event **'readData'** is triggered when audio stream data needs to be read.| 1310| callback | Callback\<ArrayBuffer> | No | Callback used to return the buffer from which the data is read. | 1311 1312**Error codes** 1313 1314For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Audio Error Codes](errorcode-audio.md). 1315 1316| ID| Error Message| 1317| ------- | --------------------------------------------| 1318| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | 1319| 6800101 | Parameter verification failed. | 1320 1321**Example** 1322 1323```ts 1324// Cancel all subscriptions to the event. 1325audioCapturer.off('readData'); 1326 1327// 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. 1328let readDataCallback = (data: ArrayBuffer) => { 1329 console.info(`read data: ${data}`); 1330}; 1331 1332audioCapturer.on('readData', readDataCallback); 1333 1334audioCapturer.off('readData', readDataCallback); 1335``` 1336 1337## getOverflowCount<sup>12+</sup> 1338 1339getOverflowCount(): Promise<number> 1340 1341Obtains the number of overflow audio frames in the audio stream that is being captured. This API uses a promise to return the result. 1342 1343**System capability**: SystemCapability.Multimedia.Audio.Capturer 1344 1345**Return value** 1346 1347| Type | Description | 1348| ------------------- | ----------------------------- | 1349| Promise<number>| Promise used to return the number of overflow audio frames.| 1350 1351**Example** 1352 1353```ts 1354import { BusinessError } from '@kit.BasicServicesKit'; 1355 1356audioCapturer.getOverflowCount().then((value: number) => { 1357 console.info(`Get overflow count Success! ${value}`); 1358}).catch((err: BusinessError) => { 1359 console.error(`Get overflow count Fail: ${err}`); 1360}); 1361``` 1362 1363## getOverflowCountSync<sup>12+</sup> 1364 1365getOverflowCountSync(): number 1366 1367Obtains the number of overflow audio frames in the audio stream that is being captured. This API returns the result synchronously. 1368 1369**System capability**: SystemCapability.Multimedia.Audio.Capturer 1370 1371**Return value** 1372 1373| Type | Description | 1374| ------------------- | ----------------------------- | 1375| number| Number of overflow audio frames.| 1376 1377**Example** 1378 1379```ts 1380import { BusinessError } from '@kit.BasicServicesKit'; 1381 1382try { 1383 let value: number = audioCapturer.getOverflowCountSync(); 1384 console.info(`Get overflow count Success! ${value}`); 1385} catch (err) { 1386 let error = err as BusinessError; 1387 console.error(`Get overflow count Fail: ${error}`); 1388} 1389``` 1390 1391## setWillMuteWhenInterrupted<sup>20+</sup> 1392 1393setWillMuteWhenInterrupted(muteWhenInterrupted: boolean): Promise<void> 1394 1395Sets whether to [mute the current audio recording stream when an audio interruption occurs](../../media/audio/using-audiocapturer-for-recording.md#setting-the-mute-interruption-mode). This API uses a promise to return the result. 1396 1397**System capability**: SystemCapability.Multimedia.Audio.Capturer 1398 1399**Parameters** 1400 1401| Name | Type | Mandatory | Description | 1402| ---------- |---------------- | ------ |---------------------------------------------------------| 1403| 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.| 1404 1405**Return value** 1406 1407| Type | Description | 1408| ------------------- | ----------------------------- | 1409| Promise<void>| Promise that returns no value.| 1410 1411**Error codes** 1412 1413For details about the error codes, see [Audio Error Codes](errorcode-audio.md). 1414 1415| ID| Error Message| 1416| ------- | --------------------------------------------| 1417| 6800103 | Operation not permit at current state. | 1418 1419**Example** 1420 1421```ts 1422import { BusinessError } from '@kit.BasicServicesKit'; 1423 1424audioCapturer.setWillMuteWhenInterrupted(true).then(() => { 1425 console.info('setWillMuteWhenInterrupted Success!'); 1426}).catch((err: BusinessError) => { 1427 console.error(`setWillMuteWhenInterrupted Fail: ${err}`); 1428}); 1429``` 1430 1431## read<sup>(deprecated)</sup> 1432 1433read(size: number, isBlockingRead: boolean, callback: AsyncCallback<ArrayBuffer\>): void 1434 1435Reads the buffer. This API uses an asynchronous callback to return the result. 1436 1437> **NOTE** 1438> 1439> This API is supported since API version 8 and deprecated since API version 11. You are advised to use [on('readData')](#onreaddata11) instead. 1440 1441**System capability**: SystemCapability.Multimedia.Audio.Capturer 1442 1443**Parameters** 1444 1445| Name | Type | Mandatory| Description | 1446| :------------- | :-------------------------- | :--- | :------------------------------- | 1447| size | number | Yes | Number of bytes to read. | 1448| isBlockingRead | boolean | Yes | Whether to block the read operation. The value **true** means to block the read operation, and **false** means the opposite. | 1449| 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.| 1450 1451**Example** 1452 1453```ts 1454import { BusinessError } from '@kit.BasicServicesKit'; 1455 1456let bufferSize: number = 0; 1457 1458audioCapturer.getBufferSize().then((data: number) => { 1459 console.info(`AudioFrameworkRecLog: getBufferSize: SUCCESS ${data}`); 1460 bufferSize = data; 1461}).catch((err: BusinessError) => { 1462 console.error(`AudioFrameworkRecLog: getBufferSize: ERROR: ${err}`); 1463}); 1464 1465audioCapturer.read(bufferSize, true, (err: BusinessError, buffer: ArrayBuffer) => { 1466 if (!err) { 1467 console.info('Success in reading the buffer data'); 1468 } 1469}); 1470``` 1471 1472## read<sup>(deprecated)</sup> 1473 1474read(size: number, isBlockingRead: boolean): Promise<ArrayBuffer\> 1475 1476Reads the buffer. This API uses a promise to return the result. 1477 1478> **NOTE** 1479> 1480> This API is supported since API version 8 and deprecated since API version 11. You are advised to use [on('readData')](#onreaddata11) instead. 1481 1482**System capability**: SystemCapability.Multimedia.Audio.Capturer 1483 1484**Parameters** 1485 1486| Name | Type | Mandatory| Description | 1487| :------------- | :------ | :--- | :--------------- | 1488| size | number | Yes | Number of bytes to read. | 1489| isBlockingRead | boolean | Yes | Whether to block the read operation. The value **true** means to block the read operation, and **false** means the opposite.| 1490 1491**Return value** 1492 1493| Type | Description | 1494| :-------------------- | :----------------------------------------------------- | 1495| Promise<ArrayBuffer\> | Promise used to return the data read from the buffer.| 1496 1497**Example** 1498 1499```ts 1500import { BusinessError } from '@kit.BasicServicesKit'; 1501 1502let bufferSize: number = 0; 1503 1504audioCapturer.getBufferSize().then((data: number) => { 1505 console.info(`AudioFrameworkRecLog: getBufferSize: SUCCESS ${data}`); 1506 bufferSize = data; 1507}).catch((err: BusinessError) => { 1508 console.error(`AudioFrameworkRecLog: getBufferSize: ERROR ${err}`); 1509}); 1510console.info(`Buffer size: ${bufferSize}`); 1511 1512audioCapturer.read(bufferSize, true).then((buffer: ArrayBuffer) => { 1513 console.info('buffer read successfully'); 1514}).catch((err: BusinessError) => { 1515 console.error(`ERROR : ${err}`); 1516}); 1517``` 1518