1# @ohos.multimedia.media (Media) 2 3> **NOTE** 4> 5> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. 6 7The multimedia subsystem provides a set of simple and easy-to-use APIs for you to access the system and use media resources. 8 9This subsystem offers the following audio and video services: 10 11- Audio and video playback ([AVPlayer](#avplayer9)<sup>9+</sup>) 12 13- Audio and video recording [AVRecorder](#avrecorder9)<sup>9+</sup>) 14 15- Video transcoding ([AVTranscoder](#avtranscoder12)<sup>12+</sup>) 16 17- Obtaining audio and video metadata ([AVMetadataExtractor](#avmetadataextractor11)<sup>11+</sup>) 18 19- Obtaining video thumbnails ([AVImageGenerator](#avimagegenerator12)<sup>12+</sup>) 20 21## Modules to Import 22 23```ts 24import { media } from '@kit.MediaKit'; 25``` 26 27## media.createAVPlayer<sup>9+</sup> 28 29createAVPlayer(callback: AsyncCallback\<AVPlayer>): void 30 31Creates an **AVPlayer** instance. This API uses an asynchronous callback to return the result. 32 33> **NOTE** 34> 35> You are advised to create a maximum of 16 **AVPlayer** instances for an application in both audio and video playback scenarios.<!--Del--> 36> The actual number of instances that can be created may be different. It depends on the specifications of the device chip in use. For example, in the case of RK3568, you are advised to create a maximum of 6 **AVPlayer** instances for an application in audio and video playback scenarios.<!--DelEnd--> 37 38**Atomic service API**: This API can be used in atomic services since API version 11. 39 40**System capability**: SystemCapability.Multimedia.Media.AVPlayer 41 42**Parameters** 43 44| Name | Type | Mandatory| Description | 45| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ | 46| callback | AsyncCallback\<[AVPlayer](#avplayer9)> | Yes | Callback used to return the result. If the operation is successful, an **AVPlayer** instance is returned; otherwise, **null** is returned. The instance can be used to play audio and video.| 47 48**Error codes** 49 50For details about the error codes, see [Media Error Codes](errorcode-media.md). 51 52| ID| Error Message | 53| -------- | ------------------------------ | 54| 5400101 | No memory. Return by callback. | 55 56**Example** 57 58```ts 59import { BusinessError } from '@kit.BasicServicesKit'; 60 61let avPlayer: media.AVPlayer; 62media.createAVPlayer((error: BusinessError, video: media.AVPlayer) => { 63 if (video != null) { 64 avPlayer = video; 65 console.info('Succeeded in creating AVPlayer'); 66 } else { 67 console.error(`Failed to create AVPlayer, error message:${error.message}`); 68 } 69}); 70``` 71 72## media.createAVPlayer<sup>9+</sup> 73 74createAVPlayer(): Promise\<AVPlayer> 75 76Creates an **AVPlayer** instance. This API uses a promise to return the result. 77 78> **NOTE** 79> 80> You are advised to create a maximum of 16 **AVPlayer** instances for an application in both audio and video playback scenarios.<!--Del--> 81> The actual number of instances that can be created may be different. It depends on the specifications of the device chip in use. For example, in the case of RK3568, you are advised to create a maximum of 6 **AVPlayer** instances for an application in audio and video playback scenarios.<!--DelEnd--> 82 83**Atomic service API**: This API can be used in atomic services since API version 11. 84 85**System capability**: SystemCapability.Multimedia.Media.AVPlayer 86 87**Return value** 88 89| Type | Description | 90| ------------------------------- | ------------------------------------------------------------ | 91| Promise\<[AVPlayer](#avplayer9)> | Promise used to return the result. If the operation is successful, an **AVPlayer** instance is returned; otherwise, **null** is returned. The instance can be used to play audio and video.| 92 93**Error codes** 94 95For details about the error codes, see [Media Error Codes](errorcode-media.md). 96 97| ID| Error Message | 98| -------- | ----------------------------- | 99| 5400101 | No memory. Return by promise. | 100 101**Example** 102 103```ts 104import { BusinessError } from '@kit.BasicServicesKit'; 105 106let avPlayer: media.AVPlayer; 107media.createAVPlayer().then((video: media.AVPlayer) => { 108 if (video != null) { 109 avPlayer = video; 110 console.info('Succeeded in creating AVPlayer'); 111 } else { 112 console.error('Failed to create AVPlayer'); 113 } 114}).catch((error: BusinessError) => { 115 console.error(`Failed to create AVPlayer, error message:${error.message}`); 116}); 117``` 118 119## media.createAVRecorder<sup>9+</sup> 120 121createAVRecorder(callback: AsyncCallback\<AVRecorder>): void 122 123Creates an **AVRecorder** instance. This API uses an asynchronous callback to return the result. 124 125> **NOTE** 126> 127> - A maximum of 2 **AVRecorder** instances can be created. 128> - Only one instance can perform audio recording on a device at one time, since all the applications share the audio channel. Any attempt to create the second instance for audio recording fails due to audio channel conflicts. 129 130**System capability**: SystemCapability.Multimedia.Media.AVRecorder 131 132**Parameters** 133 134| Name | Type | Mandatory| Description | 135| -------- | ------------------------------------------ | ---- | ------------------------------------------------------------ | 136| callback | AsyncCallback\<[AVRecorder](#avrecorder9)> | Yes | Callback used to return the result. If the operation is successful, an **AVRecorder** instance is returned; otherwise, **null** is returned. The instance can be used to record audio and video.| 137 138**Error codes** 139 140For details about the error codes, see [Media Error Codes](errorcode-media.md). 141 142| ID| Error Message | 143| -------- | ------------------------------ | 144| 5400101 | No memory. Return by callback. | 145 146**Example** 147 148```ts 149import { BusinessError } from '@kit.BasicServicesKit'; 150let avRecorder: media.AVRecorder; 151 152media.createAVRecorder((error: BusinessError, recorder: media.AVRecorder) => { 153 if (recorder != null) { 154 avRecorder = recorder; 155 console.info('Succeeded in creating AVRecorder'); 156 } else { 157 console.error(`Failed to create AVRecorder, error message:${error.message}`); 158 } 159}); 160``` 161 162## media.createAVRecorder<sup>9+</sup> 163 164createAVRecorder(): Promise\<AVRecorder> 165 166Creates an **AVRecorder** instance. This API uses a promise to return the result. 167 168> **NOTE** 169> 170> - A maximum of 2 **AVRecorder** instances can be created. 171> - Only one instance can perform audio recording on a device at one time, since all the applications share the audio channel. Any attempt to create the second instance for audio recording fails due to audio channel conflicts. 172 173**Atomic service API**: This API can be used in atomic services since API version 12. 174 175**System capability**: SystemCapability.Multimedia.Media.AVRecorder 176 177**Return value** 178 179| Type | Description | 180| ------------------------------------ | ------------------------------------------------------------ | 181| Promise\<[AVRecorder](#avrecorder9)> | Promise used to return the result. If the operation is successful, an **AVRecorder** instance is returned; otherwise, **null** is returned. The instance can be used to record audio and video.| 182 183**Error codes** 184 185For details about the error codes, see [Media Error Codes](errorcode-media.md). 186 187| ID| Error Message | 188| -------- | ----------------------------- | 189| 5400101 | No memory. Return by promise. | 190 191**Example** 192 193```ts 194import { BusinessError } from '@kit.BasicServicesKit'; 195 196let avRecorder: media.AVRecorder; 197media.createAVRecorder().then((recorder: media.AVRecorder) => { 198 if (recorder != null) { 199 avRecorder = recorder; 200 console.info('Succeeded in creating AVRecorder'); 201 } else { 202 console.error('Failed to create AVRecorder'); 203 } 204}).catch((error: BusinessError) => { 205 console.error(`Failed to create AVRecorder, error message:${error.message}`); 206}); 207``` 208 209## media.createAVTranscoder<sup>12+</sup> 210 211createAVTranscoder(): Promise\<AVTranscoder> 212 213Creates an **AVTranscoder** instance. This API uses a promise to return the result. 214 215> **NOTE** 216 217> A maximum of 2 **AVTranscoder** instances can be created. 218 219**System capability**: SystemCapability.Multimedia.Media.AVTranscoder 220 221**Return value** 222 223| Type | Description | 224| ------------------------------- | ------------------------------------------------------------ | 225| Promise\<[AVTranscoder](#avtranscoder12)> | Promise used to return the result. If the operation is successful, an **AVTranscoder** instance is returned; otherwise, **null** is returned. The instance can be used for video transcoding.| 226 227**Error codes** 228 229For details about the error codes, see [Media Error Codes](errorcode-media.md). 230 231| ID| Error Message | 232| -------- | ----------------------------- | 233| 5400101 | No memory. Return by promise. | 234 235**Example** 236 237```ts 238import { BusinessError } from '@kit.BasicServicesKit'; 239 240let avTranscoder: media.AVTranscoder; 241media.createAVTranscoder().then((transcoder: media.AVTranscoder) => { 242 if (transcoder != null) { 243 avTranscoder = transcoder; 244 console.info('Succeeded in creating AVTranscoder'); 245 } else { 246 console.error('Failed to create AVTranscoder'); 247 } 248}).catch((error: BusinessError) => { 249 console.error(`Failed to create AVTranscoder, error message:${error.message}`); 250}); 251``` 252 253## media.createAVMetadataExtractor<sup>11+</sup> 254 255createAVMetadataExtractor(callback: AsyncCallback\<AVMetadataExtractor>): void 256 257Creates an **AVMetadataExtractor** instance. This API uses an asynchronous callback to return the result. 258 259**System capability**: SystemCapability.Multimedia.Media.AVMetadataExtractor 260 261**Parameters** 262 263| Name | Type | Mandatory| Description | 264| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ | 265| callback | AsyncCallback\<[AVMetadataExtractor](#avmetadataextractor11)> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the **AVMetadataExtractor** instance created; otherwise, **err** is an error object.| 266 267**Error codes** 268 269For details about the error codes, see [Media Error Codes](errorcode-media.md). 270 271| ID| Error Message | 272| -------- | ------------------------------ | 273| 5400101 | No memory. Returned by callback. | 274 275**Example** 276 277```ts 278import { BusinessError } from '@kit.BasicServicesKit'; 279 280let avMetadataExtractor: media.AVMetadataExtractor; 281media.createAVMetadataExtractor((error: BusinessError, extractor: media.AVMetadataExtractor) => { 282 if (extractor != null) { 283 avMetadataExtractor = extractor; 284 console.info('Succeeded in creating AVMetadataExtractor'); 285 } else { 286 console.error(`Failed to create AVMetadataExtractor, error message:${error.message}`); 287 } 288}); 289``` 290 291## media.createAVMetadataExtractor<sup>11+</sup> 292 293createAVMetadataExtractor(): Promise\<AVMetadataExtractor> 294 295Creates an **AVMetadataExtractor** instance. This API uses a promise to return the result. 296 297**System capability**: SystemCapability.Multimedia.Media.AVMetadataExtractor 298 299**Error codes** 300 301For details about the error codes, see [Media Error Codes](errorcode-media.md). 302 303| ID| Error Message | 304| -------- | ------------------------------ | 305| 5400101 | No memory. Returned by promise. | 306 307**Example** 308 309```ts 310import { BusinessError } from '@kit.BasicServicesKit'; 311 312let avMetadataExtractor: media.AVMetadataExtractor; 313media.createAVMetadataExtractor().then((extractor: media.AVMetadataExtractor) => { 314 if (extractor != null) { 315 avMetadataExtractor = extractor; 316 console.info('Succeeded in creating AVMetadataExtractor'); 317 } else { 318 console.error(`Failed to create AVMetadataExtractor`); 319 } 320}).catch((error: BusinessError) => { 321 console.error(`Failed to create AVMetadataExtractor, error message:${error.message}`); 322}); 323``` 324 325## media.createSoundPool<sup>10+</sup> 326 327createSoundPool(maxStreams: number, audioRenderInfo: audio.AudioRendererInfo, callback: AsyncCallback\<SoundPool>): void 328 329Creates a **SoundPool** instance. This API uses an asynchronous callback to return the result. 330 331**System capability**: SystemCapability.Multimedia.Media.SoundPool 332 333**Parameters** 334 335| Name | Type | Mandatory| Description | 336| -------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | 337| maxStreams | number | Yes | Maximum number of streams that can be played by the **SoundPool** instance.| 338| audioRenderInfo | [audio.AudioRendererInfo](../apis-audio-kit/js-apis-audio.md#audiorendererinfo8) | Yes | Audio renderer parameters. When the **usage** parameter in **audioRenderInfo** is set to **STREAM_USAGE_UNKNOWN**, **STREAM_USAGE_MUSIC**, **STREAM_USAGE_MOVIE**, or **STREAM_USAGE_AUDIOBOOK**, the SoundPool uses the audio mixing mode when playing a short sound, without interrupting the playback of other audios.| 339| callback | AsyncCallback<[SoundPool](js-apis-inner-multimedia-soundPool.md)> | Yes | Callback used to return the result. If the operation is successful, a **SoundPool** instance is returned; otherwise, **null** is returned. The instance is used for loading and playback.| 340 341**Error codes** 342 343For details about the error codes, see [Media Error Codes](errorcode-media.md). 344 345| ID| Error Message | 346| -------- | ------------------------------ | 347| 5400101 | No memory. Return by callback. | 348 349**Example** 350 351```js 352import { audio } from '@kit.AudioKit'; 353 354let soundPool: media.SoundPool; 355let audioRendererInfo: audio.AudioRendererInfo = { 356 usage : audio.StreamUsage.STREAM_USAGE_MUSIC, 357 rendererFlags : 0 358} 359 360media.createSoundPool(5, audioRendererInfo, (error, soundPool_: media.SoundPool) => { 361 if (error) { 362 console.error(`Failed to createSoundPool`) 363 return; 364 } else { 365 soundPool = soundPool_; 366 console.info(`Succeeded in createSoundPool`) 367 } 368}); 369``` 370 371## media.createSoundPool<sup>10+</sup> 372 373createSoundPool(maxStreams: number, audioRenderInfo: audio.AudioRendererInfo): Promise\<SoundPool> 374 375Creates a **SoundPool** instance. This API uses a promise to return the result. 376 377**System capability**: SystemCapability.Multimedia.Media.SoundPool 378 379**Parameters** 380 381| Name | Type | Mandatory| Description | 382| -------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | 383| maxStreams | number | Yes | Maximum number of streams that can be played by the **SoundPool** instance.| 384| audioRenderInfo | [audio.AudioRendererInfo](../apis-audio-kit/js-apis-audio.md#audiorendererinfo8) | Yes | Audio renderer parameters.| 385 386**Return value** 387 388| Type | Description | 389| ----------------------------------------- | ------------------------------------------------------------ | 390| Promise<[SoundPool](js-apis-inner-multimedia-soundPool.md)> | Promise used to return the result. If the operation is successful, a **SoundPool** instance is returned; otherwise, **null** is returned. The instance is used for loading and playback.| 391 392**Error codes** 393 394For details about the error codes, see [Media Error Codes](errorcode-media.md). 395 396| ID| Error Message | 397| -------- | ----------------------------- | 398| 5400101 | No memory. Return by promise. | 399 400**Example** 401 402```js 403import { audio } from '@kit.AudioKit'; 404import { BusinessError } from '@kit.BasicServicesKit'; 405 406let soundPool: media.SoundPool; 407let audioRendererInfo: audio.AudioRendererInfo = { 408 usage : audio.StreamUsage.STREAM_USAGE_MUSIC, 409 rendererFlags : 0 410} 411 412media.createSoundPool(5, audioRendererInfo).then((soundpool_: media.SoundPool) => { 413 if (soundpool_ != null) { 414 soundPool = soundpool_; 415 console.info('Succceeded in creating SoundPool'); 416 } else { 417 console.error('Failed to create SoundPool'); 418 } 419}, (error: BusinessError) => { 420 console.error(`soundpool catchCallback, error message:${error.message}`); 421}); 422``` 423 424## media.createAVScreenCaptureRecorder<sup>12+</sup> 425 426createAVScreenCaptureRecorder(): Promise\<AVScreenCaptureRecorder> 427 428Creates an **AVScreenCaptureRecorder** instance. This API uses a promise to return the result. 429 430**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture 431 432**Return value** 433 434| Type | Description | 435| ------------------------------------------------------------ | ------------------------------------------------------------ | 436| Promise\<[AVScreenCaptureRecorder](#avscreencapturerecorder12)> | Promise used to return the result. If the operation is successful, an **AVScreenCaptureRecorder** instance is returned; otherwise, **null** is returned. The instance can be used for screen capture.| 437 438**Error codes** 439 440| ID| Error Message | 441| -------- | ------------------------------ | 442| 5400101 | No memory. Return by promise. | 443 444**Example** 445 446```ts 447import { BusinessError } from '@kit.BasicServicesKit'; 448 449let avScreenCaptureRecorder: media.AVScreenCaptureRecorder; 450media.createAVScreenCaptureRecorder().then((captureRecorder: media.AVScreenCaptureRecorder) => { 451 if (captureRecorder != null) { 452 avScreenCaptureRecorder = captureRecorder; 453 console.info('Succeeded in createAVScreenCaptureRecorder'); 454 } else { 455 console.error('Failed to createAVScreenCaptureRecorder'); 456 } 457}).catch((error: BusinessError) => { 458 console.error(`createAVScreenCaptureRecorder catchCallback, error message:${error.message}`); 459}); 460``` 461 462## AVErrorCode<sup>9+</sup> 463 464Enumerates the [media error codes](errorcode-media.md). 465 466**Atomic service API**: This API can be used in atomic services since API version 11. 467 468**System capability**: SystemCapability.Multimedia.Media.Core 469 470| Name | Value | Description | 471| :------------------------------------ | ------- | ------------------------------------ | 472| AVERR_OK | 0 | The operation is successful. | 473| AVERR_NO_PERMISSION | 201 | No permission to perform the operation. | 474| AVERR_INVALID_PARAMETER | 401 | Invalid input parameter. | 475| AVERR_UNSUPPORT_CAPABILITY | 801 | Unsupported API. | 476| AVERR_NO_MEMORY | 5400101 | The system memory is insufficient or the number of services reaches the upper limit.| 477| AVERR_OPERATE_NOT_PERMIT | 5400102 | The operation is not allowed in the current state or you do not have the permission to perform the operation.| 478| AVERR_IO | 5400103 | The data stream is abnormal. | 479| AVERR_TIMEOUT | 5400104 | The system or network response times out. | 480| AVERR_SERVICE_DIED | 5400105 | The service process is dead. | 481| AVERR_UNSUPPORT_FORMAT | 5400106 | The format of the media asset is not supported. | 482| AVERR_AUDIO_INTERRUPTED<sup>11+</sup> | 5400107 | The audio focus is interrupted. | 483 484## MediaType<sup>8+</sup> 485 486Enumerates the media types. 487 488**System capability**: SystemCapability.Multimedia.Media.Core 489 490| Name | Value | Description | 491| -------------- | --------------------- | ------------------- | 492| MEDIA_TYPE_AUD | 0 | Media.<br> **Atomic service API**: This API can be used in atomic services since API version 11. | 493| MEDIA_TYPE_VID | 1 | Video.<br> **Atomic service API**: This API can be used in atomic services since API version 11. | 494| MEDIA_TYPE_SUBTITLE<sup>12+</sup> | 2 | Subtitle.<br> **Atomic service API**: This API can be used in atomic services since API version 12.| 495 496## CodecMimeType<sup>8+</sup> 497 498Enumerates the codec MIME types. 499 500**System capability**: SystemCapability.Multimedia.Media.Core 501 502| Name | Value | Description | 503| ------------ | --------------------- | ------------------------ | 504| VIDEO_H263 | 'video/h263' | Video in H.263 format. | 505| VIDEO_AVC | 'video/avc' | Video in AVC format. | 506| VIDEO_MPEG2 | 'video/mpeg2' | Video in MPEG-2 format. | 507| VIDEO_MPEG4 | 'video/mp4v-es' | Video in MPEG-4 format. | 508| VIDEO_VP8 | 'video/x-vnd.on2.vp8' | Video in VP8 format. | 509| VIDEO_HEVC<sup>11+</sup> | 'video/hevc' | Video in H.265 format.| 510| AUDIO_AAC | 'audio/mp4a-latm' | Audio in MP4A-LATM format.<br> **Atomic service API**: This API can be used in atomic services since API version 12.| 511| AUDIO_VORBIS | 'audio/vorbis' | Audio in Vorbis format. | 512| AUDIO_FLAC | 'audio/flac' | Audio in FLAC format. | 513| AUDIO_MP3<sup>12+</sup> | 'audio/mpeg' | Audio in MPEG format. | 514| AUDIO_G711MU<sup>12+</sup> | 'audio/g711mu' | Audio in G.711 μ-law format.| 515 516## MediaDescriptionKey<sup>8+</sup> 517 518Enumerates the media description keys. 519 520**System capability**: SystemCapability.Multimedia.Media.Core 521 522| Name | Value | Description | 523| ------------------------ | --------------- | ------------------------------------------------------------ | 524| MD_KEY_TRACK_INDEX | 'track_index' | Track index, which is a number.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 525| MD_KEY_TRACK_TYPE | 'track_type' | Track type, which is a number. For details, see [MediaType](#mediatype8).<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 526| MD_KEY_CODEC_MIME | 'codec_mime' | Codec MIME type, which is a string.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 527| MD_KEY_DURATION | 'duration' | Media duration, which is a number, in units of ms.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 528| MD_KEY_BITRATE | 'bitrate' | Bit rate, which is a number, in units of bit/s.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 529| MD_KEY_WIDTH | 'width' | Video width, which is a number, in units of pixel.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 530| MD_KEY_HEIGHT | 'height' | Video height, which is a number, in units of pixel.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 531| MD_KEY_FRAME_RATE | 'frame_rate' | Video frame rate, which is a number, measured in frames per 100 seconds.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 532| MD_KEY_AUD_CHANNEL_COUNT | 'channel_count' | Number of audio channels, which is a number.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 533| MD_KEY_AUD_SAMPLE_RATE | 'sample_rate' | Sampling rate, which is a number, in units of Hz.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 534| MD_KEY_AUD_SAMPLE_DEPTH<sup>12+</sup> | 'sample_depth' | Bit depth, which is a number, in units of bits.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 535| MD_KEY_TRACK_NAME<sup>12+</sup> | 'track_name' | Track name, which is a string.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 536| MD_KEY_HDR_TYPE<sup>12+</sup> | 'hdr_type' | Codec track type, which is a string.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 537 538## PlaybackInfoKey<sup>12+</sup> 539 540Enumerates the playback description keys. 541 542**System capability**: SystemCapability.Multimedia.Media.Core 543 544| Name | Value | Description | 545| ------------------------ | --------------- | ------------------------------------------------------------ | 546| SERVER_IP_ADDRESS | 'server_ip_address' | IP address of the server, which is a string. | 547| AVG_DOWNLOAD_RATE | 'average_download_rate'| Average download rate, which is a number, in units of bit/s.| 548| DOWNLOAD_RATE | 'download_rate' | Download rate in one second, which is a number, in units of bit/s.| 549| IS_DOWNLOADING | 'is_downloading' | Download status, which is a number. The value **1** means that the downloaded is in progress, and **0** means that the download is complete.| 550| BUFFER_DURATION | 'buffer_duration' | Duration that the cached data can be played, which is a number, in units of seconds.| 551 552## BufferingInfoType<sup>8+</sup> 553 554Enumerates the buffering event types. 555 556**Atomic service API**: This API can be used in atomic services since API version 12. 557 558**System capability**: SystemCapability.Multimedia.Media.Core 559 560| Name | Value | Description | 561| ----------------- | ---- | -------------------------------- | 562| BUFFERING_START | 1 | Buffering starts.<br>**Atomic service API**: This API can be used in atomic services since API version 12. | 563| BUFFERING_END | 2 | Buffering ends.<br>**Atomic service API**: This API can be used in atomic services since API version 12. | 564| BUFFERING_PERCENT | 3 | Buffering progress, in percent.<br>**Atomic service API**: This API can be used in atomic services since API version 12. | 565| CACHED_DURATION | 4 | Cache duration, in ms.<br>**Atomic service API**: This API can be used in atomic services since API version 12. | 566 567## StateChangeReason<sup>9+</sup> 568 569Enumerates the reasons for the state transition of the **AVPlayer** or **AVRecorder** instance. The enum value is reported together with **state**. 570 571**Atomic service API**: This API can be used in atomic services since API version 11. 572 573**System capability**: SystemCapability.Multimedia.Media.Core 574 575| Name | Value | Description | 576| ---------- | ---- | ------------------------------------------------------------ | 577| USER | 1 | State transition triggered by user behavior. It happens when a user or the client calls an API.| 578| BACKGROUND | 2 | State transition caused by background system behavior. For example, if an application does not have the permission of Media Controller, the application is forcibly suspended or stopped by the system when it switches to the background.| 579 580## AVPlayer<sup>9+</sup> 581 582A playback management class that provides APIs to manage and play media assets. Before calling any API in **AVPlayer**, you must use [createAVPlayer()](#mediacreateavplayer9) to create an **AVPlayer** instance. 583 584For details about the audio and video playback demo, see [Audio Playback](../../media/media/using-avplayer-for-playback.md) and [Video Playback](../../media/media/video-playback.md). 585 586> **NOTE** 587> 588> When using the **AVPlayer** instance, you are advised to register the following callbacks to proactively obtain status changes: 589> - [on('stateChange')](#onstatechange9): listens for AVPlayer state changes. 590> - [on('error')](#onerror9): listens for error events. 591 592### Attributes 593 594**System capability**: SystemCapability.Multimedia.Media.AVPlayer 595 596| Name | Type | Read-Only| Optional| Description | 597| --------------------------------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | 598| url<sup>9+</sup> | string | No | Yes | URL of the media asset. It can be set only when the AVPlayer is in the idle state. <br>The video formats MP4, MPEG-TS, and MKV are supported.<br>The audio formats M4A, AAC, MP3, OGG, WAV, FLAC, and AMR are supported.<br>**Example of supported URLs**:<br>1. FD: fd://xx<br><br>2. HTTP: http\://xx<br>3. HTTPS: https\://xx<br>4. HLS: http\://xx or https\://xx<br>**NOTE**<br>- To set a network playback path, you must declare the [ohos.permission.INTERNET](../../security/AccessToken/permissions-for-all.md#ohospermissioninternet) permission by following the instructions provided in [Declaring Permissions](../../security/AccessToken/declare-permissions.md). The error code [201](../errorcode-universal.md) may be reported.<br>- WebM is no longer supported since API version 11.<br> - After the resource handle (FD) is transferred to an **AVPlayer** instance, do not use the resource handle to perform other read and write operations, including but not limited to transferring this handle to other **AVPlayer**, **AVMetadataExtractor**, **AVImageGenerator**, or **AVTranscoder** instance. Competition occurs when multiple AVPlayers use the same resource handle to read and write files at the same time, resulting in errors in obtaining data.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 599| fdSrc<sup>9+</sup> | [AVFileDescriptor](#avfiledescriptor9) | No | Yes | FD of the media asset. It can be set only when the AVPlayer is in the idle state.<br>This attribute is required when media assets of an application are continuously stored in a file.<br>The video formats MP4, MPEG-TS, and MKV are supported.<br>The audio formats M4A, AAC, MP3, OGG, WAV, FLAC, and AMR are supported.<br>**Example:**<br>Assume that a media file that stores continuous assets consists of the following:<br>Video 1 (address offset: 0, byte length: 100)<br>Video 2 (address offset: 101; byte length: 50)<br>Video 3 (address offset: 151, byte length: 150)<br>1. To play video 1: AVFileDescriptor {fd = resource handle; offset = 0; length = 100; }<br>2. To play video 2: AVFileDescriptor {fd = resource handle; offset = 101; length = 50; }<br>3. To play video 3: AVFileDescriptor {fd = resource handle; offset = 151; length = 150; }<br>To play an independent media file, use **src=fd://xx**.<br>**NOTE**<br>WebM is no longer supported since API version 11.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 600| dataSrc<sup>10+</sup> | [AVDataSrcDescriptor](#avdatasrcdescriptor10) | No | Yes | Descriptor of a streaming media asset. It can be set only when the AVPlayer is in the idle state.<br>Use scenario: An application starts playing a media file while the file is still being downloaded from the remote to the local host.<br>The video formats MP4, MPEG-TS, and MKV are supported.<br>The audio formats M4A, AAC, MP3, OGG, WAV, FLAC, and AMR are supported.<br>**Example:**<br>A user is obtaining an audio and video file from a remote server and wants to play the downloaded file content. To implement this scenario, do as follows:<br>1. Obtain the total file size, in bytes. If the total size cannot be obtained, set **fileSize** to **-1**.<br>2. Implement the **func** callback to fill in data. If **fileSize** is **-1**, the format of **func** is **func(buffer: ArrayBuffer, length: number)**, and the AVPlayer obtains data in sequence; otherwise, the format is **func(buffer: ArrayBuffer, length: number, pos: number)**, and the AVPlayer seeks and obtains data in the required positions.<br>3. Set **AVDataSrcDescriptor {fileSize = size, callback = func}**.<br>**Notes:**<br>If the media file to play is in MP4/M4A format, ensure that the **moov** field (specifying the media information) is before the **mdat** field (specifying the media data) or the fields before the **moov** field is less than 10 MB. Otherwise, the parsing fails and the media file cannot be played.<br>**NOTE**<br>WebM is no longer supported since API version 11.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 601| surfaceId<sup>9+</sup> | string | No | Yes | Video window ID. By default, there is no video window.<br>This parameter can be set when the AVPlayer is in the initialized state.<br>It can be set again when the AVPlayer is in the prepared, playing, paused, completed, or stopped state, in the prerequisite that the video window ID has been set in the initialized state. After the new setting is performed, the video is played in the new window.<br>It is used to render the window for video playback and therefore is not required in audio-only playback scenarios.<br>**Example:**<br>[Create a surface ID through XComponent](../apis-arkui/arkui-ts/ts-basic-components-xcomponent.md#getxcomponentsurfaceid).<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 602| loop<sup>9+</sup> | boolean | No | No | Whether to loop playback. The value **true** means to loop playback, and **false** (default) means the opposite. It is a dynamic attribute<br>and can be set only when the AVPlayer is in the prepared, playing, paused, or completed state.<br>This setting is not supported in live mode.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 603| videoScaleType<sup>9+</sup> | [VideoScaleType](#videoscaletype9) | No | Yes | Video scale type. The default value is **VIDEO_SCALE_TYPE_FIT**. It is a dynamic attribute<br>and can be set only when the AVPlayer is in the prepared, playing, paused, or completed state.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 604| audioInterruptMode<sup>9+</sup> | [audio.InterruptMode](../apis-audio-kit/js-apis-audio.md#interruptmode9) | No | Yes | Audio interruption mode. The default value is **SHARE_MODE**. It is a dynamic attribute<br>and can be set only when the AVPlayer is in the prepared, playing, paused, or completed state.<br>To take effect, this attribute must be set before [play()](#play9) is called for the first time.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 605| audioRendererInfo<sup>10+</sup> | [audio.AudioRendererInfo](../apis-audio-kit/js-apis-audio.md#audiorendererinfo8) | No | Yes | Audio renderer information. If the media source contains videos, the default value of **usage** is **STREAM_USAGE_MOVIE**. Otherwise, the default value of **usage** is **STREAM_USAGE_MUSIC**. The default value of **rendererFlags** is 0. If the default value of **usage** does not meet the requirements, configure [audio.AudioRendererInfo](../apis-audio-kit/js-apis-audio.md#audiorendererinfo8).<br>This parameter can be set only when the AVPlayer is in the initialized state.<br>To take effect, this attribute must be set before [prepare()](#prepare9) is called for the first time.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 606| audioEffectMode<sup>10+</sup> | [audio.AudioEffectMode](../apis-audio-kit/js-apis-audio.md#audioeffectmode10) | No | Yes | Audio effect mode. The audio effect mode is a dynamic attribute and is restored to the default value **EFFECT_DEFAULT** when **usage** of **audioRendererInfo** is changed. It can be set only when the AVPlayer is in the prepared, playing, paused, or completed state.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 607| state<sup>9+</sup> | [AVPlayerState](#avplayerstate9) | Yes | No | AVPlayer state. It can be used as a query parameter when the AVPlayer is in any state.<br>**Atomic service API**: This API can be used in atomic services since API version 12. | 608| currentTime<sup>9+</sup> | number | Yes | No | Current video playback position, in ms. It can be used as a query parameter when the AVPlayer is in the prepared, playing, paused, or completed state.<br>The value **-1** indicates an invalid value.<br>In live mode, **-1** is returned by default.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 609| duration<sup>9+</sup> | number | Yes | No | Video duration, in ms. It can be used as a query parameter when the AVPlayer is in the prepared, playing, paused, or completed state.<br>The value **-1** indicates an invalid value.<br>In live mode, **-1** is returned by default.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 610| width<sup>9+</sup> | number | Yes | No | Video width, in px. It can be used as a query parameter when the AVPlayer is in the prepared, playing, paused, or completed state.<br>The value **0** indicates an invalid value.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 611| height<sup>9+</sup> | number | Yes | No | Video height, in px. It can be used as a query parameter when the AVPlayer is in the prepared, playing, paused, or completed state.<br>The value **0** indicates an invalid value.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 612 613### on('stateChange')<sup>9+</sup> 614 615on(type: 'stateChange', callback: OnAVPlayerStateChangeHandle): void 616 617Subscribes to AVPlayer state changes. 618 619**Atomic service API**: This API can be used in atomic services since API version 11. 620 621**System capability**: SystemCapability.Multimedia.Media.AVPlayer 622 623**Parameters** 624 625| Name | Type | Mandatory| Description | 626| -------- | -------- | ---- | ------------------------------------------------------------ | 627| type | string | Yes | Event type, which is **'stateChange'** in this case. This event can be triggered by both user operations and the system.| 628| callback | [OnAVPlayerStateChangeHandle](#onavplayerstatechangehandle12) | Yes | Callback invoked when the event is triggered.| 629 630**Example** 631 632```ts 633avPlayer.on('stateChange', async (state: string, reason: media.StateChangeReason) => { 634 switch (state) { 635 case 'idle': 636 console.info('state idle called'); 637 break; 638 case 'initialized': 639 console.info('initialized prepared called'); 640 break; 641 case 'prepared': 642 console.info('state prepared called'); 643 break; 644 case 'playing': 645 console.info('state playing called'); 646 break; 647 case 'paused': 648 console.info('state paused called'); 649 break; 650 case 'completed': 651 console.info('state completed called'); 652 break; 653 case 'stopped': 654 console.info('state stopped called'); 655 break; 656 case 'released': 657 console.info('state released called'); 658 break; 659 case 'error': 660 console.info('state error called'); 661 break; 662 default: 663 console.info('unknown state :' + state); 664 break; 665 } 666}) 667``` 668 669### off('stateChange')<sup>9+</sup> 670 671off(type: 'stateChange', callback?: OnAVPlayerStateChangeHandle): void 672 673Unsubscribes from AVPlayer state changes. 674 675**Atomic service API**: This API can be used in atomic services since API version 11. 676 677**System capability**: SystemCapability.Multimedia.Media.AVPlayer 678 679**Parameters** 680 681| Name| Type | Mandatory| Description | 682| ------ | ------ | ---- | ----------------------------------------------------- | 683| type | string | Yes | Event type, which is **'stateChange'** in this case.| 684| callback | [OnAVPlayerStateChangeHandle](#onavplayerstatechangehandle12) | No | Callback invoked when the event is triggered.<br>This parameter is supported since API version 12.| 685 686**Example** 687 688```ts 689avPlayer.off('stateChange') 690``` 691 692### on('error')<sup>9+</sup> 693 694on(type: 'error', callback: ErrorCallback): void 695 696Subscribes to AVPlayer errors. This event is used only for error prompt and does not require the user to stop playback control. If [AVPlayerState](#avplayerstate9) is also switched to error, call [reset()](#reset9) or [release()](#release9) to exit the playback. 697 698**Atomic service API**: This API can be used in atomic services since API version 11. 699 700**System capability**: SystemCapability.Multimedia.Media.AVPlayer 701 702**Parameters** 703 704| Name | Type | Mandatory| Description | 705| -------- | -------- | ---- | ------------------------------------------------------------ | 706| type | string | Yes | Event type, which is **'error'** in this case. This event can be triggered by both user operations and the system.| 707| callback | [ErrorCallback](../apis-basic-services-kit/js-apis-base.md#errorcallback) | Yes | Callback used to return the error code ID and error message.| 708 709**Error codes** 710 711For details about the error codes, see [Media Error Codes](errorcode-media.md). 712 713| ID| Error Message | 714| -------- | --------------------- | 715| 201 | Permission denied | 716| 401 | The parameter check failed. | 717| 801 | Capability not supported. | 718| 5400101 | No memory. | 719| 5400102 | Operation not allowed.| 720| 5400103 | I/O error | 721| 5400104 | Time out | 722| 5400105 | Service died. | 723| 5400106 | Unsupport format. | 724 725**Example** 726 727```ts 728import { BusinessError } from '@kit.BasicServicesKit'; 729 730avPlayer.on('error', (error: BusinessError) => { 731 console.info('error happened,and error message is :' + error.message) 732 console.info('error happened,and error code is :' + error.code) 733}) 734``` 735 736### off('error')<sup>9+</sup> 737 738off(type: 'error', callback?: ErrorCallback): void 739 740Unsubscribes from AVPlayer errors. 741 742**Atomic service API**: This API can be used in atomic services since API version 11. 743 744**System capability**: SystemCapability.Multimedia.Media.AVPlayer 745 746**Parameters** 747 748| Name| Type | Mandatory| Description | 749| ------ | ------ | ---- | ----------------------------------------- | 750| type | string | Yes | Event type, which is **'error'** in this case.| 751| callback | [ErrorCallback](../apis-basic-services-kit/js-apis-base.md#errorcallback) | No | Callback used to return the error code ID and error message.<br>This parameter is supported since API version 12.| 752 753**Example** 754 755```ts 756avPlayer.off('error') 757``` 758 759### setMediaSource<sup>12+</sup> 760 761setMediaSource(src:MediaSource, strategy?: PlaybackStrategy): Promise\<void> 762 763Sets a source of streaming media that can be pre-downloaded, downloads the media data, and temporarily stores the data in the memory. For details about how to use the API, see [Video Playback](../../media/media/video-playback.md) This API uses a promise to return the result. 764 765**Atomic service API**: This API can be used in atomic services since API version 12. 766 767**System capability**: SystemCapability.Multimedia.Media.AVPlayer 768 769**Parameters** 770 771| Name | Type | Mandatory| Description | 772| -------- | -------- | ---- | -------------------- | 773| src | [MediaSource](#mediasource12) | Yes | Source of the streaming media to pre-download.| 774| strategy | [PlaybackStrategy](#playbackstrategy12) | No | strategy for playing the pre-downloaded streaming media.| 775 776**Return value** 777 778| Type | Description | 779| -------------- | ------------------------------------------ | 780| Promise\<void> | Promise that returns no value.| 781 782**Error codes** 783 784For details about the error codes, see [Media Error Codes](errorcode-media.md). 785 786| ID| Error Message | 787| -------- | ----------------------------------------- | 788| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 789| 5400102 | Operation not allowed. Return by promise. | 790 791**Example** 792 793```ts 794import { media } from '@kit.MediaKit'; 795 796let player = await media.createAVPlayer(); 797let headers: Record<string, string> = {"User-Agent" : "User-Agent-Value"}; 798let mediaSource : media.MediaSource = media.createMediaSourceWithUrl("http://xxx", headers); 799let playStrategy : media.PlaybackStrategy = {preferredWidth: 1, preferredHeight: 2, preferredBufferDuration: 3, preferredHdr: false}; 800player.setMediaSource(mediaSource, playStrategy); 801``` 802 803### setPlaybackStrategy<sup>12+</sup> 804 805setPlaybackStrategy(strategy: PlaybackStrategy): Promise\<void> 806 807Sets a playback strategy. This API can be called only when the AVPlayer is in the initialized state. 808 809**Atomic service API**: This API can be used in atomic services since API version 12. 810 811**System capability**: SystemCapability.Multimedia.Media.AVPlayer 812 813**Parameters** 814 815| Name | Type | Mandatory| Description | 816| -------- | -------- | ---- | -------------------- | 817| strategy | [PlaybackStrategy](#playbackstrategy12) | Yes | Playback strategy.| 818 819**Return value** 820 821| Type | Description | 822| -------------- | ------------------------------------ | 823| Promise\<void> | Promise that returns no value.| 824 825**Error codes** 826 827For details about the error codes, see [Media Error Codes](errorcode-media.md). 828 829| ID| Error Message | 830| -------- | ----------------------------------------- | 831| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. 2. Parameter verification failed. | 832| 5400102 | Operation not allowed. Return by promise. | 833 834**Example** 835 836```ts 837import { media } from '@kit.MediaKit'; 838 839let player = await media.createAVPlayer(); 840let fileDescriptor = await context.resourceManager.getRawFd('xxx.mp4') 841player.fdSrc = fileDescriptor 842let playStrategy : media.PlaybackStrategy = {preferredWidth: 1, preferredHeight: 2, preferredBufferDuration: 3, 843 preferredHdr: false, mutedMediaType: media.MediaType.MEDIA_TYPE_AUD}; 844player.setPlaybackStrategy(playStrategy); 845``` 846 847### prepare<sup>9+</sup> 848 849prepare(callback: AsyncCallback\<void>): void 850 851Prepares for audio and video playback. This API can be called only when the AVPlayer is in the initialized state. The state changes can be detected by subscribing to the [stateChange](#onstatechange9) event. This API uses an asynchronous callback to return the result. 852 853**Atomic service API**: This API can be used in atomic services since API version 11. 854 855**System capability**: SystemCapability.Multimedia.Media.AVPlayer 856 857**Parameters** 858 859| Name | Type | Mandatory| Description | 860| -------- | -------- | ---- | -------------------- | 861| callback | AsyncCallback\<void> | Yes | Callback used to return the result.| 862 863**Error codes** 864 865For details about the error codes, see [Media Error Codes](errorcode-media.md). 866 867| ID| Error Message | 868| -------- | ------------------------------------------ | 869| 5400102 | Operation not allowed. Return by callback. | 870| 5400106 | Unsupport format. Return by callback. | 871 872**Example** 873 874```ts 875import { BusinessError } from '@kit.BasicServicesKit'; 876 877avPlayer.prepare((err: BusinessError) => { 878 if (err) { 879 console.error('Failed to prepare,error message is :' + err.message) 880 } else { 881 console.info('Succeeded in preparing'); 882 } 883}) 884``` 885 886### prepare<sup>9+</sup> 887 888prepare(): Promise\<void> 889 890Prepares for audio and video playback. This API can be called only when the AVPlayer is in the initialized state. The state changes can be detected by subscribing to the [stateChange](#onstatechange9) event. This API uses a promise to return the result. 891 892**Atomic service API**: This API can be used in atomic services since API version 11. 893 894**System capability**: SystemCapability.Multimedia.Media.AVPlayer 895 896**Return value** 897 898| Type | Description | 899| -------------- | ------------------------- | 900| Promise\<void> | Promise that returns no value.| 901 902**Error codes** 903 904For details about the error codes, see [Media Error Codes](errorcode-media.md). 905 906| ID| Error Message | 907| -------- | ----------------------------------------- | 908| 5400102 | Operation not allowed. Return by promise. | 909| 5400106 | Unsupport format. Return by promise. | 910 911**Example** 912 913```ts 914import { BusinessError } from '@kit.BasicServicesKit'; 915 916avPlayer.prepare().then(() => { 917 console.info('Succeeded in preparing'); 918}, (err: BusinessError) => { 919 console.error('Failed to prepare,error message is :' + err.message) 920}) 921``` 922 923### setMediaMuted<sup>12+</sup> 924 925setMediaMuted(mediaType: MediaType, muted: boolean ): Promise\<void> 926 927Mutes or unmutes the audio. This API can be called only when the AVPlayer is in the prepared, playing, paused, or completed state. The **mediaType** parameter can be set only to the audio format. 928 929**Atomic service API**: This API can be used in atomic services since API version 12. 930 931**System capability**: SystemCapability.Multimedia.Media.AVPlayer 932 933**Parameters** 934 935| Name | Type | Mandatory| Description | 936| -------- | -------- | ---- | -------------------- | 937| mediaType | [MediaType](#mediatype8) | Yes | Media type.| 938| muted | boolean | Yes | Whether to mute the audio.| 939 940**Return value** 941 942| Type | Description | 943| -------------- | ------------------------- | 944| Promise\<void> | Promise that returns no value.| 945 946**Error codes** 947 948For details about the error codes, see [Media Error Codes](errorcode-media.md). 949 950| ID| Error Message| 951| -------- | ----------------------------------------- | 952| 401 | The parameter check failed. Return by promise. | 953| 5400102 | Operation not allowed. Return by promise. | 954 955**Example** 956 957```ts 958import { BusinessError } from '@kit.BasicServicesKit'; 959 960avPlayer.prepare().then(() => { 961 console.info('Succeeded in preparing'); 962 avPlayer.setMediaMuted(media.MediaType.MEDIA_TYPE_AUD, true) 963}, (err: BusinessError) => { 964 console.error('Failed to prepare,error message is :' + err.message) 965}) 966``` 967 968### play<sup>9+</sup> 969 970play(callback: AsyncCallback\<void>): void 971 972Starts to play an audio and video asset. This API can be called only when the AVPlayer is in the prepared, paused, or completed state. This API uses an asynchronous callback to return the result. 973 974**Atomic service API**: This API can be used in atomic services since API version 11. 975 976**System capability**: SystemCapability.Multimedia.Media.AVPlayer 977 978**Parameters** 979 980| Name | Type | Mandatory| Description | 981| -------- | -------- | ---- | -------------------- | 982| callback | AsyncCallback\<void> | Yes | Callback used to return the result.| 983 984**Error codes** 985 986For details about the error codes, see [Media Error Codes](errorcode-media.md). 987 988| ID| Error Message | 989| -------- | ------------------------------------------ | 990| 5400102 | Operation not allowed. Return by callback. | 991 992**Example** 993 994```ts 995import { BusinessError } from '@kit.BasicServicesKit'; 996 997avPlayer.play((err: BusinessError) => { 998 if (err) { 999 console.error('Failed to play,error message is :' + err.message) 1000 } else { 1001 console.info('Succeeded in playing'); 1002 } 1003}) 1004``` 1005 1006### play<sup>9+</sup> 1007 1008play(): Promise\<void> 1009 1010Starts to play an audio and video asset. This API can be called only when the AVPlayer is in the prepared, paused, or completed state. This API uses a promise to return the result. 1011 1012**Atomic service API**: This API can be used in atomic services since API version 11. 1013 1014**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1015 1016**Return value** 1017 1018| Type | Description | 1019| -------------- | ------------------------- | 1020| Promise\<void> | Promise that returns no value.| 1021 1022**Error codes** 1023 1024For details about the error codes, see [Media Error Codes](errorcode-media.md). 1025 1026| ID| Error Message | 1027| -------- | ----------------------------------------- | 1028| 5400102 | Operation not allowed. Return by promise. | 1029 1030**Example** 1031 1032```ts 1033import { BusinessError } from '@kit.BasicServicesKit'; 1034 1035avPlayer.play().then(() => { 1036 console.info('Succeeded in playing'); 1037}, (err: BusinessError) => { 1038 console.error('Failed to play,error message is :' + err.message) 1039}) 1040``` 1041 1042### pause<sup>9+</sup> 1043 1044pause(callback: AsyncCallback\<void>): void 1045 1046Pauses audio and video playback. This API can be called only when the AVPlayer is in the playing state. This API uses an asynchronous callback to return the result. 1047 1048**Atomic service API**: This API can be used in atomic services since API version 11. 1049 1050**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1051 1052**Parameters** 1053 1054| Name | Type | Mandatory| Description | 1055| -------- | -------- | ---- | -------------------- | 1056| callback | AsyncCallback\<void> | Yes | Callback used to return the result.| 1057 1058**Error codes** 1059 1060For details about the error codes, see [Media Error Codes](errorcode-media.md). 1061 1062| ID| Error Message | 1063| -------- | ------------------------------------------ | 1064| 5400102 | Operation not allowed. Return by callback. | 1065 1066**Example** 1067 1068```ts 1069import { BusinessError } from '@kit.BasicServicesKit'; 1070 1071avPlayer.pause((err: BusinessError) => { 1072 if (err) { 1073 console.error('Failed to pause,error message is :' + err.message) 1074 } else { 1075 console.info('Succeeded in pausing'); 1076 } 1077}) 1078``` 1079 1080### pause<sup>9+</sup> 1081 1082pause(): Promise\<void> 1083 1084Pauses audio and video playback. This API can be called only when the AVPlayer is in the playing state. This API uses a promise to return the result. 1085 1086**Atomic service API**: This API can be used in atomic services since API version 11. 1087 1088**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1089 1090**Return value** 1091 1092| Type | Description | 1093| -------------- | ------------------------- | 1094| Promise\<void> | Promise that returns no value.| 1095 1096**Error codes** 1097 1098For details about the error codes, see [Media Error Codes](errorcode-media.md). 1099 1100| ID| Error Message | 1101| -------- | ----------------------------------------- | 1102| 5400102 | Operation not allowed. Return by promise. | 1103 1104**Example** 1105 1106```ts 1107import { BusinessError } from '@kit.BasicServicesKit'; 1108 1109avPlayer.pause().then(() => { 1110 console.info('Succeeded in pausing'); 1111}, (err: BusinessError) => { 1112 console.error('Failed to pause,error message is :' + err.message) 1113}) 1114``` 1115 1116### stop<sup>9+</sup> 1117 1118stop(callback: AsyncCallback\<void>): void 1119 1120Stops audio and video playback. This API can be called only when the AVPlayer is in the prepared, playing, paused, or completed state. This API uses an asynchronous callback to return the result. 1121 1122**Atomic service API**: This API can be used in atomic services since API version 11. 1123 1124**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1125 1126**Parameters** 1127 1128| Name | Type | Mandatory| Description | 1129| -------- | -------- | ---- | -------------------- | 1130| callback | AsyncCallback\<void> | Yes | Callback used to return the result.| 1131 1132**Error codes** 1133 1134For details about the error codes, see [Media Error Codes](errorcode-media.md). 1135 1136| ID| Error Message | 1137| -------- | ------------------------------------------ | 1138| 5400102 | Operation not allowed. Return by callback. | 1139 1140**Example** 1141 1142```ts 1143import { BusinessError } from '@kit.BasicServicesKit'; 1144 1145avPlayer.stop((err: BusinessError) => { 1146 if (err) { 1147 console.error('Failed to stop,error message is :' + err.message) 1148 } else { 1149 console.info('Succeeded in stopping'); 1150 } 1151}) 1152``` 1153 1154### stop<sup>9+</sup> 1155 1156stop(): Promise\<void> 1157 1158Stops audio and video playback. This API can be called only when the AVPlayer is in the prepared, playing, paused, or completed state. This API uses a promise to return the result. 1159 1160**Atomic service API**: This API can be used in atomic services since API version 11. 1161 1162**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1163 1164**Return value** 1165 1166| Type | Description | 1167| -------------- | ------------------------- | 1168| Promise\<void> | Promise that returns no value.| 1169 1170**Error codes** 1171 1172For details about the error codes, see [Media Error Codes](errorcode-media.md). 1173 1174| ID| Error Message | 1175| -------- | ----------------------------------------- | 1176| 5400102 | Operation not allowed. Return by promise. | 1177 1178**Example** 1179 1180```ts 1181import { BusinessError } from '@kit.BasicServicesKit'; 1182 1183avPlayer.stop().then(() => { 1184 console.info('Succeeded in stopping'); 1185}, (err: BusinessError) => { 1186 console.error('Failed to stop,error message is :' + err.message) 1187}) 1188``` 1189 1190### reset<sup>9+</sup> 1191 1192reset(callback: AsyncCallback\<void>): void 1193 1194Resets audio and video playback. This API can be called only when the AVPlayer is in the initialized, prepared, playing, paused, completed, stopped, or error state. This API uses an asynchronous callback to return the result. 1195 1196**Atomic service API**: This API can be used in atomic services since API version 11. 1197 1198**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1199 1200**Parameters** 1201 1202| Name | Type | Mandatory| Description | 1203| -------- | -------- | ---- | -------------------- | 1204| callback | AsyncCallback\<void> | Yes | Callback used to return the result.| 1205 1206**Error codes** 1207 1208For details about the error codes, see [Media Error Codes](errorcode-media.md). 1209 1210| ID| Error Message | 1211| -------- | ------------------------------------------ | 1212| 5400102 | Operation not allowed. Return by callback. | 1213 1214**Example** 1215 1216```ts 1217import { BusinessError } from '@kit.BasicServicesKit'; 1218 1219avPlayer.reset((err: BusinessError) => { 1220 if (err) { 1221 console.error('Failed to reset,error message is :' + err.message) 1222 } else { 1223 console.info('Succeeded in resetting'); 1224 } 1225}) 1226``` 1227 1228### reset<sup>9+</sup> 1229 1230reset(): Promise\<void> 1231 1232Resets audio and video playback. This API can be called only when the AVPlayer is in the initialized, prepared, playing, paused, completed, stopped, or error state. This API uses a promise to return the result. 1233 1234**Atomic service API**: This API can be used in atomic services since API version 11. 1235 1236**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1237 1238**Return value** 1239 1240| Type | Description | 1241| -------------- | ------------------------- | 1242| Promise\<void> | Promise that returns no value.| 1243 1244**Error codes** 1245 1246For details about the error codes, see [Media Error Codes](errorcode-media.md). 1247 1248| ID| Error Message | 1249| -------- | ----------------------------------------- | 1250| 5400102 | Operation not allowed. Return by promise. | 1251 1252**Example** 1253 1254```ts 1255import { BusinessError } from '@kit.BasicServicesKit'; 1256 1257avPlayer.reset().then(() => { 1258 console.info('Succeeded in resetting'); 1259}, (err: BusinessError) => { 1260 console.error('Failed to reset,error message is :' + err.message) 1261}) 1262``` 1263 1264### release<sup>9+</sup> 1265 1266release(callback: AsyncCallback\<void>): void 1267 1268Releases the playback resources. This API can be called when the AVPlayer is in any state except released. This API uses an asynchronous callback to return the result. 1269 1270**Atomic service API**: This API can be used in atomic services since API version 11. 1271 1272**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1273 1274**Parameters** 1275 1276| Name | Type | Mandatory| Description | 1277| -------- | -------- | ---- | -------------------- | 1278| callback | AsyncCallback\<void> | Yes | Callback used to return the result.| 1279 1280**Error codes** 1281 1282For details about the error codes, see [Media Error Codes](errorcode-media.md). 1283 1284| ID| Error Message | 1285| -------- | ------------------------------------------ | 1286| 5400102 | Operation not allowed. Return by callback. | 1287 1288**Example** 1289 1290```ts 1291import { BusinessError } from '@kit.BasicServicesKit'; 1292 1293avPlayer.release((err: BusinessError) => { 1294 if (err) { 1295 console.error('Failed to release,error message is :' + err.message) 1296 } else { 1297 console.info('Succeeded in releasing'); 1298 } 1299}) 1300``` 1301 1302### release<sup>9+</sup> 1303 1304release(): Promise\<void> 1305 1306Releases the playback resources. This API can be called when the AVPlayer is in any state except released. This API uses a promise to return the result. 1307 1308**Atomic service API**: This API can be used in atomic services since API version 11. 1309 1310**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1311 1312**Return value** 1313 1314| Type | Description | 1315| -------------- | ------------------------- | 1316| Promise\<void> | Promise that returns no value.| 1317 1318**Error codes** 1319 1320For details about the error codes, see [Media Error Codes](errorcode-media.md). 1321 1322| ID| Error Message | 1323| -------- | ----------------------------------------- | 1324| 5400102 | Operation not allowed. Return by promise. | 1325 1326**Example** 1327 1328```ts 1329import { BusinessError } from '@kit.BasicServicesKit'; 1330 1331avPlayer.release().then(() => { 1332 console.info('Succeeded in releasing'); 1333}, (err: BusinessError) => { 1334 console.error('Failed to release,error message is :' + err.message) 1335}) 1336``` 1337 1338### getTrackDescription<sup>9+</sup> 1339 1340getTrackDescription(callback: AsyncCallback\<Array\<MediaDescription>>): void 1341 1342Obtains the audio and video track information. This API can be called only when the AVPlayer is in the prepared, playing, or paused state. To obtain information about all audio and video tracks, this API must be called after the data loading callback is triggered. This API uses an asynchronous callback to return the result. 1343 1344**Atomic service API**: This API can be used in atomic services since API version 11. 1345 1346**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1347 1348**Parameters** 1349 1350| Name | Type | Mandatory| Description | 1351| -------- | ------------------------------------------------------------ | ---- | -------------------------------------------- | 1352| callback | AsyncCallback<Array<[MediaDescription](#mediadescription8)>> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the MediaDescription array obtained; otherwise, **err** is an error object.| 1353 1354**Error codes** 1355 1356For details about the error codes, see [Media Error Codes](errorcode-media.md). 1357 1358| ID| Error Message | 1359| -------- | ------------------------------------------ | 1360| 5400102 | Operation not allowed. Return by callback. | 1361 1362**Example** 1363 1364```ts 1365import { BusinessError } from '@kit.BasicServicesKit'; 1366 1367avPlayer.getTrackDescription((error: BusinessError, arrList: Array<media.MediaDescription>) => { 1368 if ((arrList) != null) { 1369 console.info('Succeeded in doing getTrackDescription'); 1370 } else { 1371 console.error(`Failed to do getTrackDescription, error:${error}`); 1372 } 1373}); 1374``` 1375 1376### getTrackDescription<sup>9+</sup> 1377 1378getTrackDescription(): Promise\<Array\<MediaDescription>> 1379 1380Obtains the audio and video track information. This API can be called only when the AVPlayer is in the prepared, playing, or paused state. This API uses a promise to return the result. 1381 1382**Atomic service API**: This API can be used in atomic services since API version 11. 1383 1384**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1385 1386**Return value** 1387 1388| Type | Description | 1389| ------------------------------------------------------ | ------------------------------------------------- | 1390| Promise<Array<[MediaDescription](#mediadescription8)>> | Promise used to return the MediaDescription array that holds the audio and video track information.| 1391 1392**Error codes** 1393 1394For details about the error codes, see [Media Error Codes](errorcode-media.md). 1395 1396| ID| Error Message | 1397| -------- | ----------------------------------------- | 1398| 5400102 | Operation not allowed. Return by promise. | 1399 1400**Example** 1401 1402```ts 1403import { BusinessError } from '@kit.BasicServicesKit'; 1404 1405avPlayer.getTrackDescription().then((arrList: Array<media.MediaDescription>) => { 1406 console.info('Succeeded in getting TrackDescription'); 1407}).catch((error: BusinessError) => { 1408 console.error(`Failed to get TrackDescription, error:${error}`); 1409}); 1410``` 1411 1412### getSelectedTracks<sup>12+</sup> 1413 1414getSelectedTracks(): Promise\<Array\<number>> 1415 1416Obtains the indexes of the selected audio or video tracks. This API can be called only when the AVPlayer is in the prepared, playing, or paused state. This API uses a promise to return the result. 1417 1418**Atomic service API**: This API can be used in atomic services since API version 12. 1419 1420**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1421 1422**Return value** 1423 1424| Type | Description | 1425| ------------------------------------------------------ | ------------------------------------------------- | 1426| Promise<Array<[number]>> | Promise used to return the index array.| 1427 1428**Error codes** 1429 1430For details about the error codes, see [Media Error Codes](errorcode-media.md). 1431 1432| ID| Error Message | 1433| -------- | ----------------------------------------- | 1434| 5400102 | Operation not allowed. | 1435 1436**Example** 1437 1438```ts 1439import { BusinessError } from '@kit.BasicServicesKit'; 1440 1441avPlayer.getSelectedTracks().then((arrList: Array<number>) => { 1442 console.info('Succeeded in getting SelectedTracks'); 1443}).catch((error: BusinessError) => { 1444 console.error(`Failed to get SelectedTracks, error:${error}`); 1445}); 1446``` 1447 1448### getPlaybackInfo<sup>12+</sup> 1449 1450getPlaybackInfo(): Promise\<PlaybackInfo> 1451 1452Obtains the playback information. This API can be called only when the AVPlayer is in the prepared, playing, or paused state. This API uses a promise to return the result. 1453 1454**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1455 1456**Return value** 1457 1458| Type | Description | 1459| ------------------------------------------------------ | ------------------------------------------------- | 1460| Promise<[PlaybackInfo](#playbackinfo12)> | Promise used to return **PlaybackInfo**.| 1461 1462**Example** 1463 1464```ts 1465import { BusinessError } from '@kit.BasicServicesKit'; 1466import { media } from '@kit.MediaKit'; 1467 1468let avPlayer: media.AVPlayer | undefined = undefined; 1469let playbackInfo: media.PlaybackInfo | undefined = undefined; 1470media.createAVPlayer(async (err: BusinessError, player: media.AVPlayer) => { 1471 if (player != null) { 1472 avPlayer = player; 1473 console.info(`Succeeded in creating AVPlayer`); 1474 if (avPlayer) { 1475 try { 1476 playbackInfo = await avPlayer.getPlaybackInfo(); 1477 console.info(`AVPlayer getPlaybackInfo = ${JSON.stringify(playbackInfo)}`); // Print PlaybackInfo. 1478 } catch (error) { 1479 console.error(`error = ${error}`); 1480 } 1481 } 1482 } else { 1483 console.error(`Failed to create AVPlayer, error message:${err.message}`); 1484 } 1485}); 1486``` 1487 1488### selectTrack<sup>12+</sup> 1489 1490selectTrack(index: number, mode?: SwitchMode): Promise\<void> 1491 1492Selects an audio track when the AVPlayer is used to play a video with multiple audio tracks. This API uses a promise to return the result. 1493 1494**Atomic service API**: This API can be used in atomic services since API version 12. 1495 1496**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1497 1498**Parameters** 1499 1500| Name | Type | Mandatory| Description | 1501| -------- | -------- | ---- | -------------------- | 1502| index | number | Yes | Index of the audio track, which is obtained from [MediaDescription](#mediadescription8).| 1503| mode | [SwitchMode](#switchmode12) | No | Video track switch mode. The default mode is **SMOOTH**. Only the DASH protocol is supported. **This parameter is valid only for video playback.**| 1504 1505**Return value** 1506 1507| Type | Description | 1508| -------------- | ------------------------- | 1509| Promise\<void> | Promise that returns no value.| 1510 1511**Error codes** 1512 1513For details about the error codes, see [Media Error Codes](errorcode-media.md). 1514 1515| ID| Error Message | 1516| -------- | ----------------------------------------- | 1517| 401 | The parameter check failed. Return by promise. | 1518| 5400102 | Operation not allowed. Return by promise. | 1519 1520**Example** 1521 1522```ts 1523import { BusinessError } from '@kit.BasicServicesKit'; 1524import { media } from '@kit.MediaKit'; 1525 1526let avPlayer: media.AVPlayer = await media.createAVPlayer(); 1527let audioTrackIndex: Object = 0; 1528avPlayer.getTrackDescription((error: BusinessError, arrList: Array<media.MediaDescription>) => { 1529 if (arrList != null) { 1530 for (let i = 0; i < arrList.length; i++) { 1531 if (i != 0) { 1532 // Obtain the audio track list. 1533 audioTrackIndex = arrList[i][media.MediaDescriptionKey.MD_KEY_TRACK_INDEX]; 1534 } 1535 } 1536 } else { 1537 console.error(`Failed to get TrackDescription, error:${error}`); 1538 } 1539}); 1540 1541// Select an audio track. 1542avPlayer.selectTrack(parseInt(audioTrackIndex.toString())); 1543``` 1544 1545### deselectTrack<sup>12+</sup> 1546 1547deselectTrack(index: number): Promise\<void> 1548 1549Deselects an audio track when the AVPlayer is used to play a video with multiple audio tracks. This API uses a promise to return the result. 1550 1551**Atomic service API**: This API can be used in atomic services since API version 12. 1552 1553**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1554 1555**Parameters** 1556 1557| Name | Type | Mandatory| Description | 1558| -------- | -------- | ---- | -------------------- | 1559| index | number | Yes | Index of the audio track, which is obtained from [MediaDescription](#mediadescription8).| 1560 1561**Return value** 1562 1563| Type | Description | 1564| -------------- | ------------------------- | 1565| Promise\<void> | Promise that returns no value.| 1566 1567**Error codes** 1568 1569For details about the error codes, see [Media Error Codes](errorcode-media.md). 1570 1571| ID| Error Message | 1572| -------- | ----------------------------------------- | 1573| 401 | The parameter check failed. Return by promise. | 1574| 5400102 | Operation not allowed. Return by promise. | 1575 1576**Example** 1577 1578```ts 1579import { BusinessError } from '@kit.BasicServicesKit'; 1580import { media } from '@kit.MediaKit'; 1581 1582let avPlayer: media.AVPlayer = await media.createAVPlayer(); 1583let audioTrackIndex: Object = 0; 1584avPlayer.getTrackDescription((error: BusinessError, arrList: Array<media.MediaDescription>) => { 1585 if (arrList != null) { 1586 for (let i = 0; i < arrList.length; i++) { 1587 if (i != 0) { 1588 // Obtain the audio track list. 1589 audioTrackIndex = arrList[i][media.MediaDescriptionKey.MD_KEY_TRACK_INDEX]; 1590 } 1591 } 1592 } else { 1593 console.error(`Failed to get TrackDescription, error:${error}`); 1594 } 1595}); 1596 1597// Select an audio track. 1598avPlayer.selectTrack(parseInt(audioTrackIndex.toString())); 1599// Deselect the audio track and restore to the default audio track. 1600avPlayer.deselectTrack(parseInt(audioTrackIndex.toString())); 1601``` 1602 1603### setDecryptionConfig<sup>11+</sup> 1604 1605setDecryptionConfig(mediaKeySession: drm.MediaKeySession, secureVideoPath: boolean): void 1606 1607Sets the decryption configuration. When receiving a [mediaKeySystemInfoUpdate event](#onmediakeysysteminfoupdate11), create the related configuration and set the decryption configuration based on the information in the reported event. Otherwise, the playback fails. 1608 1609**Atomic service API**: This API can be used in atomic services since API version 12. 1610 1611**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1612 1613**Parameters** 1614 1615| Name | Type | Mandatory| Description | 1616| -------- | ------------------------------------------------------------ | ---- | -------------------------------------------- | 1617| mediaKeySession | [drm.MediaKeySession](../apis-drm-kit/js-apis-drm.md#mediakeysession) | Yes | Decryption session.| 1618| secureVideoPath | boolean | Yes| Secure video channel. The value **true** means that a secure video channel is selected, and **false** means that a non-secure video channel is selected.| 1619 1620**Error codes** 1621 1622For details about the error codes, see [Media Error Codes](errorcode-media.md). 1623 1624| ID| Error Message | 1625| -------- | ----------------------------------------- | 1626| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 1627 1628**Example** 1629 1630For details about the DRM module, see [js-apis-drm.md](../apis-drm-kit/js-apis-drm.md). 1631```ts 1632import { drm } from '@kit.DrmKit'; 1633 1634// Create a media key system. 1635let keySystem:drm.MediaKeySystem = drm.createMediaKeySystem('com.clearplay.drm'); 1636// Create a media key session. 1637let keySession:drm.MediaKeySession = keySystem.createMediaKeySession(drm.ContentProtectionLevel.CONTENT_PROTECTION_LEVEL_SW_CRYPTO); 1638// Generate a media key request and set the response to the media key request. 1639// Flag indicating whether a secure video channel is used. 1640let secureVideoPath:boolean = false; 1641// Set the decryption configuration. 1642avPlayer.setDecryptionConfig(keySession, secureVideoPath); 1643``` 1644 1645### getMediaKeySystemInfos<sup>11+</sup> 1646 1647getMediaKeySystemInfos(): Array\<drm.MediaKeySystemInfo> 1648 1649Obtains the media key system information of the media asset that is being played. This API must be called after the [mediaKeySystemInfoUpdate event](#onmediakeysysteminfoupdate11) is triggered. 1650 1651**Atomic service API**: This API can be used in atomic services since API version 12. 1652 1653**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1654 1655**Return value** 1656 1657| Type | Description | 1658| ------------------------------------------------------ | ------------------------------------------------- | 1659| Array<[drm.MediaKeySystemInfo](../apis-drm-kit/js-apis-drm.md#mediakeysysteminfo)> | Array of **MediaKeySystemInfo** objects, each of which contains the **uuid** and **pssh** attributes.| 1660 1661**Example** 1662 1663```ts 1664import { drm } from '@kit.DrmKit'; 1665 1666const infos = avPlayer.getMediaKeySystemInfos(); 1667console.info('GetMediaKeySystemInfos count: ' + infos.length); 1668for (let i = 0; i < infos.length; i++) { 1669 console.info('GetMediaKeySystemInfos uuid: ' + infos[i]["uuid"]); 1670 console.info('GetMediaKeySystemInfos pssh: ' + infos[i]["pssh"]); 1671} 1672``` 1673 1674### seek<sup>9+</sup> 1675 1676seek(timeMs: number, mode?:SeekMode): void 1677 1678Seeks to the specified playback position. This API can be called only when the AVPlayer is in the prepared, playing, paused, or completed state. You can check whether the seek operation takes effect by subscribing to the [seekDone](#onseekdone9) event. 1679This API is not supported in live mode. 1680 1681**Atomic service API**: This API can be used in atomic services since API version 11. 1682 1683**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1684 1685**Parameters** 1686 1687| Name| Type | Mandatory| Description | 1688| ------ | ---------------------- | ---- | ------------------------------------------------------------ | 1689| timeMs | number | Yes | Position to seek to, in ms. The value range is [0, [duration](#attributes)].| 1690| mode | [SeekMode](#seekmode8) | No | Seek mode based on the video I frame. The default value is **SEEK_PREV_SYNC**. **Set this parameter only for video playback.**| 1691 1692**Example** 1693 1694```ts 1695let seekTime: number = 1000 1696avPlayer.seek(seekTime, media.SeekMode.SEEK_PREV_SYNC) 1697``` 1698 1699### on('seekDone')<sup>9+</sup> 1700 1701on(type: 'seekDone', callback: Callback\<number>): void 1702 1703Subscribes to the event to check whether the seek operation takes effect. 1704 1705**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1706 1707**Atomic service API**: This API can be used in atomic services since API version 11. 1708 1709**Parameters** 1710 1711| Name | Type | Mandatory| Description | 1712| -------- | -------- | ---- | ------------------------------------------------------------ | 1713| type | string | Yes | Event type, which is **'seekDone'** in this case. This event is triggered each time **seek()** is called.| 1714| callback | Callback\<number> | Yes | Callback invoked when the event is triggered. It reports the time position requested by the user.<br>For video playback, [SeekMode](#seekmode8) may cause the actual position to be different from that requested by the user. The exact position can be obtained from the **currentTime** attribute. The time in this callback only means that the requested seek operation is complete.| 1715 1716**Example** 1717 1718```ts 1719avPlayer.on('seekDone', (seekDoneTime:number) => { 1720 console.info('seekDone called,and seek time is:' + seekDoneTime) 1721}) 1722``` 1723 1724### off('seekDone')<sup>9+</sup> 1725 1726off(type: 'seekDone', callback?: Callback\<number>): void 1727 1728Unsubscribes from the event that checks whether the seek operation takes effect. 1729 1730**Atomic service API**: This API can be used in atomic services since API version 11. 1731 1732**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1733 1734**Parameters** 1735 1736| Name| Type | Mandatory| Description | 1737| ------ | ------ | ---- | ---------------------------------------------------- | 1738| type | string | Yes | Event type, which is **'seekDone'** in this case.| 1739| callback | Callback\<number> | No | Callback invoked when the event is triggered. It reports the time position requested by the user.<br>For video playback, [SeekMode](#seekmode8) may cause the actual position to be different from that requested by the user. The exact position can be obtained from the **currentTime** attribute. The time in this callback only means that the requested seek operation is complete.<br>This parameter is supported since API version 12.| 1740 1741**Example** 1742 1743```ts 1744avPlayer.off('seekDone') 1745``` 1746 1747### setSpeed<sup>9+</sup> 1748 1749setSpeed(speed: PlaybackSpeed): void 1750 1751Sets the playback speed. This API can be called only when the AVPlayer is in the prepared, playing, paused, or completed state. You can check whether the setting takes effect by subscribing to the [speedDone](#onspeeddone9) event. 1752This API is not supported in live mode. 1753 1754**Atomic service API**: This API can be used in atomic services since API version 12. 1755 1756**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1757 1758**Parameters** 1759 1760| Name| Type | Mandatory| Description | 1761| ------ | -------------------------------- | ---- | ------------------ | 1762| speed | [PlaybackSpeed](#playbackspeed8) | Yes | Playback speed to set.| 1763 1764**Example** 1765 1766```ts 1767avPlayer.setSpeed(media.PlaybackSpeed.SPEED_FORWARD_2_00_X) 1768``` 1769 1770### on('speedDone')<sup>9+</sup> 1771 1772on(type: 'speedDone', callback: Callback\<number>): void 1773 1774Subscribes to the event to check whether the playback speed is successfully set. 1775 1776**Atomic service API**: This API can be used in atomic services since API version 12. 1777 1778**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1779 1780**Parameters** 1781 1782| Name | Type | Mandatory| Description | 1783| -------- | -------- | ---- | ------------------------------------------------------------ | 1784| type | string | Yes | Event type, which is **'speedDone'** in this case. This event is triggered each time **setSpeed()** is called.| 1785| callback | Callback\<number> | Yes | Callback used to return the result. When the call of **setSpeed** is successful, the effective speed mode is reported. For details, see [PlaybackSpeed](#playbackspeed8).| 1786 1787**Example** 1788 1789```ts 1790avPlayer.on('speedDone', (speed:number) => { 1791 console.info('speedDone called,and speed value is:' + speed) 1792}) 1793``` 1794 1795### off('speedDone')<sup>9+</sup> 1796 1797off(type: 'speedDone', callback?: Callback\<number>): void 1798 1799Unsubscribes from the event that checks whether the playback speed is successfully set. 1800 1801**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1802 1803**Parameters** 1804 1805| Name| Type | Mandatory| Description | 1806| ------ | ------ | ---- | --------------------------------------------------------- | 1807| type | string | Yes | Event type, which is **'speedDone'** in this case.| 1808| callback | Callback\<number> | No | Callback used to return the result. When the call of **setSpeed** is successful, the effective speed mode is reported. For details, see [PlaybackSpeed](#playbackspeed8).<br>This parameter is supported since API version 12.| 1809 1810**Example** 1811 1812```ts 1813avPlayer.off('speedDone') 1814``` 1815 1816### setBitrate<sup>9+</sup> 1817 1818setBitrate(bitrate: number): void 1819 1820Sets the bit rate, which is valid only for HTTP Live Streaming (HLS) streams. This API can be called only when the AVPlayer is in the prepared, playing, paused, or completed state. You can check whether the setting takes effect by subscribing to the [bitrateDone](#onbitratedone9) event. Note that the AVPlayer selects a proper bit rate based on the network connection speed. 1821 1822**Atomic service API**: This API can be used in atomic services since API version 12. 1823 1824**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1825 1826**Parameters** 1827 1828| Name | Type | Mandatory| Description | 1829| ------- | ------ | ---- | ------------------------------------------------------------ | 1830| bitrate | number | Yes | Bit rate to set. You can obtain the available bit rates of the current HLS stream by subscribing to the [availableBitrates](#onavailablebitrates9) event. If the bit rate to set is not in the list of the available bit rates, the AVPlayer selects from the list the minimum bit rate that is closed to the bit rate to set. If the length of the available bit rate list obtained through the event is 0, no bit rate can be set and the **bitrateDone** callback will not be triggered.| 1831 1832**Example** 1833 1834```ts 1835let bitrate: number = 96000 1836avPlayer.setBitrate(bitrate) 1837``` 1838 1839### on('bitrateDone')<sup>9+</sup> 1840 1841on(type: 'bitrateDone', callback: Callback\<number>): void 1842 1843Subscribes to the event to check whether the bit rate is successfully set. 1844 1845**Atomic service API**: This API can be used in atomic services since API version 12. 1846 1847**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1848 1849**Parameters** 1850 1851| Name | Type | Mandatory| Description | 1852| -------- | -------- | ---- | ------------------------------------------------------------ | 1853| type | string | Yes | Event type, which is **'bitrateDone'** in this case. This event is triggered each time **setBitrate()** is called.| 1854| callback | Callback\<number> | Yes | Callback invoked when the event is triggered. It reports the effective bit rate. | 1855 1856**Example** 1857 1858```ts 1859avPlayer.on('bitrateDone', (bitrate:number) => { 1860 console.info('bitrateDone called,and bitrate value is:' + bitrate) 1861}) 1862``` 1863 1864### off('bitrateDone')<sup>9+</sup> 1865 1866off(type: 'bitrateDone', callback?: Callback\<number>): void 1867 1868Unsubscribes from the event that checks whether the bit rate is successfully set. 1869 1870**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1871 1872**Parameters** 1873 1874| Name| Type | Mandatory| Description | 1875| ------ | ------ | ---- | ------------------------------------------------------------ | 1876| type | string | Yes | Event type, which is **'bitrateDone'** in this case.| 1877| callback | Callback\<number> | No | Callback invoked when the event is triggered. It reports the effective bit rate.<br>This parameter is supported since API version 12. | 1878 1879**Example** 1880 1881```ts 1882avPlayer.off('bitrateDone') 1883``` 1884 1885### on('availableBitrates')<sup>9+</sup> 1886 1887on(type: 'availableBitrates', callback: Callback\<Array\<number>>): void 1888 1889Subscribes to available bit rates of HLS streams. This event is reported only after the AVPlayer switches to the prepared state. 1890 1891**Atomic service API**: This API can be used in atomic services since API version 12. 1892 1893**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1894 1895**Parameters** 1896 1897| Name | Type | Mandatory| Description | 1898| -------- | -------- | ---- | ------------------------------------------------------------ | 1899| type | string | Yes | Event type, which is **'availableBitrates'** in this case. This event is triggered once after the AVPlayer switches to the prepared state.| 1900| callback | Callback\<Array\<number>> | Yes | Callback invoked when the event is triggered. It returns an array that holds the available bit rates. If the array length is 0, no bit rate can be set.| 1901 1902**Example** 1903 1904```ts 1905avPlayer.on('availableBitrates', (bitrates: Array<number>) => { 1906 console.info('availableBitrates called,and availableBitrates length is:' + bitrates.length) 1907}) 1908``` 1909 1910### off('availableBitrates')<sup>9+</sup> 1911 1912off(type: 'availableBitrates', callback?: Callback\<Array\<number>>): void 1913 1914Unsubscribes from available bit rates of HLS streams. This event is reported after [prepare](#prepare9) is called. 1915 1916**Atomic service API**: This API can be used in atomic services since API version 12. 1917 1918**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1919 1920**Parameters** 1921 1922| Name| Type | Mandatory| Description | 1923| ------ | ------ | ---- | ------------------------------------------------------------ | 1924| type | string | Yes | Event type, which is **'availableBitrates'** in this case.| 1925| callback | Callback\<Array\<number>> | No | Callback invoked when the event is triggered. It returns an array that holds the available bit rates. If the array length is 0, no bit rate can be set.<br>This parameter is supported since API version 12.| 1926 1927**Example** 1928 1929```ts 1930avPlayer.off('availableBitrates') 1931``` 1932 1933 1934### on('mediaKeySystemInfoUpdate')<sup>11+</sup> 1935 1936on(type: 'mediaKeySystemInfoUpdate', callback: Callback\<Array\<drm.MediaKeySystemInfo>>): void 1937 1938Subscribes to media key system information changes. 1939 1940**Atomic service API**: This API can be used in atomic services since API version 12. 1941 1942**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1943 1944**Parameters** 1945 1946| Name | Type | Mandatory| Description | 1947| -------- | -------- | ---- | ------------------------------------------------------------ | 1948| type | string | Yes | Event type, which is **'mediaKeySystemInfoUpdate'** in this case. This event is triggered when the copyright protection information of the media asset being played changes.| 1949| callback | Callback\<Array\<drm.[MediaKeySystemInfo](../apis-drm-kit/js-apis-drm.md#mediakeysysteminfo)>> | Yes | Callback invoked when the event is triggered. It reports a **MediaKeySystemInfo** array.| 1950 1951**Example** 1952 1953```ts 1954import { drm } from '@kit.DrmKit'; 1955 1956avPlayer.on('mediaKeySystemInfoUpdate', (mediaKeySystemInfo: Array<drm.MediaKeySystemInfo>) => { 1957 for (let i = 0; i < mediaKeySystemInfo.length; i++) { 1958 console.info('mediaKeySystemInfoUpdate happened uuid: ' + mediaKeySystemInfo[i]["uuid"]); 1959 console.info('mediaKeySystemInfoUpdate happened pssh: ' + mediaKeySystemInfo[i]["pssh"]); 1960 } 1961}) 1962``` 1963 1964### off('mediaKeySystemInfoUpdate')<sup>11+</sup> 1965 1966off(type: 'mediaKeySystemInfoUpdate', callback?: Callback\<Array\<drm.MediaKeySystemInfo>>): void; 1967 1968Unsubscribes from media key system information changes. 1969 1970**Atomic service API**: This API can be used in atomic services since API version 12. 1971 1972**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1973 1974**Parameters** 1975 1976| Name| Type | Mandatory| Description | 1977| ------ | ------ | ---- | ------------------------------------------------------------ | 1978| type | string | Yes | Event type, which is **'mediaKeySystemInfoUpdate'** in this case.| 1979| callback | Callback\<Array\<drm.[MediaKeySystemInfo](../apis-drm-kit/js-apis-drm.md#mediakeysysteminfo)>> | No | Callback invoked when the event is triggered. It reports a **MediaKeySystemInfo** array. If this parameter is specified, only the specified callback is unregistered. Otherwise, all callbacks associated with the specified event will be unregistered.| 1980 1981**Example** 1982 1983```ts 1984avPlayer.off('mediaKeySystemInfoUpdate') 1985``` 1986 1987### setVolume<sup>9+</sup> 1988 1989setVolume(volume: number): void 1990 1991Sets the volume. This API can be called only when the AVPlayer is in the prepared, playing, paused, or completed state. You can check whether the setting takes effect by subscribing to the [volumeChange](#onvolumechange9) event. 1992 1993**Atomic service API**: This API can be used in atomic services since API version 12. 1994 1995**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1996 1997**Parameters** 1998 1999| Name| Type | Mandatory| Description | 2000| ------ | ------ | ---- | ------------------------------------------------------------ | 2001| volume | number | Yes | Relative volume. The value ranges from 0.00 to 1.00. The value **1.00** indicates the maximum volume (100%).| 2002 2003**Example** 2004 2005```ts 2006let volume: number = 1.0 2007avPlayer.setVolume(volume) 2008``` 2009 2010### on('volumeChange')<sup>9+</sup> 2011 2012on(type: 'volumeChange', callback: Callback\<number>): void 2013 2014Subscribes to the event to check whether the volume is successfully set. 2015 2016**Atomic service API**: This API can be used in atomic services since API version 12. 2017 2018**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2019 2020**Parameters** 2021 2022| Name | Type | Mandatory| Description | 2023| -------- | -------- | ---- | ------------------------------------------------------------ | 2024| type | string | Yes | Event type, which is **'volumeChange'** in this case. This event is triggered each time **setVolume()** is called.| 2025| callback | Callback\<number> | Yes | Callback invoked when the event is triggered. It reports the effective volume. | 2026 2027**Example** 2028 2029```ts 2030avPlayer.on('volumeChange', (vol: number) => { 2031 console.info('volumeChange called,and new volume is :' + vol) 2032}) 2033``` 2034 2035### off('volumeChange')<sup>9+</sup> 2036 2037off(type: 'volumeChange', callback?: Callback\<number>): void 2038 2039Unsubscribes from the event that checks whether the volume is successfully set. 2040 2041**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2042 2043**Parameters** 2044 2045| Name| Type | Mandatory| Description | 2046| ------ | ------ | ---- | ------------------------------------------------------------ | 2047| type | string | Yes | Event type, which is **'volumeChange'** in this case.| 2048| callback | Callback\<number> | No | Callback invoked when the event is triggered. It reports the effective volume.<br>This parameter is supported since API version 12. | 2049 2050**Example** 2051 2052```ts 2053avPlayer.off('volumeChange') 2054``` 2055 2056### on('endOfStream')<sup>9+</sup> 2057 2058on(type: 'endOfStream', callback: Callback\<void>): void 2059 2060Subscribes to the event that indicates the end of the stream being played. If **[loop](#attributes) = true** is set, the AVPlayer seeks to the beginning of the stream and plays the stream again. If **loop** is not set, the completed state is reported through the [stateChange](#onstatechange9) event. 2061 2062**Atomic service API**: This API can be used in atomic services since API version 12. 2063 2064**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2065 2066**Parameters** 2067 2068| Name | Type | Mandatory| Description | 2069| -------- | -------- | ---- | ------------------------------------------------------------ | 2070| type | string | Yes | Event type, which is **'endOfStream'** in this case. This event is triggered when the AVPlayer finishes playing the media asset.| 2071| callback | Callback\<void> | Yes | Callback invoked when the event is triggered. | 2072 2073**Example** 2074 2075```ts 2076avPlayer.on('endOfStream', () => { 2077 console.info('endOfStream called') 2078}) 2079``` 2080 2081### off('endOfStream')<sup>9+</sup> 2082 2083off(type: 'endOfStream', callback?: Callback\<void>): void 2084 2085Unsubscribes from the event that indicates the end of the stream being played. 2086 2087**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2088 2089**Parameters** 2090 2091| Name| Type | Mandatory| Description | 2092| ------ | ------ | ---- | ------------------------------------------------------------ | 2093| type | string | Yes | Event type, which is **'endOfStream'** in this case.| 2094| callback | Callback\<void> | No | Callback invoked when the event is triggered.<br>This parameter is supported since API version 12. | 2095 2096**Example** 2097 2098```ts 2099avPlayer.off('endOfStream') 2100``` 2101 2102### on('timeUpdate')<sup>9+</sup> 2103 2104on(type: 'timeUpdate', callback: Callback\<number>): void 2105 2106Subscribes to playback position changes. It is used to refresh the current position of the progress bar. By default, this event is reported every 100 ms. However, it is reported immediately upon a successful seek operation. 2107 2108The **'timeUpdate'** event is not supported in live mode. 2109 2110**Atomic service API**: This API can be used in atomic services since API version 11. 2111 2112**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2113 2114**Parameters** 2115 2116| Name | Type | Mandatory| Description | 2117| -------- | -------- | ---- | ---------------------------------------------- | 2118| type | string | Yes | Event type, which is **'timeUpdate'** in this case.| 2119| callback | Callback\<number> | Yes | Callback used to return the current time. | 2120 2121**Example** 2122 2123```ts 2124avPlayer.on('timeUpdate', (time:number) => { 2125 console.info('timeUpdate called,and new time is :' + time) 2126}) 2127``` 2128 2129### off('timeUpdate')<sup>9+</sup> 2130 2131off(type: 'timeUpdate', callback?: Callback\<number>): void 2132 2133Unsubscribes from playback position changes. 2134 2135**Atomic service API**: This API can be used in atomic services since API version 11. 2136 2137**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2138 2139**Parameters** 2140 2141| Name| Type | Mandatory| Description | 2142| ------ | ------ | ---- | -------------------------------------------------- | 2143| type | string | Yes | Event type, which is **'timeUpdate'** in this case.| 2144| callback | Callback\<number> | No | Callback used to return the current time.<br>This parameter is supported since API version 12. | 2145 2146**Example** 2147 2148```ts 2149avPlayer.off('timeUpdate') 2150``` 2151 2152### on('durationUpdate')<sup>9+</sup> 2153 2154 2155on(type: 'durationUpdate', callback: Callback\<number>): void 2156 2157Subscribes to media asset duration changes. It is used to refresh the length of the progress bar. By default, this event is reported once in the prepared state. However, it can be repeatedly reported for special streams that trigger duration changes. 2158The **'durationUpdate'** event is not supported in live mode. 2159 2160**Atomic service API**: This API can be used in atomic services since API version 12. 2161 2162**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2163 2164**Parameters** 2165 2166| Name | Type | Mandatory| Description | 2167| -------- | -------- | ---- | -------------------------------------------------- | 2168| type | string | Yes | Event type, which is **'durationUpdate'** in this case.| 2169| callback | Callback\<number> | Yes | Callback used to return the resource duration. | 2170 2171**Example** 2172 2173```ts 2174avPlayer.on('durationUpdate', (duration: number) => { 2175 console.info('durationUpdate called,new duration is :' + duration) 2176}) 2177``` 2178 2179### off('durationUpdate')<sup>9+</sup> 2180 2181off(type: 'durationUpdate', callback?: Callback\<number>): void 2182 2183Unsubscribes from media asset duration changes. 2184 2185**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2186 2187**Parameters** 2188 2189| Name| Type | Mandatory| Description | 2190| ------ | ------ | ---- | ------------------------------------------------------ | 2191| type | string | Yes | Event type, which is **'durationUpdate'** in this case.| 2192| callback | Callback\<number> | No | Callback used to return the resource duration.<br>This parameter is supported since API version 12. | 2193 2194**Example** 2195 2196```ts 2197avPlayer.off('durationUpdate') 2198``` 2199 2200### on('bufferingUpdate')<sup>9+</sup> 2201 2202on(type: 'bufferingUpdate', callback: OnBufferingUpdateHandler): void 2203 2204Subscribes to audio and video buffer changes. This subscription is supported only in network playback scenarios. 2205 2206**Atomic service API**: This API can be used in atomic services since API version 12. 2207 2208**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2209 2210**Parameters** 2211 2212| Name | Type | Mandatory| Description | 2213| -------- | -------- | ---- | ------------------------------------------------------------ | 2214| type | string | Yes | Event type, which is **'bufferingUpdate'** in this case. | 2215| callback | [OnBufferingUpdateHandler](#onbufferingupdatehandler12) | Yes | Callback invoked when the event is triggered.| 2216 2217**Example** 2218 2219```ts 2220avPlayer.on('bufferingUpdate', (infoType: media.BufferingInfoType, value: number) => { 2221 console.info('bufferingUpdate called,and infoType value is:' + infoType + ', value is :' + value) 2222}) 2223``` 2224 2225### off('bufferingUpdate')<sup>9+</sup> 2226 2227off(type: 'bufferingUpdate', callback?: OnBufferingUpdateHandler): void 2228 2229Unsubscribes from audio and video buffer changes. 2230 2231**Atomic service API**: This API can be used in atomic services since API version 12. 2232 2233**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2234 2235**Parameters** 2236 2237| Name| Type | Mandatory| Description | 2238| ------ | ------ | ---- | --------------------------------------------------------- | 2239| type | string | Yes | Event type, which is **'bufferingUpdate'** in this case.| 2240| callback | [OnBufferingUpdateHandler](#onbufferingupdatehandler12) | No | Callback invoked when the event is triggered.| 2241 2242**Example** 2243 2244```ts 2245avPlayer.off('bufferingUpdate') 2246``` 2247 2248### on('startRenderFrame')<sup>9+</sup> 2249 2250on(type: 'startRenderFrame', callback: Callback\<void>): void 2251 2252Subscribes to the event that indicates rendering starts for the first frame. This subscription is supported only in video playback scenarios. This event only means that the playback service sends the first frame to the display module. The actual rendering effect depends on the rendering performance of the display service. 2253 2254**Atomic service API**: This API can be used in atomic services since API version 12. 2255 2256**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2257 2258**Parameters** 2259 2260| Name | Type | Mandatory| Description | 2261| -------- | -------- | ---- | ------------------------------------------------------------ | 2262| type | string | Yes | Event type, which is **'startRenderFrame'** in this case.| 2263| callback | Callback\<void> | Yes | Callback invoked when the event is triggered. | 2264 2265**Example** 2266 2267```ts 2268avPlayer.on('startRenderFrame', () => { 2269 console.info('startRenderFrame called') 2270}) 2271``` 2272 2273### off('startRenderFrame')<sup>9+</sup> 2274 2275off(type: 'startRenderFrame', callback?: Callback\<void>): void 2276 2277Unsubscribes from the event that indicates rendering starts for the first frame. 2278 2279**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2280 2281**Parameters** 2282 2283| Name| Type | Mandatory| Description | 2284| ------ | ------ | ---- | ------------------------------------------------------------ | 2285| type | string | Yes | Event type, which is **'startRenderFrame'** in this case.| 2286| callback | Callback\<void> | No | Callback invoked when the event is triggered.<br>This parameter is supported since API version 12. | 2287 2288**Example** 2289 2290```ts 2291avPlayer.off('startRenderFrame') 2292``` 2293 2294### on('videoSizeChange')<sup>9+</sup> 2295 2296on(type: 'videoSizeChange', callback: OnVideoSizeChangeHandler): void 2297 2298Subscribes to video size (width and height) changes. This subscription is supported only in video playback scenarios. By default, this event is reported only once in the prepared state. However, it is also reported upon resolution changes in the case of HLS streams. 2299 2300**Atomic service API**: This API can be used in atomic services since API version 12. 2301 2302**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2303 2304**Parameters** 2305 2306| Name | Type | Mandatory| Description | 2307| -------- | -------- | ---- | ------------------------------------------------------------ | 2308| type | string | Yes | Event type, which is **'videoSizeChange'** in this case.| 2309| callback | [OnVideoSizeChangeHandler](#onvideosizechangehandler12) | Yes | Callback invoked when the event is triggered. | 2310 2311**Example** 2312 2313```ts 2314avPlayer.on('videoSizeChange', (width: number, height: number) => { 2315 console.info('videoSizeChange called,and width is:' + width + ', height is :' + height) 2316}) 2317``` 2318 2319### off('videoSizeChange')<sup>9+</sup> 2320 2321off(type: 'videoSizeChange', callback?: OnVideoSizeChangeHandler): void 2322 2323Unsubscribes from video size changes. 2324 2325**Atomic service API**: This API can be used in atomic services since API version 12. 2326 2327**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2328 2329**Parameters** 2330 2331| Name| Type | Mandatory| Description | 2332| ------ | ------ | ---- | ------------------------------------------------------------ | 2333| type | string | Yes | Event type, which is **'videoSizeChange'** in this case.| 2334| callback | [OnVideoSizeChangeHandler](#onvideosizechangehandler12) | No | Callback invoked when the event is triggered.<br>This parameter is supported since API version 12. | 2335 2336**Example** 2337 2338```ts 2339avPlayer.off('videoSizeChange') 2340``` 2341 2342### on('audioInterrupt')<sup>9+</sup> 2343 2344on(type: 'audioInterrupt', callback: Callback\<audio.InterruptEvent>): void 2345 2346Subscribes to the audio interruption event. When multiple audio and video assets are played at the same time, this event is triggered based on the audio interruption mode [audio.InterruptMode](../apis-audio-kit/js-apis-audio.md#interruptmode9). The application needs to perform corresponding processing based on different audio interruption events. For details, see [Handling Audio Interruption Events](../../media/audio/audio-playback-concurrency.md). 2347 2348**Atomic service API**: This API can be used in atomic services since API version 12. 2349 2350**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2351 2352**Parameters** 2353 2354| Name | Type | Mandatory| Description | 2355| -------- | ------------------------------------------------------------ | ---- | -------------------------------------------------------- | 2356| type | string | Yes | Event type, which is **'audioInterrupt'** in this case.| 2357| callback | Callback\<[audio.InterruptEvent](../apis-audio-kit/js-apis-audio.md#interruptevent9)> | Yes | Callback invoked when the event is triggered. | 2358 2359**Example** 2360 2361```ts 2362import { audio } from '@kit.AudioKit'; 2363 2364avPlayer.on('audioInterrupt', (info: audio.InterruptEvent) => { 2365 console.info('audioInterrupt called,and InterruptEvent info is:' + info) 2366}) 2367``` 2368 2369### off('audioInterrupt')<sup>9+</sup> 2370 2371off(type: 'audioInterrupt', callback?: Callback<audio.InterruptEvent>): void 2372 2373Unsubscribes from the audio interruption event. 2374 2375**Atomic service API**: This API can be used in atomic services since API version 12. 2376 2377**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2378 2379**Parameters** 2380 2381| Name| Type | Mandatory| Description | 2382| ------ | ------ | ---- | ------------------------------------------------------------ | 2383| type | string | Yes | Event type, which is **'audioInterrupt'** in this case.| 2384| callback | Callback\<[audio.InterruptEvent](../apis-audio-kit/js-apis-audio.md#interruptevent9)> | No | Callback invoked when the event is triggered.<br>This parameter is supported since API version 12. | 2385 2386**Example** 2387 2388```ts 2389avPlayer.off('audioInterrupt') 2390``` 2391 2392### on('audioOutputDeviceChangeWithInfo')<sup>11+</sup> 2393 2394on(type: 'audioOutputDeviceChangeWithInfo', callback: Callback\<audio.AudioStreamDeviceChangeInfo>): void 2395 2396Subscribes to audio stream output device changes and reasons. This API uses an asynchronous callback to return the result. 2397 2398When subscribing to this event, you are advised to implement the player behavior when the device is connected or disconnected by referring to [Responding to Audio Output Device Changes](../../media/audio/audio-output-device-change.md). 2399 2400**Atomic service API**: This API can be used in atomic services since API version 12. 2401 2402**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2403 2404**Parameters** 2405 2406| Name | Type | Mandatory| Description | 2407| :------- | :------------------------- | :--- | :------------------------------------------ | 2408| type | string | Yes | Event type, which is **'outputDeviceChangeWithInfo'** in this case. The event is triggered when the output device is changed.| 2409| callback | Callback\<[audio.AudioStreamDeviceChangeInfo](../apis-audio-kit/js-apis-audio.md#audiostreamdevicechangeinfo11)> | Yes | Callback used to return the output device descriptor of the current audio stream and the change reason.| 2410 2411**Error codes** 2412 2413| ID| Error Message | 2414| -------- | ------------------------------------------ | 2415| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 2416 2417**Example** 2418 2419```ts 2420import { audio } from '@kit.AudioKit'; 2421 2422avPlayer.on('audioOutputDeviceChangeWithInfo', (data: audio.AudioStreamDeviceChangeInfo) => { 2423 console.info(`${JSON.stringify(data)}`); 2424}); 2425``` 2426 2427### off('audioOutputDeviceChangeWithInfo')<sup>11+</sup> 2428 2429off(type: 'audioOutputDeviceChangeWithInfo', callback?: Callback\<audio.AudioStreamDeviceChangeInfo>): void 2430 2431Unsubscribes from audio stream output device changes and reasons. This API uses an asynchronous callback to return the result. 2432 2433**Atomic service API**: This API can be used in atomic services since API version 12. 2434 2435**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2436 2437**Parameters** 2438 2439| Name | Type | Mandatory| Description | 2440| :------- | :------------------------- | :--- | :------------------------------------------ | 2441| type | string | Yes | Event type, which is **'outputDeviceChange'** in this case. The event is triggered when the audio output device is changed.| 2442| callback | Callback\<[audio.AudioStreamDeviceChangeInfo](../apis-audio-kit/js-apis-audio.md#audiostreamdevicechangeinfo11)> | No | Callback used to return the output device descriptor of the current audio stream and the change reason.| 2443 2444**Error codes** 2445 2446| ID| Error Message | 2447| -------- | ------------------------------------------ | 2448| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 2449 2450**Example** 2451 2452```ts 2453avPlayer.off('audioOutputDeviceChangeWithInfo'); 2454``` 2455 2456### addSubtitleFromFd<sup>12+</sup> 2457 2458addSubtitleFromFd(fd: number, offset?: number, length?: number): Promise\<void> 2459 2460Adds an external subtitle to a video based on the FD. Currently, the external subtitle must be set after **fdSrc** of the video resource is set in an **AVPlayer** instance. This API uses a promise to return the result. 2461 2462**Atomic service API**: This API can be used in atomic services since API version 12. 2463 2464**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2465 2466**Parameters** 2467 2468| Name| Type | Mandatory| Description | 2469| ------ | ---------------------- | ---- | ------------------------------------------------------------ | 2470| fd | number | Yes | Resource handle, which is obtained by calling [resourceManager.getRawFd](../apis-localization-kit/js-apis-resource-manager.md#getrawfd9).| 2471| offset | number | No | Resource offset, which needs to be entered based on the preset asset information. An invalid value causes a failure to parse subtitle assets.| 2472| length | number | No | Resource length, which needs to be entered based on the preset asset information. The default value is the remaining bytes from the offset in the file. An invalid value causes a failure to parse subtitle assets.| 2473 2474**Return value** 2475 2476| Type | Description | 2477| -------------- | ------------------------------------------ | 2478| Promise\<void> | Promise that returns no value.| 2479 2480**Error codes** 2481 2482| ID| Error Message | 2483| -------- | ------------------------------------------ | 2484| 401 | The parameter check failed. Return by promise. | 2485| 5400102 | Operation not allowed. Return by promise. | 2486 2487**Example** 2488 2489```ts 2490import { media } from '@kit.MediaKit' 2491 2492let context = getContext(this) as common.UIAbilityContext 2493let fileDescriptor = await context.resourceManager.getRawFd('xxx.srt') 2494 2495avPlayer.addSubtitleFromFd(fileDescriptor.fd, fileDescriptor.offset, fileDescriptor.length) 2496``` 2497 2498### addSubtitleFromUrl<sup>12+</sup> 2499 2500addSubtitleFromUrl(url: string): Promise\<void> 2501 2502Adds an external subtitle to a video based on the URL. Currently, the external subtitle must be set after **fdSrc** of the video resource is set in an **AVPlayer** instance. This API uses a promise to return the result. 2503 2504**Atomic service API**: This API can be used in atomic services since API version 12. 2505 2506**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2507 2508**Parameters** 2509 2510| Name| Type | Mandatory| Description | 2511| ------ | ------ | ---- | ------------------------------------------------------------ | 2512| url | string | Yes | Address of the external subtitle file.| 2513 2514**Return value** 2515 2516| Type | Description | 2517| -------------- | ------------------------------------------ | 2518| Promise\<void> | Promise that returns no value.| 2519 2520**Error codes** 2521 2522| ID| Error Message | 2523| -------- | ------------------------------------------ | 2524| 401 | The parameter check failed. Return by promise. | 2525| 5400102 | Operation not allowed. Return by promise. | 2526 2527**Example** 2528 2529```ts 2530import { media } from '@kit.MediaKit' 2531 2532let fdUrl:string = 'http://xxx.xxx.xxx/xx/index.srt' 2533 2534let avPlayer: media.AVPlayer = await media.createAVPlayer() 2535avPlayer.addSubtitleFromUrl(fdUrl) 2536``` 2537 2538### on('subtitleUpdate')<sup>12+</sup> 2539 2540on(type: 'subtitleUpdate', callback: Callback\<SubtitleInfo>): void 2541 2542Subscribes to subtitle update events. When external subtitles exist, the system notifies the application through the subscribed-to callback. An application can subscribe to only one subtitle update event. When the application initiates multiple subscriptions to this event, the last subscription prevails. 2543 2544**Atomic service API**: This API can be used in atomic services since API version 12. 2545 2546**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2547 2548**Parameters** 2549 2550| Name | Type | Mandatory| Description | 2551| -------- | -------- | ---- | ------------------------------------------------------------ | 2552| type | string | Yes | Event type, which is **'subtitleUpdate'** in this case. The event is triggered when the external subtitle is updated.| 2553| callback | function | Yes | Callback invoked when the subtitle is updated.| 2554 2555**Example** 2556 2557```ts 2558avPlayer.on('subtitleUpdate', async (info: media.SubtitleInfo) => { 2559 if (info) { 2560 let text = (!info.text) ? '' : info.text 2561 let startTime = (!info.startTime) ? 0 : info.startTime 2562 let duration = (!info.duration) ? 0 : info.duration 2563 console.info('subtitleUpdate info: text=' + text + ' startTime=' + startTime +' duration=' + duration) 2564 } else { 2565 console.info('subtitleUpdate info is null') 2566 } 2567}) 2568``` 2569 2570### off('subtitleUpdate')<sup>12+</sup> 2571 2572off(type: 'subtitleUpdate', callback?: Callback\<SubtitleInfo>): void 2573 2574Unsubscribes from subtitle update events. 2575 2576**Atomic service API**: This API can be used in atomic services since API version 12. 2577 2578**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2579 2580**Parameters** 2581 2582| Name | Type | Mandatory| Description | 2583| -------- | -------- | ---- | ------------------------------------------------------------ | 2584| type | string | Yes | Event type, which is **'subtitleUpdate'** in this case. The event is triggered when the external subtitle is updated.| 2585| callback | function | No | Callback that has been registered to listen for subtitle update events.| 2586 2587**Example** 2588 2589```ts 2590avPlayer.off('subtitleUpdate') 2591``` 2592 2593### on('trackChange')<sup>12+</sup> 2594 2595on(type: 'trackChange', callback: OnTrackChangeHandler): void 2596 2597Subscribes to track change events. When the track changes, the system notifies the application through the subscribed-to callback. An application can subscribe to only one track change event. When the application initiates multiple subscriptions to this event, the last subscription prevails. 2598 2599**Atomic service API**: This API can be used in atomic services since API version 12. 2600 2601**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2602 2603**Parameters** 2604 2605| Name | Type | Mandatory| Description | 2606| -------- | -------- | ---- | ------------------------------------------------------------ | 2607| type | string | Yes | Event type, which is **'trackChange'** in this case. The event is triggered when the track changes.| 2608| callback | [OnTrackChangeHandler](#ontrackchangehandler12) | Yes | Callback invoked when the event is triggered.| 2609 2610**Example** 2611 2612```ts 2613avPlayer.on('trackChange', (index: number, isSelect: boolean) => { 2614 console.info('trackChange info: index=' + index + ' isSelect=' + isSelect) 2615}) 2616``` 2617 2618### off('trackChange')<sup>12+</sup> 2619 2620off(type: 'trackChange', callback?: OnTrackChangeHandler): void 2621 2622Unsubscribes from track change events. 2623 2624**Atomic service API**: This API can be used in atomic services since API version 12. 2625 2626**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2627 2628**Parameters** 2629 2630| Name | Type | Mandatory| Description | 2631| -------- | -------- | ---- | ------------------------------------------------------------ | 2632| type | string | Yes | Event type, which is **'trackChange'** in this case. The event is triggered when the track changes.| 2633| callback | [OnTrackChangeHandler](#ontrackchangehandler12) | No | Callback that has been registered to listen for track changes.| 2634 2635**Example** 2636 2637```ts 2638avPlayer.off('trackChange') 2639``` 2640 2641### on('trackInfoUpdate')<sup>12+</sup> 2642 2643on(type: 'trackInfoUpdate', callback: Callback\<Array\<MediaDescription>>): void 2644 2645Subscribes to track information update events. When the track information is updated, the system notifies the application through the subscribed-to callback. An application can subscribe to only one track change event. When the application initiates multiple subscriptions to this event, the last subscription prevails. 2646 2647**Atomic service API**: This API can be used in atomic services since API version 12. 2648 2649**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2650 2651**Parameters** 2652 2653| Name | Type | Mandatory| Description | 2654| -------- | -------- | ---- | ------------------------------------------------------------ | 2655| type | string | Yes | Event type, which is **'trackInfoUpdate'** in this case. The event is triggered when the track information is updated.| 2656| callback | Callback\<Array\<[MediaDescription](#mediadescription8)>> | Yes | Callback invoked when the event is triggered.| 2657 2658**Example** 2659 2660```ts 2661avPlayer.on('trackInfoUpdate', (info: Array<media.MediaDescription>) => { 2662 if (info) { 2663 for (let i = 0; i < info.length; i++) { 2664 let propertyIndex: Object = info[i][media.MediaDescriptionKey.MD_KEY_TRACK_INDEX]; 2665 let propertyType: Object = info[i][media.MediaDescriptionKey.MD_KEY_TRACK_TYPE]; 2666 console.info('track info: index=' + propertyIndex + ' tracktype=' + propertyType) 2667 } 2668 } else { 2669 console.info('track info is null') 2670 } 2671}) 2672``` 2673 2674### off('trackInfoUpdate')<sup>12+</sup> 2675 2676off(type: 'trackInfoUpdate', callback?: Callback\<Array\<MediaDescription>>): void 2677 2678Unsubscribes from track information update events. 2679 2680**Atomic service API**: This API can be used in atomic services since API version 12. 2681 2682**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2683 2684**Parameters** 2685 2686| Name | Type | Mandatory| Description | 2687| -------- | -------- | ---- | ------------------------------------------------------------ | 2688| type | string | Yes | Event type, which is **'trackInfoUpdate'** in this case. The event is triggered when the track information is updated.| 2689| callback | Callback\<Array\<[MediaDescription](#mediadescription8)>> | No | Callback that has been registered to listen for track information updates.| 2690 2691**Example** 2692 2693```ts 2694avPlayer.off('trackInfoUpdate') 2695``` 2696 2697### on('amplitudeUpdate')<sup>13+</sup> 2698 2699on(type: 'amplitudeUpdate', callback: Callback\<Array\<number>>): void 2700 2701Subscribes to update events of the maximum audio level value, which is periodically reported when audio resources are played. 2702 2703**Atomic service API**: This API can be used in atomic services since API version 13. 2704 2705**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2706 2707**Parameters** 2708 2709| Name | Type | Mandatory| Description | 2710| -------- | -------- | ---- | ------------------------------------------------------------ | 2711| type | string | Yes | Event type, which is **'amplitudeUpdate'** in this case. The event is triggered when the amplitude changes.| 2712| callback | Callback\<Array\<number>> | Yes | Callback invoked when the event is triggered.| 2713 2714**Example** 2715 2716```ts 2717avPlayer.on('amplitudeUpdate', (value: Array<number>) => { 2718 console.info('amplitudeUpdate called,and amplitudeUpdate = ${value}') 2719}) 2720``` 2721 2722### off('amplitudeUpdate')<sup>13+</sup> 2723 2724off(type: 'amplitudeUpdate', callback?: Callback\<Array\<number>>): void 2725 2726Unsubscribes from update events of the maximum amplitude. 2727 2728**Atomic service API**: This API can be used in atomic services since API version 13. 2729 2730**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2731 2732**Parameters** 2733 2734| Name| Type | Mandatory| Description | 2735| ------ | ------ | ---- | ------------------------------------------------------------ | 2736| type | string | Yes | Event type, which is **'amplitudeUpdate'** in this case. The event is triggered when the amplitude changes.| 2737| callback | Callback\<Array\<number>> | No | Callback that has been registered to listen for amplitude updates.| 2738 2739**Example** 2740 2741```ts 2742avPlayer.off('amplitudeUpdate') 2743``` 2744 2745## AVPlayerState<sup>9+</sup> 2746 2747type AVPlayerState = 'idle' | 'initialized' | 'prepared' | 'playing' | 'paused' | 'completed' | 'stopped' | 'released' | 'error' 2748 2749Enumerates the states of the [AVPlayer](#avplayer9). Your application can proactively obtain the AVPlayer state through the **state** attribute or obtain the reported AVPlayer state by subscribing to the [stateChange](#onstatechange9) event. For details about the rules for state transition, see [Audio Playback](../../media/media/using-avplayer-for-playback.md). 2750 2751**Atomic service API**: This API can be used in atomic services since API version 11. 2752 2753**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2754 2755| Type | Description | 2756| :-----------------------------: | :----------------------------------------------------------- | 2757| 'idle' | The AVPlayer enters this state after [createAVPlayer()](#mediacreateavplayer9) or [reset()](#reset9) is called.<br>In case [createAVPlayer()](#mediacreateavplayer9) is used, all attributes are set to their default values.<br>In case [reset()](#reset9) is called, the **url<sup>9+</sup>**, **fdSrc<sup>9+</sup>**, or **dataSrc<sup>10+</sup>** attribute and the **loop** attribute are reset, and other attributes are retained.| 2758| 'initialized' | The AVPlayer enters this state after **url<sup>9+</sup>** or **fdSrc<sup>9+</sup>** attribute is set in the idle state. In this case, you can configure static attributes such as the window and audio.| 2759| 'prepared' | The AVPlayer enters this state when [prepare()](#prepare9) is called in the initialized state. In this case, the playback engine has prepared the resources.| 2760| 'playing' | The AVPlayer enters this state when [play()](#play9) is called in the prepared, paused, or completed state.| 2761| 'paused' | The AVPlayer enters this state when **pause()** is called in the playing state.| 2762| 'completed' | The AVPlayer enters this state when a media asset finishes playing and loop playback is not set (no **loop = true**). In this case, if [play()](#play9) is called, the AVPlayer enters the playing state and replays the media asset; if [stop()](#stop9) is called, the AVPlayer enters the stopped state.| 2763| 'stopped' | The AVPlayer enters this state when [stop()](#stop9) is called in the prepared, playing, paused, or completed state. In this case, the playback engine retains the attributes but releases the memory resources. You can call [prepare()](#prepare9) to prepare the resources again, call [reset()](#reset9) to reset the attributes, or call [release()](#release9) to destroy the playback engine.| 2764| 'released' | The AVPlayer enters this state when [release()](#release9) is called. The playback engine associated with the **AVPlayer** instance is destroyed, and the playback process ends. This is the final state.| 2765| 'error' | The AVPlayer enters this state when an irreversible error occurs in the playback engine. You can call [reset()](#reset9) to reset the attributes or call [release()](#release9) to destroy the playback engine. For details about the error codes, see [Media Error Codes](errorcode-media.md).<br>**NOTE** Relationship between the error state and the [on('error')](#onerror9) event<br>1. When the AVPlayer enters the error state, the **on('error')** event is triggered. You can obtain the detailed error information through this event.<br>2. When the AVPlayer enters the error state, the playback service stops. This requires the client to design a fault tolerance mechanism to call [reset()](#reset9) or [release()](#release9).<br>3. The client receives **on('error')** event but the AVPlayer does not enter the error state. This situation occurs due to either of the following reasons:<br>Cause 1: The client calls an API in an incorrect state or passes in an incorrect parameter, and the AVPlayer intercepts the call. If this is the case, the client must correct its code logic.<br>Cause 2: A stream error is detected during playback. As a result, the container and decoding are abnormal for a short period of time, but continuous playback and playback control operations are not affected. If this is the case, the client does not need to design a fault tolerance mechanism.| 2766 2767## OnTrackChangeHandler<sup>12+</sup> 2768 2769type OnTrackChangeHandler = (index: number, isSelected: boolean) => void 2770 2771Describes the callback invoked for the track change event. 2772 2773**Atomic service API**: This API can be used in atomic services since API version 12. 2774 2775**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2776 2777| Name | Type | Mandatory| Description | 2778| ------ | ------ | ------ | ---------------------------------------------------------- | 2779| index | number | Yes| Index of a track. | 2780| isSelected | boolean | Yes| Status of the track, that is, whether the track is selected.| 2781 2782## OnAVPlayerStateChangeHandle<sup>12+</sup> 2783 2784type OnAVPlayerStateChangeHandle = (state: AVPlayerState, reason: StateChangeReason) => void 2785 2786Describes the callback invoked for the AVPlayer state change event. 2787 2788**Atomic service API**: This API can be used in atomic services since API version 12. 2789 2790**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2791 2792| Name | Type | Mandatory| Description | 2793| ------ | ------ | ------ | ---------------------------------------------------------- | 2794| state | [AVPlayerState](#avplayerstate9) | Yes| State of the AVPlayer. | 2795| reason | [StateChangeReason](#statechangereason9) | Yes| Reason for the state change.| 2796 2797## OnBufferingUpdateHandler<sup>12+</sup> 2798 2799type OnBufferingUpdateHandler = (infoType: BufferingInfoType, value: number) => void 2800 2801Describes the callback invoked for the buffering update event. 2802 2803**Atomic service API**: This API can be used in atomic services since API version 12. 2804 2805**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2806 2807| Name | Type | Mandatory| Description | 2808| ------ | ------ | ------ | ------------------------------------------------------------ | 2809| infoType | [BufferingInfoType](#bufferinginfotype8) | Yes| Buffering information type. | 2810| value | number | Yes| The value is fixed at **0**.| 2811 2812## OnVideoSizeChangeHandler<sup>12+</sup> 2813 2814type OnVideoSizeChangeHandler = (width: number, height: number) => void 2815 2816Describes the callback invoked for the video size change event. 2817 2818**Atomic service API**: This API can be used in atomic services since API version 12. 2819 2820**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2821 2822| Name | Type | Mandatory| Description | 2823| ------ | ------ | ------ | ------------------------------------------------------------ | 2824| width | number | Yes| Video width. | 2825| height | number | Yes| Video height.| 2826 2827## AVFileDescriptor<sup>9+</sup> 2828 2829Describes an audio and video file asset. It is used to specify a particular asset for playback based on its offset and length within a file. 2830 2831**Atomic service API**: This API can be used in atomic services since API version 11. 2832 2833**System capability**: SystemCapability.Multimedia.Media.Core 2834 2835| Name | Type | Mandatory| Description | 2836| ------ | ------ | ---- | ------------------------------------------------------------ | 2837| fd | number | Yes | Resource handle, which is obtained by calling [resourceManager.getRawFd](../apis-localization-kit/js-apis-resource-manager.md#getrawfd9) or [fs.open](../apis-core-file-kit/js-apis-file-fs.md#fsopen). | 2838| offset | number | No | Resource offset, which needs to be entered based on the preset asset information. The default value is **0**. An invalid value causes a failure to parse audio and video assets.| 2839| length | number | No | Resource length, which needs to be entered based on the preset asset information. The default value is the remaining bytes from the offset in the file. An invalid value causes a failure to parse audio and video assets.| 2840 2841## AVDataSrcDescriptor<sup>10+</sup> 2842 2843Defines the descriptor of an audio and video file, which is used in DataSource playback mode.<br>Use scenario: An application can create a playback instance and start playback before it finishes downloading the audio and video resources. 2844 2845**Atomic service API**: This API can be used in atomic services since API version 11. 2846 2847**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2848 2849| Name | Type | Mandatory| Description | 2850| ------ | ------ | ---- | ------------------------------------------------------------ | 2851| fileSize | number | Yes | Size of the file to play, in bytes. The value **-1** indicates that the size is unknown. If **fileSize** is set to **-1**, the playback mode is similar to the live mode. In this mode, the **seek** and **setSpeed** operations cannot be performed, and the **loop** attribute cannot be set, indicating that loop playback is unavailable.| 2852| callback | (buffer: ArrayBuffer, length: number, pos?: number) => number | Yes | Callback used to fill in data.<br>- Function: callback: (buffer: ArrayBuffer, length: number, pos?:number) => number;<br>- **buffer**: memory to be filled. The value is of the ArrayBuffer type. This parameter is mandatory.<br>- **length**: maximum length of the memory to be filled. The value is of the number type. This parameter is mandatory.<br>- **pos**: position of the data to be filled in the file. The value is of the number type. This parameter is optional. When **fileSize** is set to **-1**, this parameter cannot be used.<br>- Return value: length of the data to be filled, which is of the number type.| 2853 2854## SubtitleInfo<sup>12+</sup> 2855 2856Describes the external subtitle information. When a subtitle update event is subscribed to, the information about the external subtitle is returned through a callback. 2857 2858**Atomic service API**: This API can be used in atomic services since API version 12. 2859 2860**System capability**: SystemCapability.Multimedia.Media.Core 2861 2862| Name | Type | Mandatory| Description | 2863| ------ | ------ | ---- | ------------------------------------------------------------ | 2864| text | string | No | Text information of the subtitle.| 2865| startTime | number | No | Start time for displaying the subtitle, in milliseconds.| 2866| duration | number | No| Duration for displaying the subtitle, in milliseconds.| 2867 2868## SeekMode<sup>8+</sup> 2869 2870Enumerates the video playback seek modes, which can be passed in the **seek** API. 2871 2872**System capability**: SystemCapability.Multimedia.Media.Core 2873 2874| Name | Value | Description | 2875| -------------- | ---- | ------------------------------------------------------------ | 2876| SEEK_NEXT_SYNC | 0 | Seeks to the next key frame at the specified position. You are advised to use this value for the rewind operation.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2877| SEEK_PREV_SYNC | 1 | Seeks to the previous key frame at the specified position. You are advised to use this value for the fast-forward operation.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2878| SEEK_CLOSEST<sup>12+</sup> | 2 | Seeks to the frame closest to the specified position. You are advised to use this value for accurate seek.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 2879 2880## SwitchMode<sup>12+</sup> 2881 2882Enumerates the track switching modes for video playback. The mode can be passed in to **selectTrack**. Currently, this enum is valid only for DASH video tracks. 2883 2884**System capability**: SystemCapability.Multimedia.Media.Core 2885 2886| Name | Value | Description | 2887| -------------- | ---- | ------------------------------------------------------------ | 2888| SMOOTH | 0 | Smooth playback is ensured after the switching. This mode has a delay, that is, the switching does not take effect immediately.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 2889| SEGMENT | 1 | The playback starts from the start position of the current segment after the switching. In this mode, the switching takes effect immediately and repeated playback may occur.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 2890| CLOSEST | 2 | The playback starts from the frame closest to the current playback time. In this mode, the switching takes effect immediately, and the playback is suspended for 3s to 5s and then resumed.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 2891 2892## PlaybackSpeed<sup>8+</sup> 2893 2894Enumerates the video playback speeds, which can be passed in the **setSpeed** API. 2895 2896**Atomic service API**: This API can be used in atomic services since API version 12. 2897 2898**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 2899 2900| Name | Value | Description | 2901| -------------------- | ---- | ------------------------------ | 2902| SPEED_FORWARD_0_75_X | 0 | Plays the video at 0.75 times the normal speed.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 2903| SPEED_FORWARD_1_00_X | 1 | Plays the video at the normal speed.<br>**Atomic service API**: This API can be used in atomic services since API version 12. | 2904| SPEED_FORWARD_1_25_X | 2 | Plays the video at 1.25 times the normal speed.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 2905| SPEED_FORWARD_1_75_X | 3 | Plays the video at 1.75 times the normal speed.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 2906| SPEED_FORWARD_2_00_X | 4 | Plays the video at 2.00 times the normal speed.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 2907| SPEED_FORWARD_0_50_X<sup>12+</sup> | 5 | Plays the video at 0.50 times the normal speed.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 2908| SPEED_FORWARD_1_50_X<sup>12+</sup> | 6 | Plays the video at 1.50 times the normal speed.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 2909| SPEED_FORWARD_0_25_X<sup>12+</sup> | 8 | Plays the video at 0.25 times the normal speed.| 2910| SPEED_FORWARD_0_125_X<sup>12+</sup> | 9 | Plays the video at 0.125 times the normal speed.| 2911 2912## VideoScaleType<sup>9+</sup> 2913 2914Enumerates the video scale modes. 2915 2916**Atomic service API**: This API can be used in atomic services since API version 12. 2917 2918**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 2919 2920| Name | Value | Description | 2921| ------------------------- | ---- | ------------------------------------------------ | 2922| VIDEO_SCALE_TYPE_FIT | 0 | Default mode. The video will be stretched to fit the window. | 2923| VIDEO_SCALE_TYPE_FIT_CROP | 1 | The video will be stretched to fit the window, without changing its aspect ratio. The content may be cropped.| 2924 2925## MediaDescription<sup>8+</sup> 2926 2927Defines media information in key-value mode. 2928 2929**Atomic service API**: This API can be used in atomic services since API version 11. 2930 2931**System capability**: SystemCapability.Multimedia.Media.Core 2932 2933| Name | Type | Mandatory| Description | 2934| ------------- | ------ | ---- | ------------------------------------------------------------ | 2935| [key: string] | Object | Yes | For details about the key range supported and the object type and range of each key, see [MediaDescriptionKey](#mediadescriptionkey8).| 2936 2937**Example** 2938 2939```ts 2940import { BusinessError } from '@kit.BasicServicesKit'; 2941import { media } from '@kit.MediaKit'; 2942 2943function printfItemDescription(obj: media.MediaDescription, key: string) { 2944 let property: Object = obj[key]; 2945 console.info('audio key is ' + key); // Specify a key. For details about the keys, see [MediaDescriptionKey]. 2946 console.info('audio value is ' + property); // Obtain the value of the key. The value can be any type. For details about the types, see [MediaDescriptionKey]. 2947} 2948 2949let avPlayer: media.AVPlayer | undefined = undefined; 2950media.createAVPlayer((err: BusinessError, player: media.AVPlayer) => { 2951 if(player != null) { 2952 avPlayer = player; 2953 console.info(`Succeeded in creating AVPlayer`); 2954 avPlayer.getTrackDescription((error: BusinessError, arrList: Array<media.MediaDescription>) => { 2955 if (arrList != null) { 2956 for (let i = 0; i < arrList.length; i++) { 2957 printfItemDescription(arrList[i], media.MediaDescriptionKey.MD_KEY_TRACK_TYPE); // Print the MD_KEY_TRACK_TYPE value of each track. 2958 } 2959 } else { 2960 console.error(`Failed to get TrackDescription, error:${error}`); 2961 } 2962 }); 2963 } else { 2964 console.error(`Failed to create AVPlayer, error message:${err.message}`); 2965 } 2966}); 2967``` 2968 2969## PlaybackInfo<sup>12+</sup> 2970 2971Defines the playback information in key-value pairs. 2972 2973**System capability**: SystemCapability.Multimedia.Media.Core 2974 2975| Name | Type | Mandatory| Description | 2976| ------------- | ------ | ---- | ------------------------------------------------------------ | 2977| [key: string] | Object | Yes | For details about the key range supported and the object type and range of each key, see [PlaybackInfoKey](#playbackinfokey12).| 2978 2979**Example** 2980 2981```ts 2982import { BusinessError } from '@kit.BasicServicesKit'; 2983import { media } from '@kit.MediaKit'; 2984 2985function printfPlaybackInfo(obj: media.PlaybackInfo, key: string) { 2986 let property: Object = obj[key]; 2987 console.info('key is ' + key); // // Specify a key. For details about the keys, see [PlaybackInfoKey]. 2988 console.info('value is ' + property); // Obtain the value of the key. The value can be any type. For details about the types, see [PlaybackInfoKey]. 2989} 2990 2991let avPlayer: media.AVPlayer | undefined = undefined; 2992let playbackInfo: media.PlaybackInfo | undefined = undefined; 2993media.createAVPlayer(async (err: BusinessError, player: media.AVPlayer) => { 2994 if (player != null) { 2995 avPlayer = player; 2996 console.info(`Succeeded in creating AVPlayer`); 2997 if (avPlayer) { 2998 try { 2999 playbackInfo = await avPlayer.getPlaybackInfo(); 3000 console.info(`AVPlayer getPlaybackInfo = ${JSON.stringify(playbackInfo)}`); // Print PlaybackInfo. 3001 printfPlaybackInfo(playbackInfo, media.PlaybackInfoKey.SERVER_IP_ADDRESS); // Print the IP address. 3002 } catch (error) { 3003 console.error(`error = ${error}`); 3004 } 3005 } 3006 } else { 3007 console.error(`Failed to create AVPlayer, error message:${err.message}`); 3008 } 3009}); 3010``` 3011 3012## AVRecorder<sup>9+</sup> 3013 3014A recording management class that provides APIs to record media assets. Before calling any API in **AVRecorder**, you must use [createAVRecorder()](#mediacreateavrecorder9) to create an **AVRecorder** instance. 3015 3016For details about the audio and video recording demo, see [Audio Recording](../../media/media/using-avrecorder-for-recording.md) and [Video Recording](../../media/media/video-recording.md). 3017 3018> **NOTE** 3019> 3020> To use the camera to record videos, the camera module is required. For details about how to use the APIs provided by the camera module, see [Camera Management](../apis-camera-kit/js-apis-camera.md). 3021 3022### Attributes 3023 3024**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3025 3026| Name | Type | Read-Only| Optional| Description | 3027| ------- | ------------------------------------ | ---- | ---- | ------------------ | 3028| state9+ | [AVRecorderState](#avrecorderstate9) | Yes | No | AVRecorder state.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 3029 3030### prepare<sup>9+</sup> 3031 3032prepare(config: AVRecorderConfig, callback: AsyncCallback\<void>): void 3033 3034Sets audio and video recording parameters. This API uses an asynchronous callback to return the result. 3035 3036**Required permissions:** ohos.permission.MICROPHONE 3037 3038This permission is required only if audio recording is involved. 3039 3040To use the camera to record videos, the camera module is required. For details about how to use the APIs provided by the camera module, see [Camera Management](../apis-camera-kit/js-apis-camera.md). 3041 3042**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3043 3044**Parameters** 3045 3046| Name | Type | Mandatory| Description | 3047| -------- | -------------------------------------- | ---- | ------------------------------------- | 3048| config | [AVRecorderConfig](#avrecorderconfig9) | Yes | Audio and video recording parameters to set. | 3049| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 3050 3051**Error codes** 3052 3053For details about the error codes, see [Media Error Codes](errorcode-media.md). 3054 3055| ID| Error Message | 3056| -------- | --------------------------------------- | 3057| 201 | Permission denied. Return by callback. | 3058| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 3059| 5400102 | Operate not permit. Return by callback. | 3060| 5400105 | Service died. Return by callback. | 3061 3062**Example** 3063 3064```ts 3065import { BusinessError } from '@kit.BasicServicesKit'; 3066 3067// Configure the parameters based on those supported by the hardware device. 3068let avRecorderProfile: media.AVRecorderProfile = { 3069 audioBitrate : 48000, 3070 audioChannels : 2, 3071 audioCodec : media.CodecMimeType.AUDIO_AAC, 3072 audioSampleRate : 48000, 3073 fileFormat : media.ContainerFormatType.CFT_MPEG_4, 3074 videoBitrate : 2000000, 3075 videoCodec : media.CodecMimeType.VIDEO_AVC, 3076 videoFrameWidth : 640, 3077 videoFrameHeight : 480, 3078 videoFrameRate : 30 3079} 3080let avRecorderConfig: media.AVRecorderConfig = { 3081 audioSourceType : media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC, 3082 videoSourceType : media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV, 3083 profile : avRecorderProfile, 3084 url : 'fd://', // Before passing in an FD to this parameter, the file must be created by the caller and granted with the read and write permissions. Example value: fd://45. 3085 rotation: 0, // The value can be 0, 90, 180, or 270. If any other value is used, prepare() reports an error. 3086 location : { latitude : 30, longitude : 130 } 3087} 3088 3089avRecorder.prepare(avRecorderConfig, (err: BusinessError) => { 3090 if (err) { 3091 console.error('Failed to prepare and error is ' + err.message); 3092 } else { 3093 console.info('Succeeded in preparing'); 3094 } 3095}) 3096``` 3097 3098### prepare<sup>9+</sup> 3099 3100prepare(config: AVRecorderConfig): Promise\<void> 3101 3102Sets audio and video recording parameters. This API uses a promise to return the result. 3103 3104**Required permissions:** ohos.permission.MICROPHONE 3105 3106This permission is required only if audio recording is involved. 3107 3108To use the camera to record videos, the camera module is required. For details about how to use the APIs provided by the camera module, see [Camera Management](../apis-camera-kit/js-apis-camera.md). 3109 3110**Atomic service API**: This API can be used in atomic services since API version 12. 3111 3112**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3113 3114**Parameters** 3115 3116| Name| Type | Mandatory| Description | 3117| ------ | -------------------------------------- | ---- | -------------------------- | 3118| config | [AVRecorderConfig](#avrecorderconfig9) | Yes | Audio and video recording parameters to set.| 3119 3120**Return value** 3121 3122| Type | Description | 3123| -------------- | ------------------------------------------ | 3124| Promise\<void> | Promise that returns no value.| 3125 3126**Error codes** 3127 3128For details about the error codes, see [Media Error Codes](errorcode-media.md). 3129 3130| ID| Error Message | 3131| -------- | -------------------------------------- | 3132| 201 | Permission denied. Return by promise. | 3133| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 3134| 5400102 | Operate not permit. Return by promise. | 3135| 5400105 | Service died. Return by promise. | 3136 3137**Example** 3138 3139```ts 3140import { BusinessError } from '@kit.BasicServicesKit'; 3141 3142// Configure the parameters based on those supported by the hardware device. 3143let avRecorderProfile: media.AVRecorderProfile = { 3144 audioBitrate : 48000, 3145 audioChannels : 2, 3146 audioCodec : media.CodecMimeType.AUDIO_AAC, 3147 audioSampleRate : 48000, 3148 fileFormat : media.ContainerFormatType.CFT_MPEG_4, 3149 videoBitrate : 2000000, 3150 videoCodec : media.CodecMimeType.VIDEO_AVC, 3151 videoFrameWidth : 640, 3152 videoFrameHeight : 480, 3153 videoFrameRate : 30 3154} 3155let avRecorderConfig: media.AVRecorderConfig = { 3156 audioSourceType : media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC, 3157 videoSourceType : media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV, 3158 profile : avRecorderProfile, 3159 url : 'fd://', // Before passing in an FD to this parameter, the file must be created by the caller and granted with the read and write permissions. Example value: fd://45. 3160 rotation: 0, // The value can be 0, 90, 180, or 270. If any other value is used, prepare() reports an error. 3161 location : { latitude : 30, longitude : 130 } 3162} 3163 3164avRecorder.prepare(avRecorderConfig).then(() => { 3165 console.info('Succeeded in preparing'); 3166}).catch((err: BusinessError) => { 3167 console.error('Failed to prepare and catch error is ' + err.message); 3168}); 3169``` 3170 3171### getInputSurface<sup>9+</sup> 3172 3173getInputSurface(callback: AsyncCallback\<string>): void 3174 3175Obtains the surface required for recording. This API uses an asynchronous callback to return the result. The caller obtains the **surfaceBuffer** from this surface and fills in the corresponding video data. 3176 3177Note that the video data must carry the timestamp (in ns) and buffer size, and the start time of the timestamp must be based on the system startup time. 3178 3179This API can be called only after the [prepare()](#prepare9-2) API is called. 3180 3181**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3182 3183**Parameters** 3184 3185| Name | Type | Mandatory| Description | 3186| -------- | ---------------------- | ---- | --------------------------- | 3187| callback | AsyncCallback\<string> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the surface ID obtained; otherwise, **err** is an error object.| 3188 3189**Error codes** 3190 3191For details about the error codes, see [Media Error Codes](errorcode-media.md). 3192 3193| ID| Error Message | 3194| -------- | --------------------------------------- | 3195| 5400102 | Operate not permit. Return by callback. | 3196| 5400103 | IO error. Return by callback. | 3197| 5400105 | Service died. Return by callback. | 3198 3199**Example** 3200 3201```ts 3202import { BusinessError } from '@kit.BasicServicesKit'; 3203let surfaceID: string; // The surfaceID is transferred to the camera API to create a videoOutput instance. 3204 3205avRecorder.getInputSurface((err: BusinessError, surfaceId: string) => { 3206 if (err) { 3207 console.error('Failed to do getInputSurface and error is ' + err.message); 3208 } else { 3209 console.info('Succeeded in doing getInputSurface'); 3210 surfaceID = surfaceId; 3211 } 3212}); 3213 3214``` 3215 3216### getInputSurface<sup>9+</sup> 3217 3218getInputSurface(): Promise\<string> 3219 3220Obtains the surface required for recording. This API uses a promise to return the result. The caller obtains the **surfaceBuffer** from this surface and fills in the corresponding video data. 3221 3222Note that the video data must carry the timestamp (in ns) and buffer size, and the start time of the timestamp must be based on the system startup time. 3223 3224This API can be called only after the [prepare()](#prepare9-3) API is called. 3225 3226**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3227 3228**Return value** 3229 3230| Type | Description | 3231| ---------------- | -------------------------------- | 3232| Promise\<string> | Promise used to return the result.| 3233 3234**Error codes** 3235 3236For details about the error codes, see [Media Error Codes](errorcode-media.md). 3237 3238| ID| Error Message | 3239| -------- | -------------------------------------- | 3240| 5400102 | Operate not permit. Return by promise. | 3241| 5400103 | IO error. Return by promise. | 3242| 5400105 | Service died. Return by promise. | 3243 3244**Example** 3245 3246```ts 3247import { BusinessError } from '@kit.BasicServicesKit'; 3248let surfaceID: string; // The surfaceID is transferred to the camera API to create a videoOutput instance. 3249 3250avRecorder.getInputSurface().then((surfaceId: string) => { 3251 console.info('Succeeded in getting InputSurface'); 3252 surfaceID = surfaceId; 3253}).catch((err: BusinessError) => { 3254 console.error('Failed to get InputSurface and catch error is ' + err.message); 3255}); 3256``` 3257 3258### updateRotation<sup>12+</sup> 3259 3260updateRotation(rotation: number): Promise\<void> 3261 3262Updates the video rotation angle. This API uses a promise to return the result. 3263 3264This API can be called only after the [prepare()](#prepare9-3) event is triggered and before the [start()](#start9) API is called. 3265 3266**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3267 3268**Parameters** 3269 3270| Name | Type | Mandatory| Description | 3271| -------- | -------------------- | ---- | --------------------------- | 3272| rotation | number | Yes | Rotation angle, which can only be 0, 90, 180, or 270 degrees.| 3273 3274**Return value** 3275 3276| Type | Description | 3277| ---------------- | -------------------------------- | 3278| Promise\<void> | Promise that returns no value.| 3279 3280**Error codes** 3281 3282For details about the error codes, see [Media Error Codes](errorcode-media.md). 3283 3284| ID| Error Message | 3285| -------- | -------------------------------------- | 3286| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 3287| 5400102 | Operation not allowed. Return by promise. | 3288| 5400103 | IO error. Return by promise. | 3289| 5400105 | Service died. Return by promise. | 3290 3291**Example** 3292 3293```ts 3294import { BusinessError } from '@kit.BasicServicesKit'; 3295 3296let rotation = 90 3297 3298avRecorder.updateRotation(rotation).then(() => { 3299 console.info('Succeeded in updateRotation'); 3300}).catch((err: BusinessError) => { 3301 console.error('Failed to updateRotation and catch error is ' + err.message); 3302}); 3303``` 3304 3305### start<sup>9+</sup> 3306 3307start(callback: AsyncCallback\<void>): void 3308 3309Starts recording. This API uses an asynchronous callback to return the result. 3310 3311For audio-only recording, this API can be called only after the [prepare()](#prepare9-2) API is called. For video-only recording, this API can be called only after the [getInputSurface()](#getinputsurface9) API is called. 3312 3313**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3314 3315**Parameters** 3316 3317| Name | Type | Mandatory| Description | 3318| -------- | -------------------- | ---- | ---------------------------- | 3319| callback | AsyncCallback\<void> | Yes |Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 3320 3321**Error codes** 3322 3323For details about the error codes, see [Media Error Codes](errorcode-media.md). 3324 3325| ID| Error Message | 3326| -------- | --------------------------------------- | 3327| 5400102 | Operate not permit. Return by callback. | 3328| 5400103 | IO error. Return by callback. | 3329| 5400105 | Service died. Return by callback. | 3330 3331**Example** 3332 3333```ts 3334import { BusinessError } from '@kit.BasicServicesKit'; 3335 3336avRecorder.start((err: BusinessError) => { 3337 if (err) { 3338 console.error('Failed to start AVRecorder and error is ' + err.message); 3339 } else { 3340 console.info('Succeeded in starting AVRecorder'); 3341 } 3342}); 3343``` 3344 3345### start<sup>9+</sup> 3346 3347start(): Promise\<void> 3348 3349Starts recording. This API uses a promise to return the result. 3350 3351For audio-only recording, this API can be called only after the [prepare()](#prepare9-3) API is called. For video-only recording, this API can be called only after the [getInputSurface()](#getinputsurface9-1) API is called. 3352 3353**Atomic service API**: This API can be used in atomic services since API version 12. 3354 3355**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3356 3357**Return value** 3358 3359| Type | Description | 3360| -------------- | ------------------------------------- | 3361| Promise\<void> | Promise that returns no value.| 3362 3363**Error codes** 3364 3365For details about the error codes, see [Media Error Codes](errorcode-media.md). 3366 3367| ID| Error Message | 3368| -------- | -------------------------------------- | 3369| 5400102 | Operate not permit. Return by promise. | 3370| 5400103 | IO error. Return by promise. | 3371| 5400105 | Service died. Return by promise. | 3372 3373**Example** 3374 3375```ts 3376import { BusinessError } from '@kit.BasicServicesKit'; 3377 3378avRecorder.start().then(() => { 3379 console.info('Succeeded in starting AVRecorder'); 3380}).catch((err: BusinessError) => { 3381 console.error('Failed to start AVRecorder and catch error is ' + err.message); 3382}); 3383``` 3384 3385### pause<sup>9+</sup> 3386 3387pause(callback: AsyncCallback\<void>): void 3388 3389Pauses recording. This API uses an asynchronous callback to return the result. 3390 3391This API can be called only after the [start()](#start9) API is called. You can call [resume()](#resume9) to resume recording. 3392 3393**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3394 3395**Parameters** 3396 3397| Name | Type | Mandatory| Description | 3398| -------- | -------------------- | ---- | --------------------------- | 3399| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 3400 3401**Error codes** 3402 3403For details about the error codes, see [Media Error Codes](errorcode-media.md). 3404 3405| ID| Error Message | 3406| -------- | --------------------------------------- | 3407| 5400102 | Operate not permit. Return by callback. | 3408| 5400103 | IO error. Return by callback. | 3409| 5400105 | Service died. Return by callback. | 3410 3411**Example** 3412 3413```ts 3414import { BusinessError } from '@kit.BasicServicesKit'; 3415 3416avRecorder.pause((err: BusinessError) => { 3417 if (err) { 3418 console.error('Failed to pause AVRecorder and error is ' + err.message); 3419 } else { 3420 console.info('Succeeded in pausing'); 3421 } 3422}); 3423``` 3424 3425### pause<sup>9+</sup> 3426 3427pause(): Promise\<void> 3428 3429Pauses recording. This API uses a promise to return the result. 3430 3431This API can be called only after the [start()](#start9-1) API is called. You can call [resume()](#resume9-1) to resume recording. 3432 3433**Atomic service API**: This API can be used in atomic services since API version 12. 3434 3435**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3436 3437**Return value** 3438 3439| Type | Description | 3440| -------------- | ------------------------------------- | 3441| Promise\<void> | Promise that returns no value.| 3442 3443**Error codes** 3444 3445For details about the error codes, see [Media Error Codes](errorcode-media.md). 3446 3447| ID| Error Message | 3448| -------- | -------------------------------------- | 3449| 5400102 | Operate not permit. Return by promise. | 3450| 5400103 | IO error. Return by promise. | 3451| 5400105 | Service died. Return by promise. | 3452 3453**Example** 3454 3455```ts 3456import { BusinessError } from '@kit.BasicServicesKit'; 3457 3458avRecorder.pause().then(() => { 3459 console.info('Succeeded in pausing'); 3460}).catch((err: BusinessError) => { 3461 console.error('Failed to pause AVRecorder and catch error is ' + err.message); 3462}); 3463``` 3464 3465### resume<sup>9+</sup> 3466 3467resume(callback: AsyncCallback\<void>): void 3468 3469Resumes recording. This API uses an asynchronous callback to return the result. 3470 3471This API can be called only after the [pause()](#pause9-2) API is called. 3472 3473**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3474 3475**Parameters** 3476 3477| Name | Type | Mandatory| Description | 3478| -------- | -------------------- | ---- | ---------------------------- | 3479| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 3480 3481**Error codes** 3482 3483For details about the error codes, see [Media Error Codes](errorcode-media.md). 3484 3485| ID| Error Message | 3486| -------- | --------------------------------------- | 3487| 5400102 | Operate not permit. Return by callback. | 3488| 5400103 | IO error. Return by callback. | 3489| 5400105 | Service died. Return by callback. | 3490 3491**Example** 3492 3493```ts 3494import { BusinessError } from '@kit.BasicServicesKit'; 3495 3496avRecorder.resume((err: BusinessError) => { 3497 if (err) { 3498 console.error('Failed to resume AVRecorder and error is ' + err.message); 3499 } else { 3500 console.info('Succeeded in resuming AVRecorder'); 3501 } 3502}); 3503``` 3504 3505### resume<sup>9+</sup> 3506 3507resume(): Promise\<void> 3508 3509Resumes recording. This API uses a promise to return the result. 3510 3511This API can be called only after the [pause()](#pause9-3) API is called. 3512 3513**Atomic service API**: This API can be used in atomic services since API version 12. 3514 3515**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3516 3517**Return value** 3518 3519| Type | Description | 3520| -------------- | ------------------------------------- | 3521| Promise\<void> | Promise that returns no value.| 3522 3523**Error codes** 3524 3525For details about the error codes, see [Media Error Codes](errorcode-media.md). 3526 3527| ID| Error Message | 3528| -------- | -------------------------------------- | 3529| 5400102 | Operate not permit. Return by promise. | 3530| 5400103 | IO error. Return by promise. | 3531| 5400105 | Service died. Return by promise. | 3532 3533**Example** 3534 3535```ts 3536import { BusinessError } from '@kit.BasicServicesKit'; 3537 3538avRecorder.resume().then(() => { 3539 console.info('Succeeded in resuming AVRecorder'); 3540}).catch((err: BusinessError) => { 3541 console.error('Failed to resume AVRecorder failed and catch error is ' + err.message); 3542}); 3543``` 3544 3545### stop<sup>9+</sup> 3546 3547stop(callback: AsyncCallback\<void>): void 3548 3549Stops recording. This API uses an asynchronous callback to return the result. 3550 3551This API can be called only after the [start()](#start9) or [pause()](#pause9-2) API is called. 3552 3553For audio-only recording, you can call [prepare()](#prepare9-2) again for re-recording. For video-only recording or audio and video recording, you can call [prepare()](#prepare9-2) and [getInputSurface()](#getinputsurface9) again for re-recording. 3554 3555**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3556 3557**Parameters** 3558 3559| Name | Type | Mandatory| Description | 3560| -------- | -------------------- | ---- | ---------------------------- | 3561| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 3562 3563**Error codes** 3564 3565For details about the error codes, see [Media Error Codes](errorcode-media.md). 3566 3567| ID| Error Message | 3568| -------- | --------------------------------------- | 3569| 5400102 | Operate not permit. Return by callback. | 3570| 5400103 | IO error. Return by callback. | 3571| 5400105 | Service died. Return by callback. | 3572 3573**Example** 3574 3575```ts 3576import { BusinessError } from '@kit.BasicServicesKit'; 3577 3578avRecorder.stop((err: BusinessError) => { 3579 if (err) { 3580 console.error('Failed to stop AVRecorder and error is ' + err.message); 3581 } else { 3582 console.info('Succeeded in stopping AVRecorder'); 3583 } 3584}); 3585``` 3586 3587### stop<sup>9+</sup> 3588 3589stop(): Promise\<void> 3590 3591Stops recording. This API uses a promise to return the result. 3592 3593This API can be called only after the [start()](#start9-1) or [pause()](#pause9-3) API is called. 3594 3595For audio-only recording, you can call [prepare()](#prepare9-3) again for re-recording. For video-only recording or audio and video recording, you can call [prepare()](#prepare9-3) and [getInputSurface()](#getinputsurface9-1) again for re-recording. 3596 3597**Atomic service API**: This API can be used in atomic services since API version 12. 3598 3599**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3600 3601**Return value** 3602 3603| Type | Description | 3604| -------------- | ------------------------------------- | 3605| Promise\<void> | Promise that returns no value.| 3606 3607**Error codes** 3608 3609For details about the error codes, see [Media Error Codes](errorcode-media.md). 3610 3611| ID| Error Message | 3612| -------- | -------------------------------------- | 3613| 5400102 | Operate not permit. Return by promise. | 3614| 5400103 | IO error. Return by promise. | 3615| 5400105 | Service died. Return by promise. | 3616 3617**Example** 3618 3619```ts 3620import { BusinessError } from '@kit.BasicServicesKit'; 3621 3622avRecorder.stop().then(() => { 3623 console.info('Succeeded in stopping AVRecorder'); 3624}).catch((err: BusinessError) => { 3625 console.error('Failed to stop AVRecorder and catch error is ' + err.message); 3626}); 3627``` 3628 3629### reset<sup>9+</sup> 3630 3631reset(callback: AsyncCallback\<void>): void 3632 3633Resets audio and video recording. This API uses an asynchronous callback to return the result. 3634 3635For audio-only recording, you can call [prepare()](#prepare9-2) again for re-recording. For video-only recording or audio and video recording, you can call [prepare()](#prepare9-2) and [getInputSurface()](#getinputsurface9) again for re-recording. 3636 3637**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3638 3639**Parameters** 3640 3641| Name | Type | Mandatory| Description | 3642| -------- | -------------------- | ---- | ------------------------------ | 3643| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 3644 3645**Error codes** 3646 3647For details about the error codes, see [Media Error Codes](errorcode-media.md). 3648 3649| ID| Error Message | 3650| -------- | --------------------------------- | 3651| 5400103 | IO error. Return by callback. | 3652| 5400105 | Service died. Return by callback. | 3653 3654**Example** 3655 3656```ts 3657import { BusinessError } from '@kit.BasicServicesKit'; 3658 3659avRecorder.reset((err: BusinessError) => { 3660 if (err) { 3661 console.error('Failed to reset AVRecorder and error is ' + err.message); 3662 } else { 3663 console.info('Succeeded in resetting AVRecorder'); 3664 } 3665}); 3666``` 3667 3668### reset<sup>9+</sup> 3669 3670reset(): Promise\<void> 3671 3672Resets audio and video recording. This API uses a promise to return the result. 3673 3674For audio-only recording, you can call [prepare()](#prepare9-3) again for re-recording. For video-only recording or audio and video recording, you can call [prepare()](#prepare9-3) and [getInputSurface()](#getinputsurface9-1) again for re-recording. 3675 3676**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3677 3678**Return value** 3679 3680| Type | Description | 3681| -------------- | --------------------------------------- | 3682| Promise\<void> | Promise that returns no value.| 3683 3684**Error codes** 3685 3686For details about the error codes, see [Media Error Codes](errorcode-media.md). 3687 3688| ID| Error Message | 3689| -------- | -------------------------------- | 3690| 5400103 | IO error. Return by promise. | 3691| 5400105 | Service died. Return by promise. | 3692 3693**Example** 3694 3695```ts 3696import { BusinessError } from '@kit.BasicServicesKit'; 3697 3698avRecorder.reset().then(() => { 3699 console.info('Succeeded in resetting AVRecorder'); 3700}).catch((err: BusinessError) => { 3701 console.error('Failed to reset and catch error is ' + err.message); 3702}); 3703``` 3704 3705### release<sup>9+</sup> 3706 3707release(callback: AsyncCallback\<void>): void 3708 3709Releases the audio and video recording resources. This API uses an asynchronous callback to return the result. 3710 3711After the resources are released, you can no longer perform any operation on the **AVRecorder** instance. 3712 3713**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3714 3715**Parameters** 3716 3717| Name | Type | Mandatory| Description | 3718| -------- | -------------------- | ---- | ---------------------------------- | 3719| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 3720 3721**Error codes** 3722 3723For details about the error codes, see [Media Error Codes](errorcode-media.md). 3724 3725| ID| Error Message | 3726| -------- | --------------------------------- | 3727| 5400105 | Service died. Return by callback. | 3728 3729**Example** 3730 3731```ts 3732import { BusinessError } from '@kit.BasicServicesKit'; 3733 3734avRecorder.release((err: BusinessError) => { 3735 if (err) { 3736 console.error('Failed to release AVRecorder and error is ' + err.message); 3737 } else { 3738 console.info('Succeeded in releasing AVRecorder'); 3739 } 3740}); 3741``` 3742 3743### release<sup>9+</sup> 3744 3745release(): Promise\<void> 3746 3747Releases the audio and video recording resources. This API uses a promise to return the result. 3748 3749After the resources are released, you can no longer perform any operation on the **AVRecorder** instance. 3750 3751**Atomic service API**: This API can be used in atomic services since API version 12. 3752 3753**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3754 3755**Return value** 3756 3757| Type | Description | 3758| -------------- | ------------------------------------------- | 3759| Promise\<void> | Promise that returns no value.| 3760 3761**Error codes** 3762 3763For details about the error codes, see [Media Error Codes](errorcode-media.md). 3764 3765| ID| Error Message | 3766| -------- | --------------------------------- | 3767| 5400105 | Service died. Return by callback. | 3768 3769**Example** 3770 3771```ts 3772import { BusinessError } from '@kit.BasicServicesKit'; 3773 3774avRecorder.release().then(() => { 3775 console.info('Succeeded in releasing AVRecorder'); 3776}).catch((err: BusinessError) => { 3777 console.error('Failed to release AVRecorder and catch error is ' + err.message); 3778}); 3779``` 3780 3781### getCurrentAudioCapturerInfo<sup>11+</sup> 3782 3783getCurrentAudioCapturerInfo(callback: AsyncCallback\<audio.AudioCapturerChangeInfo>): void 3784 3785Obtains the information about the current audio capturer. This API uses an asynchronous callback to return the result. 3786 3787This API can be called only after the **prepare()** API is called. If this API is called after **stop()** is successfully called, an error is reported. 3788 3789**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3790 3791**Parameters** 3792 3793| Name | Type | Mandatory| Description | 3794| -------- | ------------------------------------------------------------ | ---- | ------------------------------------ | 3795| callback | AsyncCallback\<[audio.AudioCapturerChangeInfo](../apis-audio-kit/js-apis-audio.md#audiocapturerchangeinfo9)> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the **audio.AudioCapturerChangeInfo** object obtained; otherwise, **err** is an error object.| 3796 3797**Error codes** 3798 3799For details about the error codes, see [Media Error Codes](errorcode-media.md). 3800 3801| ID| Error Message | 3802| -------- | ------------------------------------------ | 3803| 5400102 | Operation not allowed. | 3804| 5400103 | I/O error. | 3805| 5400105 | Service died. Return by callback. | 3806 3807**Example** 3808 3809```ts 3810import { audio } from '@kit.AudioKit'; 3811 3812let currentCapturerInfo: audio.AudioCapturerChangeInfo; 3813 3814avRecorder.getCurrentAudioCapturerInfo((err: BusinessError, capturerInfo: audio.AudioCapturerChangeInfo) => { 3815 if (err) { 3816 console.error('Failed to get CurrentAudioCapturerInfo and error is ' + err.message); 3817 } else { 3818 console.info('Succeeded in getting CurrentAudioCapturerInfo'); 3819 currentCapturerInfo = capturerInfo; 3820 } 3821}); 3822``` 3823 3824### getCurrentAudioCapturerInfo<sup>11+</sup> 3825 3826getCurrentAudioCapturerInfo(): Promise\<audio.AudioCapturerChangeInfo> 3827 3828Obtains the information about the current audio capturer. This API uses a promise to return the result. 3829 3830This API can be called only after the **prepare()** API is called. If this API is called after **stop()** is successfully called, an error is reported. 3831 3832**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3833 3834**Return value** 3835 3836| Type | Description | 3837| ------------------------------------------------------------ | ------------------------------------------------- | 3838| Promise\<[audio.AudioCapturerChangeInfo](../apis-audio-kit/js-apis-audio.md#audiocapturerchangeinfo9)> | Promise used to return the audio capturer information.| 3839 3840**Error codes** 3841 3842For details about the error codes, see [Media Error Codes](errorcode-media.md). 3843 3844| ID| Error Message | 3845| -------- | -------------------------------- | 3846| 5400102 | Operation not allowed. | 3847| 5400103 | I/O error. | 3848| 5400105 | Service died. Return by promise. | 3849 3850**Example** 3851 3852```ts 3853import { audio } from '@kit.AudioKit'; 3854 3855let currentCapturerInfo: audio.AudioCapturerChangeInfo; 3856 3857avRecorder.getCurrentAudioCapturerInfo().then((capturerInfo: audio.AudioCapturerChangeInfo) => { 3858 console.info('Succeeded in getting CurrentAudioCapturerInfo'); 3859 currentCapturerInfo = capturerInfo; 3860}).catch((err: BusinessError) => { 3861 console.error('Failed to get CurrentAudioCapturerInfo and catch error is ' + err.message); 3862}); 3863``` 3864 3865### getAudioCapturerMaxAmplitude<sup>11+</sup> 3866 3867getAudioCapturerMaxAmplitude(callback: AsyncCallback\<number>): void 3868 3869Obtains the maximum amplitude of the current audio capturer. This API uses an asynchronous callback to return the result. 3870 3871This API can be called only after the **prepare()** API is called. If this API is called after **stop()** is successfully called, an error is reported. 3872 3873The return value is the maximum amplitude within the duration from the time the maximum amplitude is obtained last time to the current time. For example, if you have obtained the maximum amplitude at 1s and you call this API again at 2s, then the return value is the maximum amplitude within the duration from 1s to 2s. 3874 3875**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3876 3877**Parameters** 3878 3879| Name | Type | Mandatory| Description | 3880| -------- | ---------------------- | ---- | ------------------------------------ | 3881| callback | AsyncCallback\<number> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the maximum amplitude obtained; otherwise, **err** is an error object.| 3882 3883**Error codes** 3884 3885For details about the error codes, see [Media Error Codes](errorcode-media.md). 3886 3887| ID| Error Message | 3888| -------- | ------------------------------------------ | 3889| 5400102 | Operation not allowed. | 3890| 5400105 | Service died. Return by callback. | 3891 3892**Example** 3893 3894```ts 3895let maxAmplitude: number; 3896 3897avRecorder.getAudioCapturerMaxAmplitude((err: BusinessError, amplitude: number) => { 3898 if (err) { 3899 console.error('Failed to get AudioCapturerMaxAmplitude and error is ' + err.message); 3900 } else { 3901 console.info('Succeeded in getting AudioCapturerMaxAmplitude'); 3902 maxAmplitude = amplitude; 3903 } 3904}); 3905``` 3906 3907### getAudioCapturerMaxAmplitude<sup>11+</sup> 3908 3909getAudioCapturerMaxAmplitude(): Promise\<number> 3910 3911Obtains the maximum amplitude of the current audio capturer. This API uses a promise to return the result. 3912 3913This API can be called only after the **prepare()** API is called. If this API is called after **stop()** is successfully called, an error is reported. 3914 3915The return value is the maximum amplitude within the duration from the time the maximum amplitude is obtained last time to the current time. For example, if you have obtained the maximum amplitude at 1s and you call this API again at 2s, then the return value is the maximum amplitude within the duration from 1s to 2s. 3916 3917**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3918 3919**Return value** 3920 3921| Type | Description | 3922| ---------------- | ------------------------------------------------- | 3923| Promise\<number>| Promise used to return the maximum amplitude obtained.| 3924 3925**Error codes** 3926 3927For details about the error codes, see [Media Error Codes](errorcode-media.md). 3928 3929| ID| Error Message | 3930| -------- | -------------------------------- | 3931| 5400102 | Operation not allowed. | 3932| 5400105 | Service died. Return by promise. | 3933 3934**Example** 3935 3936```ts 3937let maxAmplitude: number; 3938 3939avRecorder.getAudioCapturerMaxAmplitude().then((amplitude: number) => { 3940 console.info('Succeeded in getting AudioCapturerMaxAmplitude'); 3941 maxAmplitude = amplitude; 3942}).catch((err: BusinessError) => { 3943 console.error('Failed to get AudioCapturerMaxAmplitude and catch error is ' + err.message); 3944}); 3945``` 3946 3947### getAvailableEncoder<sup>11+</sup> 3948 3949getAvailableEncoder(callback: AsyncCallback\<Array\<EncoderInfo>>): void 3950 3951Obtains available encoders. This API uses an asynchronous callback to return the result. 3952 3953**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3954 3955**Parameters** 3956 3957| Name | Type | Mandatory| Description | 3958| -------- | ----------------------------------------------------- | ---- | ------------------------------------ | 3959| callback | AsyncCallback\<Array\<[EncoderInfo](#encoderinfo11)>> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the available encoders obtained; otherwise, **err** is an error object.| 3960 3961**Error codes** 3962 3963For details about the error codes, see [Media Error Codes](errorcode-media.md). 3964 3965| ID| Error Message | 3966| -------- | ------------------------------------------ | 3967| 5400102 | Operation not allowed. | 3968| 5400105 | Service died. Return by callback. | 3969 3970**Example** 3971 3972```ts 3973let encoderInfo: media.EncoderInfo; 3974 3975avRecorder.getAvailableEncoder((err: BusinessError, info: media.EncoderInfo[]) => { 3976 if (err) { 3977 console.error('Failed to get AvailableEncoder and error is ' + err.message); 3978 } else { 3979 console.info('Succeeded in getting AvailableEncoder'); 3980 encoderInfo = info[0]; 3981 } 3982}); 3983``` 3984 3985### getAvailableEncoder<sup>11+</sup> 3986 3987getAvailableEncoder(): Promise\<Array\<EncoderInfo>> 3988 3989Obtains available encoders. This API uses an asynchronous callback to return the result. 3990 3991**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3992 3993**Return value** 3994 3995| Type | Description | 3996| ----------------------------------------------- | ----------------------------------------------- | 3997| Promise\<Array\<[EncoderInfo](#encoderinfo11)>> | Promise used to return the information about the available encoders.| 3998 3999**Error codes** 4000 4001For details about the error codes, see [Media Error Codes](errorcode-media.md). 4002 4003| ID| Error Message | 4004| -------- | -------------------------------- | 4005| 5400102 | Operation not allowed. | 4006| 5400105 | Service died. Return by promise. | 4007 4008**Example** 4009 4010```ts 4011let encoderInfo: media.EncoderInfo; 4012 4013avRecorder.getAvailableEncoder().then((info: media.EncoderInfo[]) => { 4014 console.info('Succeeded in getting AvailableEncoder'); 4015 encoderInfo = info[0]; 4016}).catch((err: BusinessError) => { 4017 console.error('Failed to get AvailableEncoder and catch error is ' + err.message); 4018}); 4019``` 4020 4021### getAVRecorderConfig<sup>11+</sup> 4022 4023getAVRecorderConfig(callback: AsyncCallback\<AVRecorderConfig>): void 4024 4025Obtains the real-time configuration of this AVRecorder. This API uses an asynchronous callback to return the result. 4026 4027This API can be called only after [prepare()](#prepare9-2) is called. 4028 4029**System capability**: SystemCapability.Multimedia.Media.AVRecorder 4030 4031**Parameters** 4032 4033| Name | Type | Mandatory| Description | 4034| -------- | ---------------------- | ---- | --------------------------- | 4035| callback | AsyncCallback\<[AVRecorderConfig](#avrecorderconfig9)> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the real-time configuration obtained; otherwise, **err** is an error object.| 4036 4037**Error codes** 4038 4039For details about the error codes, see [Media Error Codes](errorcode-media.md). 4040 4041| ID| Error Message | 4042| -------- | ------------------------------------------ | 4043| 5400102 | Operate not permit. Return by callback. | 4044| 5400103 | IO error. Return by callback. | 4045| 5400105 | Service died. Return by callback. | 4046 4047**Example** 4048 4049```ts 4050import { BusinessError } from '@kit.BasicServicesKit'; 4051 4052let avConfig: media.AVRecorderConfig; 4053 4054avRecorder.getAVRecorderConfig((err: BusinessError, config: media.AVRecorderConfig) => { 4055 if (err) { 4056 console.error('Failed to get avConfig and error is ' + err.message); 4057 } else { 4058 console.info('Succeeded in getting AVRecorderConfig'); 4059 avConfig = config; 4060 } 4061}); 4062``` 4063 4064### getAVRecorderConfig<sup>11+</sup> 4065 4066getAVRecorderConfig(): Promise\<AVRecorderConfig>; 4067 4068Obtains the real-time configuration of this AVRecorder. This API uses a promise to return the result. 4069 4070This API can be called only after [prepare()](#prepare9-3) is called. 4071 4072**System capability**: SystemCapability.Multimedia.Media.AVRecorder 4073 4074**Return value** 4075 4076| Type | Description | 4077| ---------------- | -------------------------------- | 4078| Promise\<[AVRecorderConfig](#avrecorderconfig9)> | Promise used to return the real-time configuration.| 4079 4080**Error codes** 4081 4082For details about the error codes, see [Media Error Codes](errorcode-media.md). 4083 4084| ID| Error Message | 4085| -------- | ----------------------------------------- | 4086| 5400102 | Operate not permit. Return by promise. | 4087| 5400103 | IO error. Return by promise. | 4088| 5400105 | Service died. Return by promise. | 4089 4090**Example** 4091 4092```ts 4093import { BusinessError } from '@kit.BasicServicesKit'; 4094 4095let avConfig: media.AVRecorderConfig; 4096 4097avRecorder.getAVRecorderConfig().then((config: media.AVRecorderConfig) => { 4098 console.info('Succeeded in getting AVRecorderConfig'); 4099 avConfig = config; 4100}).catch((err: BusinessError) => { 4101 console.error('Failed to get AVRecorderConfig and catch error is ' + err.message); 4102}); 4103``` 4104 4105### on('stateChange')<sup>9+</sup> 4106 4107on(type: 'stateChange', callback: OnAVRecorderStateChangeHandler): void 4108 4109Subscribes to AVRecorder state changes. An application can subscribe to only one AVRecorder state change event. When the application initiates multiple subscriptions to this event, the last subscription prevails. 4110 4111**Atomic service API**: This API can be used in atomic services since API version 12. 4112 4113**System capability**: SystemCapability.Multimedia.Media.AVRecorder 4114 4115**Parameters** 4116 4117| Name | Type | Mandatory| Description | 4118| -------- | -------- | ---- | ------------------------------------------------------------ | 4119| type | string | Yes | Event type, which is **'stateChange'** in this case. This event can be triggered by both user operations and the system.| 4120| callback | [OnAVRecorderStateChangeHandler](#onavrecorderstatechangehandler12) | Yes | Callback invoked when the event is triggered.| 4121 4122**Error codes** 4123 4124For details about the error codes, see [Media Error Codes](errorcode-media.md). 4125 4126| ID| Error Message | 4127| -------- | --------------------------------- | 4128| 5400103 | IO error. Return by callback. | 4129| 5400105 | Service died. Return by callback. | 4130 4131**Example** 4132 4133```ts 4134avRecorder.on('stateChange', async (state: media.AVRecorderState, reason: media.StateChangeReason) => { 4135 console.info('case state has changed, new state is :' + state + ',and new reason is : ' + reason); 4136}); 4137``` 4138 4139### off('stateChange')<sup>9+</sup> 4140 4141off(type: 'stateChange', callback?: OnAVRecorderStateChangeHandler): void 4142 4143Unsubscribes from AVRecorder state changes. 4144 4145**Atomic service API**: This API can be used in atomic services since API version 12. 4146 4147**System capability**: SystemCapability.Multimedia.Media.AVRecorder 4148 4149**Parameters** 4150 4151| Name| Type | Mandatory| Description | 4152| ------ | ------ | ---- | ------------------------------------------------------------ | 4153| type | string | Yes | Event type, which is **'stateChange'** in this case. This event can be triggered by both user operations and the system.| 4154| callback | [OnAVRecorderStateChangeHandler](#onavrecorderstatechangehandler12) | No | Callback invoked when the event is triggered.<br>This parameter is supported since API version 12.| 4155 4156**Example** 4157 4158```ts 4159avRecorder.off('stateChange'); 4160``` 4161 4162### on('error')<sup>9+</sup> 4163 4164on(type: 'error', callback: ErrorCallback): void 4165 4166Subscribes to AVRecorder errors. This event is used only for error prompt and does not require the user to stop recording control. If the [AVRecorderState](#avrecorderstate9) is also switched to error, call [reset()](#reset9-2) or [release()][release()](#release9-2) to exit the recording. 4167 4168An application can subscribe to only one AVRecorder error event. When the application initiates multiple subscriptions to this event, the last subscription prevails. 4169 4170**Atomic service API**: This API can be used in atomic services since API version 12. 4171 4172**System capability**: SystemCapability.Multimedia.Media.AVRecorder 4173 4174**Parameters** 4175 4176| Name | Type | Mandatory| Description | 4177| -------- | ------------- | ---- | ------------------------------------------------------------ | 4178| type | string | Yes | Event type, which is **'error'** in this case.<br>This event is triggered when an error occurs during recording.| 4179| callback | [ErrorCallback](../apis-basic-services-kit/js-apis-base.md#errorcallback) | Yes | Callback invoked when the event is triggered. | 4180 4181**Error codes** 4182 4183For details about the error codes, see [Media Error Codes](errorcode-media.md). 4184 4185| ID| Error Message | 4186| -------- | ------------------------------------------ | 4187| 201 | Permission denied. | 4188| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 4189| 801 | Capability not supported. | 4190| 5400101 | No memory. | 4191| 5400102 | Operation not allowed. | 4192| 5400103 | I/O error. | 4193| 5400104 | Time out. | 4194| 5400105 | Service died. | 4195| 5400106 | Unsupport format. | 4196| 5400107 | Audio interrupted. | 4197 4198**Example** 4199 4200```ts 4201import { BusinessError } from '@kit.BasicServicesKit'; 4202 4203avRecorder.on('error', (err: BusinessError) => { 4204 console.info('case avRecorder.on(error) called, errMessage is ' + err.message); 4205}); 4206``` 4207 4208### off('error')<sup>9+</sup> 4209 4210off(type: 'error', callback?: ErrorCallback): void 4211 4212Unsubscribes from AVRecorder errors. After the unsubscription, your application can no longer receive AVRecorder errors. 4213 4214**Atomic service API**: This API can be used in atomic services since API version 12. 4215 4216**System capability**: SystemCapability.Multimedia.Media.AVRecorder 4217 4218**Parameters** 4219 4220| Name| Type | Mandatory| Description | 4221| ------ | ------ | ---- | ------------------------------------------------------------ | 4222| type | string | Yes | Event type, which is **'error'** in this case.<br>This event is triggered when an error occurs during recording.| 4223| callback | [ErrorCallback](../apis-basic-services-kit/js-apis-base.md#errorcallback) | No | Callback invoked when the event is triggered.<br>This parameter is supported since API version 12. | 4224 4225**Example** 4226 4227```ts 4228avRecorder.off('error'); 4229``` 4230 4231### on('audioCapturerChange')<sup>11+</sup> 4232 4233on(type: 'audioCapturerChange', callback: Callback<audio.AudioCapturerChangeInfo>): void 4234 4235Subscribes to audio capturer configuration changes. Any configuration change triggers the callback that returns the entire configuration information. 4236 4237When the application initiates multiple subscriptions to this event, the last subscription prevails. 4238 4239**System capability**: SystemCapability.Multimedia.Media.AVRecorder 4240 4241**Parameters** 4242 4243| Name | Type | Mandatory| Description | 4244| -------- | -------- | ---- | ------------------------------------------------------------ | 4245| type | string | Yes |Event type, which is **'audioCapturerChange'** in this case.| 4246| callback | Callback<[audio.AudioCapturerChangeInfo](../apis-audio-kit/js-apis-audio.md#audiocapturerchangeinfo9)> | Yes| Callback used to return the entire configuration information about the audio capturer.| 4247 4248**Error codes** 4249 4250| ID| Error Message | 4251| -------- | ------------------------------------------ | 4252| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 4253 4254**Example** 4255 4256```ts 4257let capturerChangeInfo: audio.AudioCapturerChangeInfo; 4258 4259avRecorder.on('audioCapturerChange', (audioCapturerChangeInfo: audio.AudioCapturerChangeInfo) => { 4260 console.info('audioCapturerChange called'); 4261 capturerChangeInfo = audioCapturerChangeInfo; 4262}); 4263``` 4264 4265### off('audioCapturerChange')<sup>11+</sup> 4266 4267off(type: 'audioCapturerChange', callback?: Callback<audio.AudioCapturerChangeInfo>): void 4268 4269Subscribes to audio capturer configuration changes. 4270 4271**System capability**: SystemCapability.Multimedia.Media.AVRecorder 4272 4273**Parameters** 4274 4275| Name| Type | Mandatory| Description | 4276| ------ | ------ | ---- | ------------------------------------------------------------ | 4277| type | string | Yes | Event type, which is **'audioCapturerChange'** in this case.| 4278| callback | Callback<[audio.AudioCapturerChangeInfo](../apis-audio-kit/js-apis-audio.md#audiocapturerchangeinfo9)> | No| Callback used to return the entire configuration information about the audio capturer.<br>This parameter is supported since API version 12.| 4279 4280**Example** 4281 4282```ts 4283avRecorder.off('audioCapturerChange'); 4284``` 4285 4286### on('photoAssetAvailable')<sup>12+</sup> 4287 4288on(type: 'photoAssetAvailable', callback: Callback\<photoAccessHelper.PhotoAsset>): void 4289 4290Subscribes to media asset callback events. When [FileGenerationMode](#filegenerationmode12) is used during media file creation, the [PhotoAsset](../apis-media-library-kit/js-apis-photoAccessHelper.md#photoasset) object is called back to the application after the [stop](#stop9-2) operation is complete. 4291 4292When the application initiates multiple subscriptions to this event, the last subscription prevails. 4293 4294**System capability**: SystemCapability.Multimedia.Media.AVRecorder 4295 4296**Parameters** 4297 4298| Name | Type | Mandatory| Description | 4299| -------- | -------- | ---- | ------------------------------------------------------------ | 4300| type | string | Yes |Event type, which is **'photoAssetAvailable'** in this case. The event is triggered when a photo asset is available.| 4301| callback | Callback<[photoAccessHelper.PhotoAsset](../apis-media-library-kit/js-apis-photoAccessHelper.md#photoasset)> | Yes| Callback used to return the **PhotoAsset** object corresponding to the resource file created by the system.| 4302 4303**Error codes** 4304 4305| ID| Error Message | 4306| -------- | ------------------------------------------ | 4307| 5400103 | IO error. Return by callback. | 4308| 5400105 | Service died. Return by callback. | 4309 4310**Example** 4311 4312```ts 4313import { photoAccessHelper } from '@kit.MediaLibraryKit'; 4314let photoAsset: photoAccessHelper.PhotoAsset; 4315 4316// Example: Process the photoAsset callback and save the video. 4317async saveVideo(asset: photoAccessHelper.PhotoAsset) { 4318 console.info("saveVideo called"); 4319 try { 4320 let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(getContext(this)); 4321 let assetChangeRequest: photoAccessHelper.MediaAssetChangeRequest = new photoAccessHelper.MediaAssetChangeRequest(asset); 4322 assetChangeRequest.saveCameraPhoto(); 4323 await phAccessHelper.applyChanges(assetChangeRequest); 4324 console.info('apply saveVideo successfully'); 4325 } catch (err) { 4326 console.error(`apply saveVideo failed with error: ${err.code}, ${err.message}`); 4327 } 4328} 4329// Subscribe to the photoAsset event. 4330avRecorder.on('photoAssetAvailable', (asset: photoAccessHelper.PhotoAsset) => { 4331 console.info('photoAssetAvailable called'); 4332 if (asset != undefined) { 4333 photoAsset = asset; 4334 // Process the photoAsset callback. 4335 // Example: this.saveVideo (asset); 4336 } else { 4337 console.error('photoAsset is undefined'); 4338 } 4339}); 4340``` 4341 4342### off('photoAssetAvailable')<sup>12+</sup> 4343 4344off(type: 'photoAssetAvailable', callback?: Callback<photoAccessHelper.PhotoAsset>): void 4345 4346Unsubscribes from media asset callback events. 4347 4348**System capability**: SystemCapability.Multimedia.Media.AVRecorder 4349 4350**Parameters** 4351 4352| Name| Type | Mandatory| Description | 4353| ------ | ------ | ---- | ------------------------------------------------------------ | 4354| type | string | Yes | Event type, which is **'photoAssetAvailable'** in this case.| 4355 4356**Example** 4357 4358```ts 4359avRecorder.off('photoAssetAvailable'); 4360``` 4361 4362## AVRecorderState<sup>9+</sup> 4363 4364type AVRecorderState = 'idle' | 'prepared' | 'started' | 'paused' | 'stopped' | 'released' | 'error' 4365 4366Enumerates the AVRecorder states. You can obtain the state through the **state** attribute. 4367 4368**Atomic service API**: This API can be used in atomic services since API version 12. 4369 4370**System capability**: SystemCapability.Multimedia.Media.AVRecorder 4371 4372| Type | Description | 4373| -------- | ------------------------------------------------------------ | 4374| 'idle' | The AVRecorder enters this state after it is just created or the [AVRecorder.reset()](#reset9-2) API is called when the AVRecorder is in any state except released. In this state, you can call [AVRecorder.prepare()](#prepare9-2) to set recording parameters. | 4375| 'prepared' | The AVRecorder enters this state when the parameters are set. In this state, you can call [AVRecorder.start()](#start9) to start recording.| 4376| 'started' | The AVRecorder enters this state when the recording starts. In this state, you can call [AVRecorder.pause()](#pause9-2) to pause recording or call [AVRecorder.stop()](#stop9-2) to stop recording.| 4377| 'paused' | The AVRecorder enters this state when the recording is paused. In this state, you can call [AVRecorder.resume()](#resume9) to continue recording or call [AVRecorder.stop()](#stop9-2) to stop recording.| 4378| 'stopped' | The AVRecorder enters this state when the recording stops. In this state, you can call [AVRecorder.prepare()](#prepare9-2) to set recording parameters so that the AVRecorder enters the prepared state again.| 4379| 'released' | The AVRecorder enters this state when the recording resources are released. In this state, no operation can be performed. In any other state, you can call [AVRecorder.release()](#release9-2) to enter the released state.| 4380| 'error' | The AVRecorder enters this state when an irreversible error occurs in the **AVRecorder** instance. In this state, the [AVRecorder.on('error') event](#onerror9-1) is reported, with the detailed error cause. In the error state, you must call [AVRecorder.reset()](#reset9-2) to reset the **AVRecorder** instance or call [AVRecorder.release()](#release9-2) to release the resources.| 4381 4382## OnAVRecorderStateChangeHandler<sup>12+</sup> 4383 4384type OnAVRecorderStateChangeHandler = (state: AVRecorderState, reason: StateChangeReason) => void 4385 4386Describes the callback invoked for the AVRecorder state change event. 4387 4388**Atomic service API**: This API can be used in atomic services since API version 12. 4389 4390**System capability**: SystemCapability.Multimedia.Media.AVPlayer 4391 4392| Name | Type | Mandatory| Description | 4393| ------ | ------ | ------ | ------------------------------------------------------------ | 4394| state | [AVRecorderState](#avrecorderstate9) | Mandatory| AVRecorder state. | 4395| reason | [StateChangeReason](#statechangereason9) | Mandatory| Reason for the state change.| 4396 4397## AVRecorderConfig<sup>9+</sup> 4398 4399Describes the audio and video recording parameters. 4400 4401The **audioSourceType** and **videoSourceType** parameters are used to distinguish audio-only recording, video-only recording, and audio and video recording. For audio-only recording, set only **audioSourceType**. For video-only recording, set only **videoSourceType**. For audio and video recording, set both **audioSourceType** and **videoSourceType**. 4402 4403**System capability**: SystemCapability.Multimedia.Media.AVRecorder 4404 4405| Name | Type | Mandatory| Description | 4406| --------------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | 4407| audioSourceType | [AudioSourceType](#audiosourcetype9) | No | Type of the audio source to record. This parameter is mandatory for audio recording.<br> **Atomic service API**: This API can be used in atomic services since API version 12.| 4408| videoSourceType | [VideoSourceType](#videosourcetype9) | No | Type of the video source to record. This parameter is mandatory for video recording. | 4409| profile | [AVRecorderProfile](#avrecorderprofile9) | Yes | Recording profile. This parameter is mandatory.<br> **Atomic service API**: This API can be used in atomic services since API version 12.| 4410| url | string | Yes | Recording output URL: fd://xx (fd number).<br><br>This parameter is mandatory.<br> **Atomic service API**: This API can be used in atomic services since API version 12.| 4411|fileGenerationMode<sup>12+</sup> | [FileGenerationMode](#filegenerationmode12) | No | Mode for creating the file, which is used together with [on('photoAssetAvailable')](#onphotoassetavailable12).| 4412| rotation<sup>(deprecated)</sup> | number | No | Rotation angle of the recorded video. The value can be 0 (default), 90, 180, or 270 for MP4 videos.<br>This API is supported since API version 6 and deprecated since API version 12. You are advised to use **[AVMetadata](#avmetadata11).videoOrientation** instead. If both parameters are set, **[AVMetadata](#avmetadata11).videoOrientation** is used. | 4413| location<sup>(deprecated)</sup> | [Location](#location) | No | Geographical location of the recorded video. By default, the geographical location information is not recorded.<br>This API is supported since API version 6 and deprecated since API version 12. You are advised to use **[AVMetadata](#avmetadata11).location** instead. If both parameters are set, **[AVMetadata](#avmetadata11).location** is used.| 4414| metadata<sup>12+</sup> | [AVMetadata](#avmetadata11) | No | Metadata. For details, see [AVMetadata](#avmetadata11). | 4415 4416## AVRecorderProfile<sup>9+</sup> 4417 4418Describes the audio and video recording profile. 4419 4420**System capability**: SystemCapability.Multimedia.Media.AVRecorder 4421 4422| Name | Type | Mandatory| Description | 4423| ---------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | 4424| audioBitrate | number | No | Audio encoding bit rate. This parameter is mandatory for audio recording.<br>Supported bit rate ranges:<br>- Range [32000 - 500000] for the AAC encoding format.<br>- Range [64000 - 64000] for the G.711 μ-law encoding format.<br>- Range [8000, 16000, 32000, 40000, 48000, 56000, 64000, 80000, 96000, 112000, 128000, 160000, 192000, 224000, 256000, 320000] for the MP3 encoding format.<br>When the MP3 encoding format is used, the mapping between the sampling rate and bit rate is as follows:<br>- When the sampling rate is lower than 16 kHz, the bit rate range is [8 kbit/s - 64 kbit/s].<br>- When the sampling rate ranges from 16 kHz to 32 kHz, the bit rate range is [8 kbit/s - 160 kbit/s].<br>- When the sampling rate is greater than 32 kHz, the bit rate range is [32 kbit/s - 320 kbit/s].<br> **Atomic service API**: This API can be used in atomic services since API version 12.| 4425| audioChannels | number | No | Number of audio channels. This parameter is mandatory for audio recording.<br>- Range [1 - 8] for the AAC encoding format.<br>- Range [1 - 1] for the G.711 μ-law encoding format.<br>- Range [1 - 2] for the MP3 encoding format.<br> **Atomic service API**: This API can be used in atomic services since API version 12. | 4426| audioCodec | [CodecMimeType](#codecmimetype8) | No | Audio encoding format. This parameter is mandatory for audio recording. Currently, **AUDIO_AAC**, **AUDIO_MP3**, and **AUDIO_G711MU** are supported.<br> **Atomic service API**: This API can be used in atomic services since API version 12. | 4427| audioSampleRate | number | No | Audio sampling rate. This parameter is mandatory for audio recording.<br>Supported sampling rate ranges:<br>- Range [8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000, 64000, 88200, 96000] for the AAC encoding format.<br>- Range [8000 - 8000] for the G.711 μ-law encoding format.<br>- Range [8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000] for the MP3 encoding format.<br>Variable bit rate. The bit rate is for reference only.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 4428| fileFormat | [ContainerFormatType](#containerformattype8) | Yes | Container format of a file. This parameter is mandatory. Currently, the MP4, M4A, MP3, and WAV container formats are supported. The AUDIO_MP3 encoding format cannot be used in the MP4 container format.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 4429| videoBitrate | number | No | Video encoding bit rate. This parameter is mandatory for video recording. The value range is [10000 - 100000000]. | 4430| videoCodec | [CodecMimeType](#codecmimetype8) | No | Video encoding format. This parameter is mandatory for video recording. Currently, VIDEO_AVC is supported.| 4431| videoFrameWidth | number | No | Width of a video frame. This parameter is mandatory for video recording. The value range is [176 - 4096]. | 4432| videoFrameHeight | number | No | Height of a video frame. This parameter is mandatory for video recording. The value range is [144 - 4096]. | 4433| videoFrameRate | number | No | Video frame rate. This parameter is mandatory for video recording. The value range is [1 - 60]. | 4434| isHdr<sup>11+</sup> | boolean | No | HDR encoding. This parameter is optional for video recording. The default value is **false**, and there is no requirement on the encoding format. When **isHdr** is set to **true**, the encoding format must be **video/hevc**.| 4435| enableTemporalScale<sup>12+</sup> | boolean | No | Whether temporal layered encoding is supported. This parameter is optional for video recording. The default value is **false**. If this parameter is set to **true**, some frames in the video output streams can be skipped without being encoded.| 4436 4437## AudioSourceType<sup>9+</sup> 4438 4439Enumerates the audio source types for video recording. 4440 4441**System capability**: SystemCapability.Multimedia.Media.AVRecorder 4442 4443| Name | Value | Description | 4444| ------------------------- | ---- | ---------------------- | 4445| AUDIO_SOURCE_TYPE_DEFAULT | 0 | Default audio input source.| 4446| AUDIO_SOURCE_TYPE_MIC | 1 | Microphone audio input source.<br> **Atomic service API**: This API can be used in atomic services since API version 12.| 4447| AUDIO_SOURCE_TYPE_VOICE_RECOGNITION<sup>12+</sup> | 2 | Audio source in speech recognition scenarios.| 4448| AUDIO_SOURCE_TYPE_VOICE_COMMUNICATION<sup>12+</sup> | 7 | Voice communication source.| 4449| AUDIO_SOURCE_TYPE_VOICE_MESSAGE<sup>12+</sup> | 10 | Voice message source.| 4450| AUDIO_SOURCE_TYPE_CAMCORDER<sup>12+</sup> | 13 | Audio source in camera recording scenarios.| 4451 4452## VideoSourceType<sup>9+</sup> 4453 4454Enumerates the video source types for video recording. 4455 4456**System capability**: SystemCapability.Multimedia.Media.AVRecorder 4457 4458| Name | Value | Description | 4459| ----------------------------- | ---- | ------------------------------- | 4460| VIDEO_SOURCE_TYPE_SURFACE_YUV | 0 | The input surface carries raw data.| 4461| VIDEO_SOURCE_TYPE_SURFACE_ES | 1 | The input surface carries ES data. | 4462 4463## ContainerFormatType<sup>8+</sup> 4464 4465Enumerates the container format types (CFTs). 4466 4467**System capability**: SystemCapability.Multimedia.Media.Core 4468 4469| Name | Value | Description | 4470| ----------- | ----- | --------------------- | 4471| CFT_MPEG_4 | 'mp4' | Video container format MP4.| 4472| CFT_MPEG_4A | 'm4a' | Audio container format M4A.<br> **Atomic service API**: This API can be used in atomic services since API version 12.| 4473| CFT_MP3<sup>12+</sup> | 'mp3' | Audio container format MP3.| 4474| CFT_WAV<sup>12+</sup> | 'wav' | Audio container format WAV.| 4475 4476## Location 4477 4478Describes the geographical location of the recorded video. 4479 4480**System capability**: SystemCapability.Multimedia.Media.Core 4481 4482| Name | Type | Mandatory| Description | 4483| --------- | ------ | ---- | ---------------- | 4484| latitude | number | Yes | Latitude of the geographical location.| 4485| longitude | number | Yes | Longitude of the geographical location.| 4486 4487## EncoderInfo<sup>11+</sup> 4488 4489Describes the information about an encoder. 4490 4491**System capability**: SystemCapability.Multimedia.Media.AVRecorder 4492 4493| Name | Type | Readable| Writable| Description | 4494| ---------- | -------------------------------- | ---- | ---- | ------------------------------------------------------------ | 4495| mimeType | [CodecMimeType](#codecmimetype8) | Yes | No | MIME type of the encoder. | 4496| type | string | Yes | No | Encoder type. The value **audio** means an audio encoder, and **video** means a video encoder. | 4497| bitRate | [Range](#range11) | Yes | No | Bit rate range of the encoder, with the minimum and maximum bit rates specified. | 4498| frameRate | [Range](#range11) | Yes | No | Video frame rate range, with the minimum and maximum frame rates specified. This parameter is available only for video encoders. | 4499| width | [Range](#range11) | Yes | No | Video frame width range, with the minimum and maximum widths specified. This parameter is available only for video encoders. | 4500| height | [Range](#range11) | Yes | No | Video frame height range, with the minimum and maximum heights specified. This parameter is available only for video encoders. | 4501| channels | [Range](#range11) | Yes | No | Number of audio channels for the audio capturer, with the minimum and maximum numbers of audio channels specified. This parameter is available only for audio encoders. | 4502| sampleRate | Array\<number> | Yes | No | Audio sampling rate, including all available audio sampling rates. This parameter is available only for audio encoders.| 4503 4504## Range<sup>11+</sup> 4505 4506Describes a range. 4507 4508**System capability**: SystemCapability.Multimedia.Media.AVRecorder 4509 4510| Name| Type | Readable| Writable| Description | 4511| ---- | ------ | ---- | ---- | ------------ | 4512| min | number | Yes | No | Minimum value.| 4513| max | number | Yes | No | Maximum value.| 4514 4515## FileGenerationMode<sup>12+</sup> 4516 4517Enumerates the modes for creating media files. 4518 4519**System capability**: SystemCapability.Multimedia.Media.AVRecorder 4520 4521| Name | Value | Description | 4522| ----------------------------- | ---- | ------------------------------- | 4523| APP_CREATE | 0 | The application creates a media file in the sandbox.| 4524| AUTO_CREATE_CAMERA_SCENE | 1 | The system creates a media file. Currently, this mode takes effect only in camera recording scenarios. The URL set by the application is ignored.| 4525 4526## AVTranscoder<sup>12+</sup> 4527 4528A transcoding management class that provides APIs to transcode videos. Before calling any API in **AVTranscoder**, you must use **createAVTranscoder()** to create an **AVTranscoder** instance. 4529 4530For details about the AVTranscoder demo, see [Using AVTranscoder for Transcoding](../../media/media/using-avtranscoder-for-transcodering.md). 4531 4532### Attributes 4533 4534**System capability**: SystemCapability.Multimedia.Media.AVTranscoder 4535 4536| Name | Type | Read-Only| Optional| Description | 4537| ------- | ------------------------------------ | ---- | ---- | ------------------ | 4538| fdSrc<sup>12+</sup> | [AVFileDescriptor](#avfiledescriptor9) | No | No | Source media file descriptor, which specifies the data source.<br> **Example:**<br>There is a media file that stores continuous assets, the address offset is 0, and the byte length is 100. Its file descriptor is **AVFileDescriptor {fd = resourceHandle; offset = 0; length = 100; }**.<br>**NOTE**<br> - After the resource handle (FD) is transferred to an **AVTranscoder** instance, do not use the resource handle to perform other read and write operations, including but not limited to transferring this handle to other **AVPlayer**, **AVMetadataExtractor**, **AVImageGenerator**, or **AVTranscoder** instance. Competition occurs when multiple AVTranscoders use the same resource handle to read and write files at the same time, resulting in errors in obtaining data.| 4539| fdDst<sup>12+</sup> | number | No | No | Destination media file descriptor, which specifies the data source. After creating an **AVTranscoder** instance, you must set both **fdSrc** and **fdDst**.<br>**NOTE**<br> - After the resource handle (FD) is transferred to an **AVTranscoder** instance, do not use the resource handle to perform other read and write operations, including but not limited to transferring this handle to other **AVPlayer**, **AVMetadataExtractor**, **AVImageGenerator**, or **AVTranscoder** instance. Competition occurs when multiple AVTranscoders use the same resource handle to read and write files at the same time, resulting in errors in obtaining data.| 4540 4541### prepare<sup>12+</sup> 4542 4543prepare(config: AVTranscoderConfig): Promise\<void> 4544 4545Sets video transcoding parameters. This API uses a promise to return the result. 4546 4547**System capability**: SystemCapability.Multimedia.Media.AVTranscoder 4548 4549**Parameters** 4550 4551| Name| Type | Mandatory| Description | 4552| ------ | -------------------------------------- | ---- | -------------------------- | 4553| config | [AVTranscoderConfig](#avtranscoderconfig12) | Yes | Video transcoding parameters to set.| 4554 4555**Return value** 4556 4557| Type | Description | 4558| -------------- | ------------------------------------------ | 4559| Promise\<void> | Promise that returns no value.| 4560 4561**Error codes** 4562 4563For details about the error codes, see [Media Error Codes](errorcode-media.md). 4564 4565| ID| Error Message | 4566| -------- | -------------------------------------- | 4567| 401 | The parameter check failed. Return by promise. | 4568| 5400102 | Operation not allowed. Return by promise. | 4569| 5400105 | Service died. Return by promise. | 4570| 5400106 | Unsupported format. Returned by promise. | 4571 4572**Example** 4573 4574```ts 4575import { BusinessError } from '@kit.BasicServicesKit'; 4576 4577// Configure the parameters based on those supported by the hardware device. 4578let avTranscoderConfig: media.AVTranscoderConfig = { 4579 audioBitrate : 200000, 4580 audioCodec : media.CodecMimeType.AUDIO_AAC, 4581 fileFormat : media.ContainerFormatType.CFT_MPEG_4, 4582 videoBitrate : 3000000, 4583 videoCodec : media.CodecMimeType.VIDEO_AVC, 4584 videoFrameWidth : 1280, 4585 videoFrameHeight : 720, 4586} 4587 4588avTranscoder.prepare(avTranscoderConfig).then(() => { 4589 console.info('prepare success'); 4590}).catch((err: BusinessError) => { 4591 console.error('prepare failed and catch error is ' + err.message); 4592}); 4593``` 4594 4595### start<sup>12+</sup> 4596 4597start(): Promise\<void> 4598 4599Starts transcoding. This API uses a promise to return the result. 4600 4601This API can be called only after the [prepare()](#prepare12) API is called. 4602 4603**System capability**: SystemCapability.Multimedia.Media.AVTranscoder 4604 4605**Return value** 4606 4607| Type | Description | 4608| -------------- | ------------------------------------- | 4609| Promise\<void> | Promise that returns no value.| 4610 4611**Error codes** 4612 4613For details about the error codes, see [Media Error Codes](errorcode-media.md). 4614 4615| ID| Error Message | 4616| -------- | -------------------------------------- | 4617| 5400102 | Operation not allowed. Return by promise. | 4618| 5400103 | IO error. Return by promise. | 4619| 5400105 | Service died. Return by promise. | 4620 4621**Example** 4622 4623```ts 4624import { BusinessError } from '@kit.BasicServicesKit'; 4625 4626avTranscoder.start().then(() => { 4627 console.info('start AVTranscoder success'); 4628}).catch((err: BusinessError) => { 4629 console.error('start AVTranscoder failed and catch error is ' + err.message); 4630}); 4631``` 4632 4633### pause<sup>12+</sup> 4634 4635pause(): Promise\<void> 4636 4637Pauses transcoding. This API uses a promise to return the result. 4638 4639This API can be called only after the [start()](#start12) API is called. You can call [resume()](#resume12) to resume transcoding. 4640 4641**System capability**: SystemCapability.Multimedia.Media.AVTranscoder 4642 4643**Return value** 4644 4645| Type | Description | 4646| -------------- | ------------------------------------- | 4647| Promise\<void> | Promise that returns no value.| 4648 4649**Error codes** 4650 4651For details about the error codes, see [Media Error Codes](errorcode-media.md). 4652 4653| ID| Error Message | 4654| -------- | -------------------------------------- | 4655| 5400102 | Operation not allowed. Return by promise. | 4656| 5400103 | IO error. Return by promise. | 4657| 5400105 | Service died. Return by promise. | 4658 4659**Example** 4660 4661```ts 4662import { BusinessError } from '@kit.BasicServicesKit'; 4663 4664avTranscoder.pause().then(() => { 4665 console.info('pause AVTranscoder success'); 4666}).catch((err: BusinessError) => { 4667 console.error('pause AVTranscoder failed and catch error is ' + err.message); 4668}); 4669``` 4670 4671### resume<sup>12+</sup> 4672 4673resume(): Promise\<void> 4674 4675Resumes transcoding. This API uses a promise to return the result. 4676 4677This API can be called only after the [pause()](#pause12) API is called. 4678 4679**System capability**: SystemCapability.Multimedia.Media.AVTranscoder 4680 4681**Return value** 4682 4683| Type | Description | 4684| -------------- | ------------------------------------- | 4685| Promise\<void> | Promise that returns no value.| 4686 4687**Error codes** 4688 4689For details about the error codes, see [Media Error Codes](errorcode-media.md). 4690 4691| ID| Error Message | 4692| -------- | -------------------------------------- | 4693| 5400102 | Operation not allowed. Return by promise. | 4694| 5400103 | IO error. Return by promise. | 4695| 5400105 | Service died. Return by promise. | 4696 4697**Example** 4698 4699```ts 4700import { BusinessError } from '@kit.BasicServicesKit'; 4701 4702avTranscoder.resume().then(() => { 4703 console.info('resume AVTranscoder success'); 4704}).catch((err: BusinessError) => { 4705 console.error('resume AVTranscoder failed and catch error is ' + err.message); 4706}); 4707``` 4708 4709### cancel<sup>12+</sup> 4710 4711cancel(): Promise\<void> 4712 4713Cancels transcoding. This API uses a promise to return the result. 4714 4715This API can be called only after the [prepare()](#prepare12), [start()](#start12), [pause()](#pause12), or [resume()](#resume12) API is called. 4716 4717**System capability**: SystemCapability.Multimedia.Media.AVTranscoder 4718 4719**Return value** 4720 4721| Type | Description | 4722| -------------- | ------------------------------------- | 4723| Promise\<void> | Promise that returns no value.| 4724 4725**Error codes** 4726 4727For details about the error codes, see [Media Error Codes](errorcode-media.md). 4728 4729| ID| Error Message | 4730| -------- | -------------------------------------- | 4731| 5400102 | Operation not allowed. Return by promise. | 4732| 5400103 | IO error. Return by promise. | 4733| 5400105 | Service died. Return by promise. | 4734 4735**Example** 4736 4737```ts 4738import { BusinessError } from '@kit.BasicServicesKit'; 4739 4740avTranscoder.cancel().then(() => { 4741 console.info('cancel AVTranscoder success'); 4742}).catch((err: BusinessError) => { 4743 console.error('cancel AVTranscoder failed and catch error is ' + err.message); 4744}); 4745``` 4746 4747### release<sup>12+</sup> 4748 4749release(): Promise\<void> 4750 4751Releases the video transcoding resources. This API uses a promise to return the result. 4752 4753After the resources are released, you can no longer perform any operation on the **AVTranscoder** instance. 4754 4755**System capability**: SystemCapability.Multimedia.Media.AVTranscoder 4756 4757**Return value** 4758 4759| Type | Description | 4760| -------------- | ------------------------------------------- | 4761| Promise\<void> | Promise that returns no value.| 4762 4763**Error codes** 4764 4765For details about the error codes, see [Media Error Codes](errorcode-media.md). 4766 4767| ID| Error Message | 4768| -------- | --------------------------------- | 4769| 5400102 | Operation not allowed. Return by promise. | 4770| 5400105 | Service died. Return by promise. | 4771 4772**Example** 4773 4774```ts 4775import { BusinessError } from '@kit.BasicServicesKit'; 4776 4777avTranscoder.release().then(() => { 4778 console.info('release AVTranscoder success'); 4779}).catch((err: BusinessError) => { 4780 console.error('release AVTranscoder failed and catch error is ' + err.message); 4781}); 4782``` 4783 4784### on('progressUpdate')<sup>12+</sup> 4785 4786on(type: 'progressUpdate', callback: Callback\<number>): void 4787 4788Subscribes to transcoding progress updates. An application can subscribe to only one transcoding progress update event. When the application initiates multiple subscriptions to this event, the last subscription prevails. 4789 4790**System capability**: SystemCapability.Multimedia.Media.AVTranscoder 4791 4792**Parameters** 4793 4794| Name | Type | Mandatory| Description | 4795| -------- | -------- | ---- | ------------------------------------------------------------ | 4796| type | string | Yes | Event type, which is **'progressUpdate'** in this case. This event is triggered by the system during transcoding.| 4797| callback | [Callback](../apis-basic-services-kit/js-apis-base.md#callback) | Yes | Callback invoked when the event is triggered. **progress** is a number that indicates the current transcoding progress.| 4798 4799**Example** 4800 4801```ts 4802avTranscoder.on('progressUpdate', (progress: number) => { 4803 console.info('avTranscoder progressUpdate = ' + progress); 4804}); 4805``` 4806 4807### off('progressUpdate')<sup>12+</sup> 4808 4809off(type:'progressUpdate', callback?: Callback\<number>): void 4810 4811Unsubscribes from transcoding progress updates. 4812 4813**System capability**: SystemCapability.Multimedia.Media.AVTranscoder 4814 4815**Parameters** 4816 4817| Name| Type | Mandatory| Description | 4818| ------ | ------ | ---- | ------------------------------------------------------------ | 4819| type | string | Yes | Event type, which is **'progressUpdate'** in this case. This event can be triggered by both user operations and the system.| 4820| callback | [Callback](../apis-basic-services-kit/js-apis-base.md#callback) | No | Called that has been registered to listen for progress updates. You are advised to use the default value because only the last registered callback is retained in the current callback mechanism.| 4821 4822**Example** 4823 4824```ts 4825avTranscoder.off('progressUpdate'); 4826``` 4827 4828### on('error')<sup>12+</sup> 4829 4830on(type: 'error', callback: ErrorCallback): void 4831 4832Subscribes to AVTranscoder errors. If this event is reported, call [release()](#release12) to exit the transcoding. 4833 4834An application can subscribe to only one AVTranscoder error event. When the application initiates multiple subscriptions to this event, the last subscription prevails. 4835 4836**System capability**: SystemCapability.Multimedia.Media.AVTranscoder 4837 4838**Parameters** 4839 4840| Name | Type | Mandatory| Description | 4841| -------- | ------------- | ---- | ------------------------------------------------------------ | 4842| type | string | Yes | Event type, which is **'error'** in this case.<br>This event is triggered when an error occurs during recording.| 4843| callback | [ErrorCallback](../apis-basic-services-kit/js-apis-base.md#errorcallback) | Yes | Callback invoked when the event is triggered. | 4844 4845**Error codes** 4846 4847For details about the error codes, see [Media Error Codes](errorcode-media.md). 4848 4849| ID| Error Message | 4850| -------- | ------------------------------------------ | 4851| 401 | The parameter check failed. | 4852| 801 | Capability not supported. | 4853| 5400101 | No memory. | 4854| 5400102 | Operation not allowed. | 4855| 5400103 | I/O error. | 4856| 5400104 | Time out. | 4857| 5400105 | Service died. | 4858| 5400106 | Unsupport format. | 4859 4860**Example** 4861 4862```ts 4863import { BusinessError } from '@kit.BasicServicesKit'; 4864 4865avTranscoder.on('error', (err: BusinessError) => { 4866 console.info('case avTranscoder.on(error) called, errMessage is ' + err.message); 4867}); 4868``` 4869 4870### off('error')<sup>12+</sup> 4871 4872off(type:'error', callback?: ErrorCallback): void 4873 4874Unsubscribes from AVTranscoder errors. After the unsubscription, your application can no longer receive AVTranscoder errors. 4875 4876**System capability**: SystemCapability.Multimedia.Media.AVTranscoder 4877 4878**Parameters** 4879 4880| Name| Type | Mandatory| Description | 4881| ------ | ------ | ---- | ------------------------------------------------------------ | 4882| type | string | Yes | Event type, which is **'error'** in this case.<br>This event is triggered when an error occurs during transcoding.| 4883| callback | [ErrorCallback](../apis-basic-services-kit/js-apis-base.md#errorcallback) | No | Callback that has been registered to listen for AVTranscoder errors.| 4884 4885**Example** 4886 4887```ts 4888avTranscoder.off('error'); 4889``` 4890 4891### on('complete')<sup>12+</sup> 4892 4893on(type: 'complete', callback: Callback\<void>): void 4894 4895Subscribes to the event indicating that transcoding is complete. An application can subscribe to only one transcoding completion event. When the application initiates multiple subscriptions to this event, the last subscription prevails. 4896 4897When this event is reported, the current transcoding operation is complete. You can call [release()](#release12) to exit the transcoding. 4898 4899**System capability**: SystemCapability.Multimedia.Media.AVTranscoder 4900 4901**Parameters** 4902 4903| Name | Type | Mandatory| Description | 4904| -------- | -------- | ---- | ------------------------------------------------------------ | 4905| type | string | Yes | Event type, which is **'complete'** in this case. This event is triggered by the system during transcoding.| 4906| callback | [Callback](../apis-basic-services-kit/js-apis-base.md#callback) | Yes | Callback that has been registered to listen for transcoding completion events.| 4907 4908**Example** 4909 4910```ts 4911avTranscoder.on('complete', () => { 4912 console.info('avTranscoder complete'); 4913}); 4914``` 4915 4916### off('complete')<sup>12+</sup> 4917 4918off(type:'complete', callback?: Callback\<void>): void 4919 4920Unsubscribes from the event indicating that transcoding is complete. 4921 4922**System capability**: SystemCapability.Multimedia.Media.AVTranscoder 4923 4924**Parameters** 4925 4926| Name| Type | Mandatory| Description | 4927| ------ | ------ | ---- | ------------------------------------------------------------ | 4928| type | string | Yes | Event type, which is **'complete'** in this case. This event can be triggered by both user operations and the system.| 4929| callback | [Callback](../apis-basic-services-kit/js-apis-base.md#callback) | No | Callback invoked when the event is triggered.| 4930 4931**Example** 4932 4933```ts 4934avTranscoder.off('complete'); 4935``` 4936 4937## AVTranscoderConfig<sup>12+</sup> 4938 4939Describes the video transcoding parameters. 4940 4941**System capability**: SystemCapability.Multimedia.Media.AVTranscoder 4942 4943| Name | Type | Read-Only| Optional| Description | 4944| --------------- | ---------------------------------------- |---- | ---- | ------------------------------------------------------------ | 4945| audioBitrate | number | No| Yes| Bit rate of the output audio, in bit/s. The default value is 48 kbit/s.| 4946| audioCodec | [CodecMimeType](#codecmimetype8) | No| Yes | Encoding format of the output audio. Currently, only AAC is supported. | 4947| fileFormat | [ContainerFormatType](#containerformattype8) | No| No | Container format of the output video file. Currently, only MP4 is supported.| 4948| videoBitrate | number | No| Yes | Bit rate of the output video, in bit/s. The default bit rate depends on the resolution of the output video. The default bit rate is 1 Mbit/s for the resolution in the range [240p, 480P], 2 Mbit/s for the range (480P,720P], 4 Mbit/s for the range (720P,1080P], and 8 Mbit/s for 1080p or higher.| 4949| videoCodec | [CodecMimeType](#codecmimetype8) | No| Yes | Encoding format of the output video. Currently, only AVC and HEVC are supported.| 4950| videoFrameWidth | number | No| Yes | Width of the output video frame, in px. If this parameter is unspecified, the width of the source video frame is used.| 4951| videoFrameHeight | number | No| Yes | Height of the output video frame, in px. If this parameter is unspecified, the height of the source video frame is used.| 4952 4953 4954 4955## AVMetadataExtractor<sup>11+</sup> 4956 4957Provides APIs to obtain metadata from media resources. Before calling any API of **AVMetadataExtractor**, you must use [createAVMetadataExtractor()](#mediacreateavmetadataextractor11) to create an **AVMetadataExtractor** instance. 4958 4959For details about the demo for obtaining audio or video metadata, see [Obtaining Audio/Video Metadata](../../media/media/avmetadataextractor.md). 4960 4961### Attributes 4962 4963**System capability**: SystemCapability.Multimedia.Media.AVMetadataExtractor 4964 4965| Name | Type | Readable| Writable| Description | 4966| --------------------------------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | 4967| fdSrc<sup>11+</sup> | [AVFileDescriptor](#avfiledescriptor9) | Yes | Yes | Media file descriptor, which specifies the data source. Before obtaining metadata, you must set the data source through either **fdSrc** or **dataSrc**.<br> **Example:**<br>There is a media file that stores continuous assets, the address offset is 0, and the byte length is 100. Its file descriptor is **AVFileDescriptor {fd = resourceHandle; offset = 0; length = 100; }**.<br>**NOTE**<br> - After the resource handle (FD) is transferred to an **AVMetadataExtractor** instance, do not use the resource handle to perform other read and write operations, including but not limited to transferring this handle to other **AVPlayer**, **AVMetadataExtractor**, **AVImageGenerator**, or **AVTranscoder** instance. Competition occurs when multiple AVMetadataExtractor use the same resource handle to read and write files at the same time, resulting in errors in obtaining data.| 4968| dataSrc<sup>11+</sup> | [AVDataSrcDescriptor](#avdatasrcdescriptor10) | Yes | Yes | Streaming media resource descriptor, which specifies the data source. Before obtaining metadata, you must set the data source through either **fdSrc** or **dataSrc**.<br> When an application obtains a media file from the remote, you can set **dataSrc** to obtain the metadata before the application finishes the downloading.| 4969 4970### fetchMetadata<sup>11+</sup> 4971 4972fetchMetadata(callback: AsyncCallback\<AVMetadata>): void 4973 4974Obtains media metadata. This API uses an asynchronous callback to return the result. 4975 4976**System capability**: SystemCapability.Multimedia.Media.AVMetadataExtractor 4977 4978**Parameters** 4979 4980| Name | Type | Mandatory| Description | 4981| -------- | -------------------------------------------- | ---- | ----------------------------------- | 4982| callback | AsyncCallback\<[AVMetadata](#avmetadata11)> | Yes | Callback used to return the result, which is an **AVMetadata** instance.| 4983 4984**Error codes** 4985 4986For details about the error codes, see [Media Error Codes](errorcode-media.md). 4987 4988| ID| Error Message | 4989| -------- | ------------------------------------------ | 4990| 5400102 | Operation not allowed. Returned by callback. | 4991| 5400106 | Unsupported format. Returned by callback. | 4992 4993**Example** 4994 4995```ts 4996import { BusinessError } from '@kit.BasicServicesKit'; 4997 4998avMetadataExtractor.fetchMetadata((error: BusinessError, metadata: media.AVMetadata) => { 4999 if (error) { 5000 console.error(`Failed to fetch Metadata, err = ${JSON.stringify(error)}`); 5001 return; 5002 } 5003 console.info(`Succeeded in fetching Metadata, genre: ${metadata.genre}`); 5004}); 5005``` 5006 5007### fetchMetadata<sup>11+</sup> 5008 5009fetchMetadata(): Promise\<AVMetadata> 5010 5011Obtains media metadata. This API uses a promise to return the result. 5012 5013**System capability**: SystemCapability.Multimedia.Media.AVMetadataExtractor 5014 5015**Return value** 5016 5017| Type | Description | 5018| -------------- | ---------------------------------------- | 5019| Promise\<[AVMetadata](#avmetadata11)> | Promise used to return the result, which is an **AVMetadata** instance.| 5020 5021**Error codes** 5022 5023For details about the error codes, see [Media Error Codes](errorcode-media.md). 5024 5025| ID| Error Message | 5026| -------- | ----------------------------------------- | 5027| 5400102 | Operation not allowed. Returned by promise. | 5028| 5400106 | Unsupported format. Returned by promise. | 5029 5030**Example** 5031 5032```ts 5033import { BusinessError } from '@kit.BasicServicesKit'; 5034 5035avMetadataExtractor.fetchMetadata().then((metadata: media.AVMetadata) => { 5036 console.info(`Succeeded in fetching Metadata, genre: ${metadata.genre}`) 5037}).catch((error: BusinessError) => { 5038 console.error(`Failed to fetch Metadata, error message:${error.message}`); 5039}); 5040``` 5041 5042### fetchAlbumCover<sup>11+</sup> 5043 5044fetchAlbumCover(callback: AsyncCallback\<image.PixelMap>): void 5045 5046Obtains the cover of the audio album. This API uses an asynchronous callback to return the result. 5047 5048**System capability**: SystemCapability.Multimedia.Media.AVMetadataExtractor 5049 5050**Parameters** 5051 5052| Name | Type | Mandatory| Description | 5053| -------- | -------------------------------------------- | ---- | ----------------------------------- | 5054| callback | AsyncCallback\<[image.PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)> | Yes | Callback used to return the album cover.| 5055 5056**Error codes** 5057 5058For details about the error codes, see [Media Error Codes](errorcode-media.md). 5059 5060| ID| Error Message | 5061| -------- | ------------------------------------------ | 5062| 5400102 | Operation not allowed. Return by callback. | 5063| 5400106 | Unsupported format. Returned by callback. | 5064 5065**Example** 5066 5067```ts 5068import { BusinessError } from '@kit.BasicServicesKit'; 5069import { image } from '@kit.ImageKit'; 5070 5071let pixel_map : image.PixelMap | undefined = undefined; 5072 5073avMetadataExtractor.fetchAlbumCover((error: BusinessError, pixelMap: image.PixelMap) => { 5074 if (error) { 5075 console.error(`Failed to fetch AlbumCover, error = ${JSON.stringify(error)}`); 5076 return; 5077 } 5078 pixel_map = pixelMap; 5079}); 5080``` 5081 5082### fetchAlbumCover<sup>11+</sup> 5083 5084fetchAlbumCover(): Promise\<image.PixelMap> 5085 5086Obtains the cover of the audio album. This API uses a promise to return the result. 5087 5088**System capability**: SystemCapability.Multimedia.Media.AVMetadataExtractor 5089 5090**Return value** 5091 5092| Type | Description | 5093| -------------- | ---------------------------------------- | 5094| Promise\<[image.PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)> | Promise used to return the album cover.| 5095 5096**Error codes** 5097 5098For details about the error codes, see [Media Error Codes](errorcode-media.md). 5099 5100| ID| Error Message | 5101| -------- | ----------------------------------------- | 5102| 5400102 | Operation not allowed. Returned by promise. | 5103| 5400106 | Unsupported format. Returned by promise. | 5104 5105**Example** 5106 5107```ts 5108import { BusinessError } from '@kit.BasicServicesKit'; 5109import { image } from '@kit.ImageKit'; 5110 5111let pixel_map : image.PixelMap | undefined = undefined; 5112 5113avMetadataExtractor.fetchAlbumCover().then((pixelMap: image.PixelMap) => { 5114 pixel_map = pixelMap; 5115}).catch((error: BusinessError) => { 5116 console.error(`Failed to fetch AlbumCover, error message:${error.message}`); 5117}); 5118``` 5119 5120### release<sup>11+</sup> 5121 5122release(callback: AsyncCallback\<void>): void 5123 5124Releases this **AVMetadataExtractor** instance. This API uses an asynchronous callback to return the result. 5125 5126**System capability**: SystemCapability.Multimedia.Media.AVMetadataExtractor 5127 5128**Parameters** 5129 5130| Name | Type | Mandatory| Description | 5131| -------- | -------------------------------------------- | ---- | ----------------------------------- | 5132| callback | AsyncCallback\<void> | Yes |Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 5133 5134**Error codes** 5135 5136For details about the error codes, see [Media Error Codes](errorcode-media.md). 5137 5138| ID| Error Message | 5139| -------- | ------------------------------------------ | 5140| 5400102 | Operation not allowed. Returned by callback. | 5141 5142**Example** 5143 5144```ts 5145import { BusinessError } from '@kit.BasicServicesKit'; 5146 5147avMetadataExtractor.release((error: BusinessError) => { 5148 if (error) { 5149 console.error(`Failed to release, err = ${JSON.stringify(error)}`); 5150 return; 5151 } 5152 console.info(`Succeeded in releasing.`); 5153}); 5154``` 5155 5156### release<sup>11+</sup> 5157 5158release(): Promise\<void> 5159 5160Releases this **AVMetadataExtractor** instance. This API uses a promise to return the result. 5161 5162**System capability**: SystemCapability.Multimedia.Media.AVMetadataExtractor 5163 5164**Return value** 5165 5166| Type | Description | 5167| -------------- | ---------------------------------------- | 5168| Promise\<void> | Promise that returns no value.| 5169 5170**Error codes** 5171 5172For details about the error codes, see [Media Error Codes](errorcode-media.md). 5173 5174| ID| Error Message | 5175| -------- | ----------------------------------------- | 5176| 5400102 | Operation not allowed. Returned by promise. | 5177 5178**Example** 5179 5180```ts 5181import { BusinessError } from '@kit.BasicServicesKit'; 5182 5183avMetadataExtractor.release().then(() => { 5184 console.info(`Succeeded in releasing.`); 5185}).catch((error: BusinessError) => { 5186 console.error(`Failed to release, error message:${error.message}`); 5187}); 5188``` 5189 5190## AVMetadata<sup>11+</sup> 5191 5192Defines the audio and video metadata. Parameters that are not declared as read-only in [AVRecorderConfig](#avrecorderconfig9) can be used as input parameters for recording of [AVRecorder](#avrecorder9). 5193 5194**System capability**: SystemCapability.Multimedia.Media.AVMetadataExtractor 5195 5196| Name | Type | Mandatory| Description | 5197| ------ | ------ | ---- | ------------------------------------------------------------ | 5198| album | string | No | Title of the album. This parameter is read-only in the current version. | 5199| albumArtist | string | No | Artist of the album. This parameter is read-only in the current version.| 5200| artist | string | No | Artist of the media asset. This parameter is read-only in the current version.| 5201| author | string | No | Author of the media asset. This parameter is read-only in the current version.| 5202| dateTime | string | No | Time when the media asset is created. This parameter is read-only in the current version.| 5203| dateTimeFormat | string | No | Time when the media asset is created. The value is in the YYYY-MM-DD HH:mm:ss format. This parameter is read-only in the current version.| 5204| composer | string | No | Composer of the media asset. This parameter is read-only in the current version.| 5205| duration | string | No | Duration of the media asset. This parameter is read-only in the current version.| 5206| genre | string | No | Type or genre of the media asset.| 5207| hasAudio | string | No | Whether the media asset contains audio. This parameter is read-only in the current version.| 5208| hasVideo | string | No | Whether the media asset contains a video. This parameter is read-only in the current version.| 5209| mimeType | string | No | MIME type of the media asset. This parameter is read-only in the current version.| 5210| trackCount | string | No | Number of tracks of the media asset. This parameter is read-only in the current version.| 5211| sampleRate | string | No | Audio sampling rate, in Hz. This parameter is read-only in the current version.| 5212| title | string | No | Title of the media asset. This parameter is read-only in the current version. This parameter is read-only in the current version.| 5213| videoHeight | string | No | Video height, in px. This parameter is read-only in the current version.| 5214| videoWidth | string | No | Video width, in px. This parameter is read-only in the current version.| 5215| videoOrientation | string | No | Video rotation direction, in degrees.| 5216| hdrType<sup>12+</sup> | [HdrType](#hdrtype12) | No | HDR type of the media asset. This parameter is read-only in the current version.| 5217| location<sup>12+</sup> | [Location](#location) | No| Geographical location of the media asset.| 5218| customInfo<sup>12+</sup> | Record<string, string> | No| Custom key-value mappings obtained from **moov.meta.list**.| 5219 5220## HdrType<sup>12+</sup> 5221 5222Enumerates the HDR types. 5223 5224**System capability**: SystemCapability.Multimedia.Media.Core 5225 5226| Name | Value | Description | 5227| ------------------------- | ---- | ---------------------- | 5228| AV_HDR_TYPE_NONE | 0 | No HDR.| 5229| AV_HDR_TYPE_VIVID | 1 | HDR VIVID.| 5230 5231## media.createAudioPlayer<sup>(deprecated)</sup> 5232 5233createAudioPlayer(): AudioPlayer 5234 5235Creates an **AudioPlayer** instance in synchronous mode. 5236 5237> **NOTE** 5238> 5239> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [createAVPlayer](#mediacreateavplayer9) instead. 5240 5241**System capability**: SystemCapability.Multimedia.Media.AudioPlayer 5242 5243**Return value** 5244 5245| Type | Description | 5246| --------------------------- | ------------------------------------------------------------ | 5247| [AudioPlayer](#audioplayerdeprecated) | If the operation is successful, an **AudioPlayer** instance is returned; otherwise, **null** is returned. After the instance is created, you can start, pause, or stop audio playback.| 5248 5249**Example** 5250 5251```ts 5252let audioPlayer: media.AudioPlayer = media.createAudioPlayer(); 5253``` 5254 5255## media.createVideoPlayer<sup>(deprecated)</sup> 5256 5257createVideoPlayer(callback: AsyncCallback\<VideoPlayer>): void 5258 5259Creates a **VideoPlayer** instance. This API uses an asynchronous callback to return the result. 5260 5261> **NOTE** 5262> 5263> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [createAVPlayer](#mediacreateavplayer9) instead. 5264 5265**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 5266 5267**Parameters** 5268 5269| Name | Type | Mandatory| Description | 5270| -------- | ------------------------------------------ | ---- | ------------------------------------------------------------ | 5271| callback | AsyncCallback<[VideoPlayer](#videoplayerdeprecated)> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the **VideoPlayer** instance created; otherwise, **err** is an error object.| 5272 5273**Example** 5274 5275```ts 5276import { BusinessError } from '@kit.BasicServicesKit'; 5277 5278let videoPlayer: media.VideoPlayer; 5279media.createVideoPlayer((error: BusinessError, video: media.VideoPlayer) => { 5280 if (video != null) { 5281 videoPlayer = video; 5282 console.info('Succeeded in creating VideoPlayer'); 5283 } else { 5284 console.error(`Failed to create VideoPlayer, error:${error}`); 5285 } 5286}); 5287``` 5288 5289## media.createVideoPlayer<sup>(deprecated)</sup> 5290 5291createVideoPlayer(): Promise\<VideoPlayer> 5292 5293Creates a **VideoPlayer** instance. This API uses a promise to return the result. 5294 5295> **NOTE** 5296> 5297> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [createAVPlayer](#mediacreateavplayer9-1) instead. 5298 5299**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 5300 5301**Return value** 5302 5303| Type | Description | 5304| ------------------------------------ | ------------------------------------------------------------ | 5305| Promise<[VideoPlayer](#videoplayerdeprecated)> | Promise used to return the result. If the operation is successful, a **VideoPlayer** instance is returned; otherwise, **null** is returned. The instance can be used to manage and play video.| 5306 5307**Example** 5308 5309```ts 5310import { BusinessError } from '@kit.BasicServicesKit'; 5311 5312let videoPlayer: media.VideoPlayer; 5313media.createVideoPlayer().then((video: media.VideoPlayer) => { 5314 if (video != null) { 5315 videoPlayer = video; 5316 console.info('Succeeded in creating VideoPlayer'); 5317 } else { 5318 console.error('Failed to create VideoPlayer'); 5319 } 5320}).catch((error: BusinessError) => { 5321 console.error(`Failed to create VideoPlayer, error:${error}`); 5322}); 5323``` 5324 5325## media.createAudioRecorder<sup>(deprecated)</sup> 5326 5327createAudioRecorder(): AudioRecorder 5328 5329Creates an **AudioRecorder** instance to control audio recording. 5330Only one **AudioRecorder** instance can be created per device. 5331 5332> **NOTE** 5333> 5334> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [createAVRecorder](#mediacreateavrecorder9) instead. 5335 5336**System capability**: SystemCapability.Multimedia.Media.AudioRecorder 5337 5338**Return value** 5339 5340| Type | Description | 5341| ------------------------------- | ------------------------------------------------------------ | 5342| [AudioRecorder](#audiorecorderdeprecated) | If the operation is successful, an **AudioRecorder** instance is returned; otherwise, **null** is returned. The instance can be used to record audio.| 5343 5344**Example** 5345 5346```ts 5347let audioRecorder: media.AudioRecorder = media.createAudioRecorder(); 5348``` 5349 5350## MediaErrorCode<sup>(deprecated)</sup> 5351 5352Enumerates the media error codes. 5353 5354> **NOTE** 5355> 5356> This enum is supported since API version 8 and deprecated since API version 11. You are advised to use [Media Error Codes](#averrorcode9) instead. 5357 5358**System capability**: SystemCapability.Multimedia.Media.Core 5359 5360| Name | Value | Description | 5361| -------------------------- | ---- | -------------------------------------- | 5362| MSERR_OK | 0 | The operation is successful. | 5363| MSERR_NO_MEMORY | 1 | Failed to allocate memory. The system may have no available memory.| 5364| MSERR_OPERATION_NOT_PERMIT | 2 | No permission to perform the operation. | 5365| MSERR_INVALID_VAL | 3 | Invalid input parameter. | 5366| MSERR_IO | 4 | An I/O error occurs. | 5367| MSERR_TIMEOUT | 5 | The operation times out. | 5368| MSERR_UNKNOWN | 6 | An unknown error occurs. | 5369| MSERR_SERVICE_DIED | 7 | Invalid server. | 5370| MSERR_INVALID_STATE | 8 | The operation is not allowed in the current state. | 5371| MSERR_UNSUPPORTED | 9 | The operation is not supported in the current version. | 5372 5373## AudioPlayer<sup>(deprecated)</sup> 5374 5375> **NOTE** 5376> 5377> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayer](#avplayer9) instead. 5378 5379Provides APIs to manage and play audio. Before calling any API in **AudioPlayer**, you must use [createAudioPlayer()](#mediacreateaudioplayerdeprecated) to create an **AudioPlayer** instance. 5380 5381### Attributes<sup>(deprecated)</sup> 5382 5383**System capability**: SystemCapability.Multimedia.Media.AudioPlayer 5384 5385| Name | Type | Read-Only| Optional| Description | 5386| ------------------------------- | ------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | 5387| src | string | No | No | Audio file URI. The mainstream audio formats (M4A, AAC, MP3, OGG, WAV, and AMR) are supported.<br>**Example of supported URLs**:<br>1. FD: fd://xx<br><br>2. HTTP: http\://xx<br>3. HTTPS: https\://xx<br>4. HLS: http\://xx or https\://xx<br>**Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.INTERNET| 5388| fdSrc<sup>9+</sup> | [AVFileDescriptor](#avfiledescriptor9) | No | No | Description of the audio file. This attribute is required when audio assets of an application are continuously stored in a file.<br>**Example:**<br>Assume that a music file that stores continuous music assets consists of the following:<br>Music 1 (address offset: 0, byte length: 100)<br>Music 2 (address offset: 101; byte length: 50)<br>Music 3 (address offset: 151, byte length: 150)<br>1. To play music 1: AVFileDescriptor {fd = resource handle; offset = 0; length = 100; }<br>2. To play music 2: AVFileDescriptor {fd = resource handle; offset = 101; length = 50; }<br>3. To play music 3: AVFileDescriptor {fd = resource handle; offset = 151; length = 150; }<br>To play an independent music file, use **src=fd://xx**.<br>| 5389| loop | boolean | No | No | Whether to loop audio playback. The value **true** means to loop audio playback, and **false** means the opposite. | 5390| audioInterruptMode<sup>9+</sup> | [audio.InterruptMode](../apis-audio-kit/js-apis-audio.md#interruptmode9) | Yes | Yes | Audio interruption mode. | 5391| currentTime | number | Yes | No | Current audio playback position, in ms. | 5392| duration | number | Yes | No | Audio duration, in ms. | 5393| state | [AudioState](#audiostatedeprecated) | Yes | No | Audio playback state. This state cannot be used as the condition for triggering the call of **play()**, **pause()**, or **stop()**.| 5394 5395### play<sup>(deprecated)</sup> 5396 5397play(): void 5398 5399Starts to play an audio asset. This API can be called only after the **'dataLoad'** event is triggered. 5400 5401> **NOTE** 5402> 5403> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayer.play](#play9) instead. 5404 5405**System capability**: SystemCapability.Multimedia.Media.AudioPlayer 5406 5407**Example** 5408 5409```ts 5410audioPlayer.on('play', () => { // Set the 'play' event callback. 5411 console.info('audio play called'); 5412}); 5413audioPlayer.play(); 5414``` 5415 5416### pause<sup>(deprecated)</sup> 5417 5418pause(): void 5419 5420Pauses audio playback. 5421 5422> **NOTE** 5423> 5424> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayer.pause](#pause9) instead. 5425 5426**System capability**: SystemCapability.Multimedia.Media.AudioPlayer 5427 5428**Example** 5429 5430```ts 5431audioPlayer.on('pause', () => { // Set the 'pause' event callback. 5432 console.info('audio pause called'); 5433}); 5434audioPlayer.pause(); 5435``` 5436 5437### stop<sup>(deprecated)</sup> 5438 5439stop(): void 5440 5441Stops audio playback. 5442 5443> **NOTE** 5444> 5445> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayer.stop](#stop9) instead. 5446 5447**System capability**: SystemCapability.Multimedia.Media.AudioPlayer 5448 5449**Example** 5450 5451```ts 5452audioPlayer.on('stop', () => { // Set the 'stop' event callback. 5453 console.info('audio stop called'); 5454}); 5455audioPlayer.stop(); 5456``` 5457 5458### reset<sup>(deprecated)</sup> 5459 5460reset(): void 5461 5462Resets the audio asset to be played. 5463 5464> **NOTE** 5465> 5466> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [AVPlayer.reset](#reset9) instead. 5467 5468**System capability**: SystemCapability.Multimedia.Media.AudioPlayer 5469 5470**Example** 5471 5472```ts 5473audioPlayer.on('reset', () => { // Set the 'reset' event callback. 5474 console.info('audio reset called'); 5475}); 5476audioPlayer.reset(); 5477``` 5478 5479### seek<sup>(deprecated)</sup> 5480 5481seek(timeMs: number): void 5482 5483Seeks to the specified playback position. 5484 5485> **NOTE** 5486> 5487> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayer.seek](#seek9) instead. 5488 5489**System capability**: SystemCapability.Multimedia.Media.AudioPlayer 5490 5491**Parameters** 5492 5493| Name| Type | Mandatory| Description | 5494| ------ | ------ | ---- | ----------------------------------------------------------- | 5495| timeMs | number | Yes | Position to seek to, in ms. The value range is [0, duration].| 5496 5497**Example** 5498 5499```ts 5500audioPlayer.on('timeUpdate', (seekDoneTime: number) => { // Set the 'timeUpdate' event callback. 5501 if (seekDoneTime == null) { 5502 console.error('Failed to seek'); 5503 return; 5504 } 5505 console.info('Succeeded in seek. seekDoneTime: ' + seekDoneTime); 5506}); 5507audioPlayer.seek(30000); // Seek to 30000 ms. 5508``` 5509 5510### setVolume<sup>(deprecated)</sup> 5511 5512setVolume(vol: number): void 5513 5514Sets the volume. 5515 5516> **NOTE** 5517> 5518> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayer.setVolume](#setvolume9) instead. 5519 5520**System capability**: SystemCapability.Multimedia.Media.AudioPlayer 5521 5522**Parameters** 5523 5524| Name| Type | Mandatory| Description | 5525| ------ | ------ | ---- | ------------------------------------------------------------ | 5526| vol | number | Yes | Relative volume. The value ranges from 0.00 to 1.00. The value **1.00** indicates the maximum volume (100%).| 5527 5528**Example** 5529 5530```ts 5531audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback. 5532 console.info('audio volumeChange called'); 5533}); 5534audioPlayer.setVolume(1); // Set the volume to 100%. 5535``` 5536 5537### release<sup>(deprecated)</sup> 5538 5539release(): void 5540 5541Releases the audio playback resources. 5542 5543> **NOTE** 5544> 5545> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayer.release](#release9) instead. 5546 5547**System capability**: SystemCapability.Multimedia.Media.AudioPlayer 5548 5549**Example** 5550 5551```ts 5552audioPlayer.release(); 5553audioPlayer = undefined; 5554``` 5555 5556### getTrackDescription<sup>(deprecated)</sup> 5557 5558getTrackDescription(callback: AsyncCallback\<Array\<MediaDescription>>): void 5559 5560Obtains the audio track information. It can be called only after the **'dataLoad'** event is triggered. This API uses an asynchronous callback to return the result. 5561 5562> **NOTE** 5563> 5564> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.getTrackDescription](#gettrackdescription9) instead. 5565 5566**System capability**: SystemCapability.Multimedia.Media.AudioPlayer 5567 5568**Parameters** 5569 5570| Name | Type | Mandatory| Description | 5571| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------ | 5572| callback | AsyncCallback\<Array\<[MediaDescription](#mediadescription8)>> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the MediaDescription array obtained; otherwise, **err** is an error object.| 5573 5574**Example** 5575 5576```ts 5577import { BusinessError } from '@kit.BasicServicesKit'; 5578 5579audioPlayer.getTrackDescription((error: BusinessError, arrList: Array<media.MediaDescription>) => { 5580 if (arrList != null) { 5581 console.info('Succeeded in getting TrackDescription'); 5582 } else { 5583 console.error(`Failed to get TrackDescription, error:${error}`); 5584 } 5585}); 5586``` 5587 5588### getTrackDescription<sup>(deprecated)</sup> 5589 5590getTrackDescription(): Promise\<Array\<MediaDescription>> 5591 5592Obtains the audio track information. It can be called only after the **'dataLoad'** event is triggered. This API uses a promise to return the result. 5593 5594> **NOTE** 5595> 5596> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.getTrackDescription](#gettrackdescription9-1) instead. 5597 5598**System capability**: SystemCapability.Multimedia.Media.AudioPlayer 5599 5600**Return value** 5601 5602| Type | Description | 5603| ------------------------------------------------------ | ----------------------------------------------- | 5604| Promise<Array<[MediaDescription](#mediadescription8)>> | Promise used to return a **MediaDescription** array, which records the audio track information.| 5605 5606**Example** 5607 5608```ts 5609import { BusinessError } from '@kit.BasicServicesKit'; 5610 5611audioPlayer.getTrackDescription().then((arrList: Array<media.MediaDescription>) => { 5612 console.info('Succeeded in getting TrackDescription'); 5613}).catch((error: BusinessError) => { 5614 console.error(`Failed to get TrackDescription, error:${error}`); 5615}); 5616``` 5617 5618### on('bufferingUpdate')<sup>(deprecated)</sup> 5619 5620on(type: 'bufferingUpdate', callback: (infoType: BufferingInfoType, value: number) => void): void 5621 5622Subscribes to the audio buffering update event. This API works only under online playback. 5623 5624> **NOTE** 5625> 5626> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.on('bufferingUpdate')](#onbufferingupdate9) instead. 5627 5628**System capability**: SystemCapability.Multimedia.Media.AudioPlayer 5629 5630**Parameters** 5631 5632| Name | Type | Mandatory| Description | 5633| -------- | -------- | ---- | ------------------------------------------------------------ | 5634| type | string | Yes | Event type, which is **'bufferingUpdate'** in this case. | 5635| callback | function | Yes | Callback invoked when the event is triggered.<br>The value of [BufferingInfoType](#bufferinginfotype8) is fixed at **0**.| 5636 5637**Example** 5638 5639```ts 5640audioPlayer.on('bufferingUpdate', (infoType: media.BufferingInfoType, value: number) => { 5641 console.info('audio bufferingInfo type: ' + infoType); 5642 console.info('audio bufferingInfo value: ' + value); 5643}); 5644``` 5645 5646### on('play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange')<sup>(deprecated)</sup> 5647 5648on(type: 'play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange', callback: () => void): void 5649 5650Subscribes to the audio playback events. 5651 5652> **NOTE** 5653> 5654> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayer.on('stateChange')](#onstatechange9) instead. 5655 5656**System capability**: SystemCapability.Multimedia.Media.AudioPlayer 5657 5658**Parameters** 5659 5660| Name | Type | Mandatory| Description | 5661| -------- | ---------- | ---- | ------------------------------------------------------------ | 5662| type | string | Yes | Event type. The following events are supported:<br>- 'play': triggered when the [play()](#playdeprecated) API is called and audio playback starts.<br>- 'pause': triggered when the [pause()](#pausedeprecated) API is called and audio playback is paused.<br>- 'stop': triggered when the [stop()](#stopdeprecated) API is called and audio playback stops.<br>- 'reset': triggered when the [reset()](#resetdeprecated) API is called and audio playback is reset.<br>- 'dataLoad': triggered when the audio data is loaded, that is, when the **src** attribute is configured.<br>- 'finish': triggered when the audio playback is finished.<br>- 'volumeChange': triggered when the [setVolume()](#setvolumedeprecated) API is called and the playback volume is changed.| 5663| callback | () => void | Yes | Callback invoked when the event is triggered. | 5664 5665**Example** 5666 5667```ts 5668import { fileIo as fs } from '@kit.CoreFileKit'; 5669import { BusinessError } from '@kit.BasicServicesKit'; 5670 5671let audioPlayer: media.AudioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. 5672audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. 5673 console.info('audio set source called'); 5674 audioPlayer.play(); // Start the playback and trigger the 'play' event callback. 5675}); 5676audioPlayer.on('play', () => { // Set the 'play' event callback. 5677 console.info('audio play called'); 5678 audioPlayer.seek(30000); // Call the seek() API and trigger the 'timeUpdate' event callback. 5679}); 5680audioPlayer.on('pause', () => { // Set the 'pause' event callback. 5681 console.info('audio pause called'); 5682 audioPlayer.stop(); // Stop the playback and trigger the 'stop' event callback. 5683}); 5684audioPlayer.on('reset', () => { // Set the 'reset' event callback. 5685 console.info('audio reset called'); 5686 audioPlayer.release(); // Release the AudioPlayer instance. 5687 audioPlayer = undefined; 5688}); 5689audioPlayer.on('timeUpdate', (seekDoneTime: number) => { // Set the 'timeUpdate' event callback. 5690 if (seekDoneTime == null) { 5691 console.error('Failed to seek'); 5692 return; 5693 } 5694 console.info('Succeeded in seek, and seek time is ' + seekDoneTime); 5695 audioPlayer.setVolume(0.5); // Set the volume to 50% and trigger the 'volumeChange' event callback. 5696}); 5697audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback. 5698 console.info('audio volumeChange called'); 5699 audioPlayer.pause(); // Pause the playback and trigger the 'pause' event callback. 5700}); 5701audioPlayer.on('finish', () => { // Set the 'finish' event callback. 5702 console.info('audio play finish'); 5703 audioPlayer.stop(); // Stop the playback and trigger the 'stop' event callback. 5704}); 5705audioPlayer.on('error', (error: BusinessError) => { // Set the 'error' event callback. 5706 console.error(`audio error called, error: ${error}`); 5707}); 5708 5709// Set the FD (local playback) of the audio file selected by the user. 5710let fdPath = 'fd://'; 5711// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/accounts/account_0/appdata" command. 5712let path = '/data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3'; 5713fs.open(path).then((file) => { 5714 fdPath = fdPath + '' + file.fd; 5715 console.info('Succeeded in opening fd, fd is' + fdPath); 5716 audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback. 5717}, (err: BusinessError) => { 5718 console.error('Failed to open fd, err is' + err); 5719}).catch((err: BusinessError) => { 5720 console.error('Failed to open fd, err is' + err); 5721}); 5722``` 5723 5724### on('timeUpdate')<sup>(deprecated)</sup> 5725 5726on(type: 'timeUpdate', callback: Callback\<number>): void 5727 5728Subscribes to the **'timeUpdate'** event. This event is reported every second when the audio playback is in progress. 5729 5730> **NOTE** 5731> 5732> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayer.on('timeUpdate')](#ontimeupdate9) instead. 5733 5734**System capability**: SystemCapability.Multimedia.Media.AudioPlayer 5735 5736**Parameters** 5737 5738| Name | Type | Mandatory| Description | 5739| -------- | ----------------- | ---- | ------------------------------------------------------------ | 5740| type | string | Yes | Event type, which is **'timeUpdate'** in this case.<br>The **'timeUpdate'** event is triggered when the audio playback starts after an audio playback timestamp update.| 5741| callback | Callback\<number> | Yes | Callback invoked when the event is triggered. The input parameter is the updated timestamp. | 5742 5743**Example** 5744 5745```ts 5746audioPlayer.on('timeUpdate', (newTime: number) => { // Set the 'timeUpdate' event callback. 5747 if (newTime == null) { 5748 console.error('Failed to do timeUpadate'); 5749 return; 5750 } 5751 console.info('Succeeded in doing timeUpadate. seekDoneTime: ' + newTime); 5752}); 5753audioPlayer.play(); // The 'timeUpdate' event is triggered when the playback starts. 5754``` 5755 5756### on('audioInterrupt')<sup>(deprecated)</sup> 5757 5758on(type: 'audioInterrupt', callback: (info: audio.InterruptEvent) => void): void 5759 5760Subscribes to the audio interruption event. For details, see [audio.InterruptEvent](../apis-audio-kit/js-apis-audio.md#interruptevent9). 5761 5762> **NOTE** 5763> 5764> This API is supported in API version 9 and deprecated since API version 9. You are advised to use [AVPlayer.on('audioInterrupt')](#onaudiointerrupt9) instead. 5765 5766**System capability**: SystemCapability.Multimedia.Media.AudioPlayer 5767 5768**Parameters** 5769 5770| Name | Type | Mandatory| Description | 5771| -------- | ------------------------------------------------------------ | ---- | -------------------------------------------------------- | 5772| type | string | Yes | Event type, which is **'audioInterrupt'** in this case.| 5773| callback | function | Yes | Callback invoked when the event is triggered. | 5774 5775**Example** 5776 5777```ts 5778import { audio } from '@kit.AudioKit'; 5779 5780audioPlayer.on('audioInterrupt', (info: audio.InterruptEvent) => { 5781 console.info('audioInterrupt called,and InterruptEvent info is:' + info) 5782}) 5783``` 5784 5785### on('error')<sup>(deprecated)</sup> 5786 5787on(type: 'error', callback: ErrorCallback): void 5788 5789Subscribes to audio playback error events. After an error event is reported, you must handle the event and exit the playback. 5790 5791> **NOTE** 5792> 5793> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayer.on('error')](#onerror9) instead. 5794 5795**System capability**: SystemCapability.Multimedia.Media.AudioPlayer 5796 5797**Parameters** 5798 5799| Name | Type | Mandatory| Description | 5800| -------- | ------------- | ---- | ------------------------------------------------------------ | 5801| type | string | Yes | Event type, which is **'error'** in this case.<br>This event is triggered when an error occurs during audio playback.| 5802| callback | [ErrorCallback](../apis-basic-services-kit/js-apis-base.md#errorcallback) | Yes | Callback invoked when the event is triggered. | 5803 5804**Example** 5805 5806```ts 5807import { BusinessError } from '@kit.BasicServicesKit'; 5808 5809audioPlayer.on('error', (error: BusinessError) => { // Set the 'error' event callback. 5810 console.error(`audio error called, error: ${error}`); 5811}); 5812audioPlayer.setVolume(3); // Set volume to an invalid value to trigger the 'error' event. 5813``` 5814 5815## AudioState<sup>(deprecated)</sup> 5816 5817type AudioState = 'idle' | 'playing' | 'paused' | 'stopped' | 'error' 5818 5819Enumerates the audio playback states. You can obtain the state through the **state** attribute. 5820 5821> **NOTE** 5822> 5823> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayerState](#avplayerstate9) instead. 5824 5825**System capability**: SystemCapability.Multimedia.Media.AudioPlayer 5826 5827| Type | Description | 5828| ------- | ---------------------------------------------- | 5829| 'idle' | No audio playback is in progress. The audio player is in this state after the **'dataload'** or **'reset'** event is triggered.| 5830| 'playing' | Audio playback is in progress. The audio player is in this state after the **'play'** event is triggered. | 5831| 'paused' | Audio playback is paused. The audio player is in this state after the **'pause'** event is triggered. | 5832| 'stopped' | Audio playback is stopped. The audio player is in this state after the **'stop'** event is triggered. | 5833| 'error' | Audio playback is in the error state. | 5834 5835## VideoPlayer<sup>(deprecated)</sup> 5836 5837> **NOTE** 5838> 5839> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer](#avplayer9) instead. 5840 5841Provides APIs to manage and play video. Before calling any API of **VideoPlayer**, you must use [createVideoPlayer()](#mediacreatevideoplayerdeprecated) to create a **VideoPlayer** instance. 5842 5843### Attributes 5844 5845**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 5846 5847| Name | Type | Read-Only| Optional| Description | 5848| ------------------------------- | ------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | 5849| url<sup>8+</sup> | string | No | No | Video URL. The video formats MP4, MPEG-TS, and MKV are supported.<br>**Example of supported URLs**:<br>1. FD: fd://xx<br><br>2. HTTP: http\://xx<br>3. HTTPS: https\://xx<br>4. HLS: http\://xx or https\://xx<br>5. File type: file\://xx<br>**NOTE**<br>WebM is no longer supported since API version 11.| 5850| fdSrc<sup>9+</sup> | [AVFileDescriptor](#avfiledescriptor9) | No | No | Description of a video file. This attribute is required when video assets of an application are continuously stored in a file.<br>**Example:**<br>Assume that a music file that stores continuous music assets consists of the following:<br>Video 1 (address offset: 0, byte length: 100)<br>Video 2 (address offset: 101; byte length: 50)<br>Video 3 (address offset: 151, byte length: 150)<br>1. To play video 1: AVFileDescriptor {fd = resource handle; offset = 0; length = 100; }<br>2. To play video 2: AVFileDescriptor {fd = resource handle; offset = 101; length = 50; }<br>3. To play video 3: AVFileDescriptor {fd = resource handle; offset = 151; length = 150; }<br>To play an independent video file, use **src=fd://xx**.<br>| 5851| loop<sup>8+</sup> | boolean | No | No | Whether to loop video playback. The value **true** means to loop video playback, and **false** means the opposite. | 5852| videoScaleType<sup>9+</sup> | [VideoScaleType](#videoscaletype9) | No | Yes | Video scale type. The default value is **VIDEO_SCALE_TYPE_FIT**. | 5853| audioInterruptMode<sup>9+</sup> | [audio.InterruptMode](../apis-audio-kit/js-apis-audio.md#interruptmode9) | No | Yes | Audio interruption mode. | 5854| currentTime<sup>8+</sup> | number | Yes | No | Current video playback position, in ms. | 5855| duration<sup>8+</sup> | number | Yes | No | Video duration, in ms. The value **-1** indicates the live mode. | 5856| state<sup>8+</sup> | [VideoPlayState](#videoplaystatedeprecated) | Yes | No | Video playback state. | 5857| width<sup>8+</sup> | number | Yes | No | Video width, in px. | 5858| height<sup>8+</sup> | number | Yes | No | Video height, in px. | 5859 5860### setDisplaySurface<sup>(deprecated)</sup> 5861 5862setDisplaySurface(surfaceId: string, callback: AsyncCallback\<void>): void 5863 5864Sets a surface ID. This API uses an asynchronous callback to return the result. 5865 5866*Note: **SetDisplaySurface** must be called between the URL setting and the calling of **prepare**. A surface must be set for video streams without audio. Otherwise, the calling of **prepare** fails. 5867 5868> **NOTE** 5869> 5870> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.surfaceId](#attributes) instead. 5871 5872**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 5873 5874**Parameters** 5875 5876| Name | Type | Mandatory| Description | 5877| --------- | -------------------- | ---- | ------------------------- | 5878| surfaceId | string | Yes | Surface ID to set. | 5879| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the setting is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 5880 5881**Example** 5882 5883```ts 5884import { BusinessError } from '@kit.BasicServicesKit'; 5885 5886let surfaceId: string = ''; 5887videoPlayer.setDisplaySurface(surfaceId, (err: BusinessError) => { 5888 if (err) { 5889 console.error('Failed to set DisplaySurface!'); 5890 } else { 5891 console.info('Succeeded in setting DisplaySurface!'); 5892 } 5893}); 5894``` 5895 5896### setDisplaySurface<sup>(deprecated)</sup> 5897 5898setDisplaySurface(surfaceId: string): Promise\<void> 5899 5900Sets a surface ID. This API uses a promise to return the result. 5901 5902*Note: **SetDisplaySurface** must be called between the URL setting and the calling of **prepare**. A surface must be set for video streams without audio. Otherwise, the calling of **prepare** fails. 5903 5904> **NOTE** 5905> 5906> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.surfaceId](#attributes) instead. 5907 5908**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 5909 5910**Parameters** 5911 5912| Name | Type | Mandatory| Description | 5913| --------- | ------ | ---- | --------- | 5914| surfaceId | string | Yes | Surface ID to set.| 5915 5916**Return value** 5917 5918| Type | Description | 5919| -------------- | ------------------------------ | 5920| Promise\<void> | Promise that returns no value.| 5921 5922**Example** 5923 5924```ts 5925import { BusinessError } from '@kit.BasicServicesKit'; 5926 5927let surfaceId: string = ''; 5928videoPlayer.setDisplaySurface(surfaceId).then(() => { 5929 console.info('Succeeded in setting DisplaySurface'); 5930}).catch((error: BusinessError) => { 5931 console.error(`video catchCallback, error:${error}`); 5932}); 5933``` 5934 5935### prepare<sup>(deprecated)</sup> 5936 5937prepare(callback: AsyncCallback\<void>): void 5938 5939Prepares for video playback. This API uses an asynchronous callback to return the result. 5940 5941> **NOTE** 5942> 5943> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.prepare](#prepare9) instead. 5944 5945**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 5946 5947**Parameters** 5948 5949| Name | Type | Mandatory| Description | 5950| -------- | -------------------- | ---- | ------------------------ | 5951| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 5952 5953**Example** 5954 5955```ts 5956import { BusinessError } from '@kit.BasicServicesKit'; 5957 5958videoPlayer.prepare((err: BusinessError) => { 5959 if (err) { 5960 console.error('Failed to prepare!'); 5961 } else { 5962 console.info('Succeeded in preparing!'); 5963 } 5964}); 5965``` 5966 5967### prepare<sup>(deprecated)</sup> 5968 5969prepare(): Promise\<void> 5970 5971Prepares for video playback. This API uses a promise to return the result. 5972 5973> **NOTE** 5974> 5975> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.prepare](#prepare9-1) instead. 5976 5977**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 5978 5979**Return value** 5980 5981| Type | Description | 5982| -------------- | ----------------------------- | 5983| Promise\<void> | Promise that returns no value.| 5984 5985**Example** 5986 5987```ts 5988import { BusinessError } from '@kit.BasicServicesKit'; 5989 5990videoPlayer.prepare().then(() => { 5991 console.info('Succeeded in preparing'); 5992}).catch((error: BusinessError) => { 5993 console.error(`video catchCallback, error:${error}`); 5994}); 5995``` 5996 5997### play<sup>(deprecated)</sup> 5998 5999play(callback: AsyncCallback\<void>): void 6000 6001Starts video playback. This API uses an asynchronous callback to return the result. 6002 6003> **NOTE** 6004> 6005> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.play](#play9) instead. 6006 6007**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6008 6009**Parameters** 6010 6011| Name | Type | Mandatory| Description | 6012| -------- | -------------------- | ---- | ------------------------ | 6013| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 6014 6015**Example** 6016 6017```ts 6018import { BusinessError } from '@kit.BasicServicesKit'; 6019 6020videoPlayer.play((err: BusinessError) => { 6021 if (err) { 6022 console.error('Failed to play!'); 6023 } else { 6024 console.info('Succeeded in playing!'); 6025 } 6026}); 6027``` 6028 6029### play<sup>(deprecated)</sup> 6030 6031play(): Promise\<void> 6032 6033Starts video playback. This API uses a promise to return the result. 6034 6035> **NOTE** 6036> 6037> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.play](#play9-1) instead. 6038 6039**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6040 6041**Return value** 6042 6043| Type | Description | 6044| -------------- | ----------------------------- | 6045| Promise\<void> | Promise that returns no value.| 6046 6047**Example** 6048 6049```ts 6050import { BusinessError } from '@kit.BasicServicesKit'; 6051 6052videoPlayer.play().then(() => { 6053 console.info('Succeeded in playing'); 6054}).catch((error: BusinessError) => { 6055 console.error(`video catchCallback, error:${error}`); 6056}); 6057``` 6058 6059### pause<sup>(deprecated)</sup> 6060 6061pause(callback: AsyncCallback\<void>): void 6062 6063Pauses video playback. This API uses an asynchronous callback to return the result. 6064 6065> **NOTE** 6066> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.pause](#pause9) instead. 6067 6068**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6069 6070**Parameters** 6071 6072| Name | Type | Mandatory| Description | 6073| -------- | -------------------- | ---- | ------------------------ | 6074| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 6075 6076**Example** 6077 6078```ts 6079import { BusinessError } from '@kit.BasicServicesKit'; 6080 6081videoPlayer.pause((err: BusinessError) => { 6082 if (err) { 6083 console.error('Failed to pause!'); 6084 } else { 6085 console.info('Succeeded in pausing!'); 6086 } 6087}); 6088``` 6089 6090### pause<sup>(deprecated)</sup> 6091 6092pause(): Promise\<void> 6093 6094Pauses video playback. This API uses a promise to return the result. 6095 6096> **NOTE** 6097> 6098> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.pause](#pause9-1) instead. 6099 6100**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6101 6102**Return value** 6103 6104| Type | Description | 6105| -------------- | ----------------------------- | 6106| Promise\<void> | Promise that returns no value.| 6107 6108**Example** 6109 6110```ts 6111import { BusinessError } from '@kit.BasicServicesKit'; 6112 6113videoPlayer.pause().then(() => { 6114 console.info('Succeeded in pausing'); 6115}).catch((error: BusinessError) => { 6116 console.error(`video catchCallback, error:${error}`); 6117}); 6118``` 6119 6120### stop<sup>(deprecated)</sup> 6121 6122stop(callback: AsyncCallback\<void>): void 6123 6124Stops video playback. This API uses an asynchronous callback to return the result. 6125 6126> **NOTE** 6127> 6128> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.stop](#stop9) instead. 6129 6130**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6131 6132**Parameters** 6133 6134| Name | Type | Mandatory| Description | 6135| -------- | -------------------- | ---- | ------------------------ | 6136| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 6137 6138**Example** 6139 6140```ts 6141import { BusinessError } from '@kit.BasicServicesKit'; 6142 6143videoPlayer.stop((err: BusinessError) => { 6144 if (err) { 6145 console.error('Failed to stop!'); 6146 } else { 6147 console.info('Succeeded in stopping!'); 6148 } 6149}); 6150``` 6151 6152### stop<sup>(deprecated)</sup> 6153 6154stop(): Promise\<void> 6155 6156Stops video playback. This API uses a promise to return the result. 6157 6158> **NOTE** 6159> 6160> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.stop](#stop9-1) instead. 6161 6162**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6163 6164**Return value** 6165 6166| Type | Description | 6167| -------------- | ----------------------------- | 6168| Promise\<void> | Promise that returns no value.| 6169 6170**Example** 6171 6172```ts 6173import { BusinessError } from '@kit.BasicServicesKit'; 6174 6175videoPlayer.stop().then(() => { 6176 console.info('Succeeded in stopping'); 6177}).catch((error: BusinessError) => { 6178 console.error(`video catchCallback, error:${error}`); 6179}); 6180``` 6181 6182### reset<sup>(deprecated)</sup> 6183 6184reset(callback: AsyncCallback\<void>): void 6185 6186Resets video playback. This API uses an asynchronous callback to return the result. 6187 6188> **NOTE** 6189> 6190> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.reset](#reset9) instead. 6191 6192**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6193 6194**Parameters** 6195 6196| Name | Type | Mandatory| Description | 6197| -------- | -------------------- | ---- | ------------------------ | 6198| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 6199 6200**Example** 6201 6202```ts 6203import { BusinessError } from '@kit.BasicServicesKit'; 6204 6205videoPlayer.reset((err: BusinessError) => { 6206 if (err) { 6207 console.error('Failed to reset!'); 6208 } else { 6209 console.info('Succeeded in resetting!'); 6210 } 6211}); 6212``` 6213 6214### reset<sup>(deprecated)</sup> 6215 6216reset(): Promise\<void> 6217 6218Resets video playback. This API uses a promise to return the result. 6219 6220> **NOTE** 6221> 6222> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.reset](#reset9-1) instead. 6223 6224**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6225 6226**Return value** 6227 6228| Type | Description | 6229| -------------- | ----------------------------- | 6230| Promise\<void> | Promise that returns no value.| 6231 6232**Example** 6233 6234```ts 6235import { BusinessError } from '@kit.BasicServicesKit'; 6236 6237videoPlayer.reset().then(() => { 6238 console.info('Succeeded in resetting'); 6239}).catch((error: BusinessError) => { 6240 console.error(`video catchCallback, error:${error}`); 6241}); 6242``` 6243 6244### seek<sup>(deprecated)</sup> 6245 6246seek(timeMs: number, callback: AsyncCallback\<number>): void 6247 6248Seeks to the specified playback position. The previous key frame at the specified position is played. This API uses an asynchronous callback to return the result. 6249 6250> **NOTE** 6251> 6252> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.seek](#seek9) instead. 6253 6254**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6255 6256**Parameters** 6257 6258| Name | Type | Mandatory| Description | 6259| -------- | ---------------------- | ---- | ------------------------------------------------------------ | 6260| timeMs | number | Yes | Position to seek to, in ms. The value range is [0, duration].| 6261| callback | AsyncCallback\<number> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the new playback position; otherwise, **err** is an error object. | 6262 6263**Example** 6264 6265```ts 6266import { BusinessError } from '@kit.BasicServicesKit'; 6267 6268let videoPlayer: media.VideoPlayer; 6269media.createVideoPlayer((error: BusinessError, video: media.VideoPlayer) => { 6270 if (video != null) { 6271 videoPlayer = video; 6272 console.info('Succeeded in creating VideoPlayer'); 6273 } else { 6274 console.error(`Failed to create VideoPlayer, error:${error}`); 6275 } 6276}); 6277 6278let seekTime: number = 5000; 6279videoPlayer.seek(seekTime, (err: BusinessError, result: number) => { 6280 if (err) { 6281 console.error('Failed to do seek!'); 6282 } else { 6283 console.info('Succeeded in doing seek!'); 6284 } 6285}); 6286``` 6287 6288### seek<sup>(deprecated)</sup> 6289 6290seek(timeMs: number, mode:SeekMode, callback: AsyncCallback\<number>): void 6291 6292Seeks to the specified playback position. This API uses an asynchronous callback to return the result. 6293 6294> **NOTE** 6295> 6296> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.seek](#seek9) instead. 6297 6298**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6299 6300**Parameters** 6301 6302| Name | Type | Mandatory| Description | 6303| -------- | ---------------------- | ---- | ------------------------------------------------------------ | 6304| timeMs | number | Yes | Position to seek to, in ms. The value range is [0, duration].| 6305| mode | [SeekMode](#seekmode8) | Yes | Seek mode. | 6306| callback | AsyncCallback\<number> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the new playback position; otherwise, **err** is an error object. | 6307 6308**Example** 6309 6310```ts 6311import { BusinessError } from '@kit.BasicServicesKit'; 6312 6313let videoPlayer: media.VideoPlayer | null = null; 6314media.createVideoPlayer((error: BusinessError, video: media.VideoPlayer) => { 6315 if (video != null) { 6316 videoPlayer = video; 6317 console.info('Succeeded in creating VideoPlayer'); 6318 } else { 6319 console.error(`Failed to create VideoPlayer, error:${error}`); 6320 } 6321}); 6322let seekTime: number = 5000; 6323if (videoPlayer) { 6324 (videoPlayer as media.VideoPlayer).seek(seekTime, media.SeekMode.SEEK_NEXT_SYNC, (err: BusinessError, result: number) => { 6325 if (err) { 6326 console.error('Failed to do seek!'); 6327 } else { 6328 console.info('Succeeded in doing seek!'); 6329 } 6330 }); 6331} 6332``` 6333 6334### seek<sup>(deprecated)</sup> 6335 6336seek(timeMs: number, mode?:SeekMode): Promise\<number> 6337 6338Seeks to the specified playback position. If **mode** is not specified, the previous key frame at the specified position is played. This API uses a promise to return the result. 6339 6340> **NOTE** 6341> 6342> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.seek](#seek9) instead. 6343 6344**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6345 6346**Parameters** 6347 6348| Name| Type | Mandatory| Description | 6349| ------ | ---------------------- | ---- | ------------------------------------------------------------ | 6350| timeMs | number | Yes | Position to seek to, in ms. The value range is [0, duration].| 6351| mode | [SeekMode](#seekmode8) | No | Seek mode based on the video I frame. The default value is **SEEK_PREV_SYNC**. | 6352 6353**Return value** 6354 6355| Type | Description | 6356| ---------------- | ------------------------------------------- | 6357| Promise\<number>| Promise used to return the playback position, in ms.| 6358 6359**Example** 6360 6361```ts 6362import { BusinessError } from '@kit.BasicServicesKit'; 6363 6364let videoPlayer: media.VideoPlayer | null = null; 6365media.createVideoPlayer((error: BusinessError, video: media.VideoPlayer) => { 6366 if (video != null) { 6367 videoPlayer = video; 6368 console.info('Succeeded in creating VideoPlayer'); 6369 } else { 6370 console.error(`Failed to create VideoPlayer, error:${error}`); 6371 } 6372}); 6373let seekTime: number = 5000; 6374if (videoPlayer) { 6375 (videoPlayer as media.VideoPlayer).seek(seekTime).then((seekDoneTime: number) => { // seekDoneTime indicates the position after the seek operation is complete. 6376 console.info('Succeeded in doing seek'); 6377 }).catch((error: BusinessError) => { 6378 console.error(`video catchCallback, error:${error}`); 6379 }); 6380 6381 (videoPlayer as media.VideoPlayer).seek(seekTime, media.SeekMode.SEEK_NEXT_SYNC).then((seekDoneTime: number) => { 6382 console.info('Succeeded in doing seek'); 6383 }).catch((error: BusinessError) => { 6384 console.error(`video catchCallback, error:${error}`); 6385 }); 6386} 6387``` 6388 6389### setVolume<sup>(deprecated)</sup> 6390 6391setVolume(vol: number, callback: AsyncCallback\<void>): void 6392 6393Sets the volume. This API uses an asynchronous callback to return the result. 6394 6395> **NOTE** 6396> 6397> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.setVolume](#setvolume9) instead. 6398 6399**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6400 6401**Parameters** 6402 6403| Name | Type | Mandatory| Description | 6404| -------- | -------------------- | ---- | ------------------------------------------------------------ | 6405| vol | number | Yes | Relative volume. The value ranges from 0.00 to 1.00. The value **1.00** indicates the maximum volume (100%).| 6406| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the setting is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 6407 6408**Example** 6409 6410```ts 6411import { BusinessError } from '@kit.BasicServicesKit'; 6412 6413let vol: number = 0.5; 6414videoPlayer.setVolume(vol, (err: BusinessError) => { 6415 if (err) { 6416 console.error('Failed to set Volume!'); 6417 } else { 6418 console.info('Succeeded in setting Volume!'); 6419 } 6420}); 6421``` 6422 6423### setVolume<sup>(deprecated)</sup> 6424 6425setVolume(vol: number): Promise\<void> 6426 6427Sets the volume. This API uses a promise to return the result. 6428 6429> **NOTE** 6430> 6431> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.setVolume](#setvolume9) instead. 6432 6433**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6434 6435**Parameters** 6436 6437| Name| Type | Mandatory| Description | 6438| ------ | ------ | ---- | ------------------------------------------------------------ | 6439| vol | number | Yes | Relative volume. The value ranges from 0.00 to 1.00. The value **1.00** indicates the maximum volume (100%).| 6440 6441**Return value** 6442 6443| Type | Description | 6444| -------------- | ------------------------- | 6445| Promise\<void> | Promise that returns no value.| 6446 6447**Example** 6448 6449```ts 6450import { BusinessError } from '@kit.BasicServicesKit'; 6451 6452let vol: number = 0.5; 6453videoPlayer.setVolume(vol).then(() => { 6454 console.info('Succeeded in setting Volume'); 6455}).catch((error: BusinessError) => { 6456 console.error(`video catchCallback, error:${error}`); 6457}); 6458``` 6459 6460### release<sup>(deprecated)</sup> 6461 6462release(callback: AsyncCallback\<void>): void 6463 6464Releases the video playback resources. This API uses an asynchronous callback to return the result. 6465 6466> **NOTE** 6467> 6468> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.release](#release9) instead. 6469 6470**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6471 6472**Parameters** 6473 6474| Name | Type | Mandatory| Description | 6475| -------- | -------------------- | ---- | ------------------------ | 6476| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 6477 6478**Example** 6479 6480```ts 6481import { BusinessError } from '@kit.BasicServicesKit'; 6482 6483videoPlayer.release((err: BusinessError) => { 6484 if (err) { 6485 console.error('Failed to release!'); 6486 } else { 6487 console.info('Succeeded in releasing!'); 6488 } 6489}); 6490``` 6491 6492### release<sup>(deprecated)</sup> 6493 6494release(): Promise\<void> 6495 6496Releases the video playback resources. This API uses a promise to return the result. 6497 6498> **NOTE** 6499> 6500> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.release](#release9-1) instead. 6501 6502**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6503 6504**Return value** 6505 6506| Type | Description | 6507| -------------- | ----------------------------- | 6508| Promise\<void> | Promise that returns no value.| 6509 6510**Example** 6511 6512```ts 6513import { BusinessError } from '@kit.BasicServicesKit'; 6514 6515videoPlayer.release().then(() => { 6516 console.info('Succeeded in releasing'); 6517}).catch((error: BusinessError) => { 6518 console.error(`video catchCallback, error:${error}`); 6519}); 6520``` 6521 6522### getTrackDescription<sup>(deprecated)</sup> 6523 6524getTrackDescription(callback: AsyncCallback\<Array\<MediaDescription>>): void 6525 6526Obtains the video track information. This API uses an asynchronous callback to return the result. 6527 6528> **NOTE** 6529> 6530> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.getTrackDescription](#gettrackdescription9) instead. 6531 6532**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6533 6534**Parameters** 6535 6536| Name | Type | Mandatory| Description | 6537| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------ | 6538| callback | AsyncCallback\<Array\<[MediaDescription](#mediadescription8)>> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the MediaDescription array obtained; otherwise, **err** is an error object.| 6539 6540**Example** 6541 6542```ts 6543import { BusinessError } from '@kit.BasicServicesKit'; 6544 6545videoPlayer.getTrackDescription((error: BusinessError, arrList: Array<media.MediaDescription>) => { 6546 if ((arrList) != null) { 6547 console.info('Succeeded in getting TrackDescription'); 6548 } else { 6549 console.error(`Failed to get TrackDescription, error:${error}`); 6550 } 6551}); 6552``` 6553 6554### getTrackDescription<sup>(deprecated)</sup> 6555 6556getTrackDescription(): Promise\<Array\<MediaDescription>> 6557 6558Obtains the video track information. This API uses a promise to return the result. 6559 6560> **NOTE** 6561> 6562> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.getTrackDescription](#gettrackdescription9-1) instead. 6563 6564**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6565 6566**Return value** 6567 6568| Type | Description | 6569| ------------------------------------------------------ | ----------------------------------------------- | 6570| Promise<Array<[MediaDescription](#mediadescription8)>> | Promise used to return the MediaDescription array that holds the video track information.| 6571 6572**Example** 6573 6574```ts 6575import { BusinessError } from '@kit.BasicServicesKit'; 6576 6577videoPlayer.getTrackDescription().then((arrList: Array<media.MediaDescription>) => { 6578 if (arrList != null) { 6579 console.info('Succeeded in getting TrackDescription'); 6580 } else { 6581 console.error('Failed to get TrackDescription'); 6582 } 6583}).catch((error: BusinessError) => { 6584 console.error(`video catchCallback, error:${error}`); 6585}); 6586``` 6587 6588### setSpeed<sup>(deprecated)</sup> 6589 6590setSpeed(speed: number, callback: AsyncCallback\<number>): void 6591 6592Sets the playback speed. This API uses an asynchronous callback to return the result. 6593 6594> **NOTE** 6595> 6596> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.setSpeed](#setspeed9) instead. 6597 6598**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6599 6600**Parameters** 6601 6602| Name | Type | Mandatory| Description | 6603| -------- | ---------------------- | ---- | ---------------------------------------------------------- | 6604| speed | number | Yes | Video playback speed. For details, see [PlaybackSpeed](#playbackspeed8).| 6605| callback | AsyncCallback\<number> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the playback speed; otherwise, **err** is an error object. | 6606 6607**Example** 6608 6609```ts 6610import { BusinessError } from '@kit.BasicServicesKit'; 6611 6612let videoPlayer: media.VideoPlayer | null = null; 6613media.createVideoPlayer((error: BusinessError, video: media.VideoPlayer) => { 6614 if (video != null) { 6615 videoPlayer = video; 6616 console.info('Succeeded in creating VideoPlayer'); 6617 } else { 6618 console.error(`Failed to create VideoPlayer, error:${error}`); 6619 } 6620}); 6621let speed = media.PlaybackSpeed.SPEED_FORWARD_2_00_X; 6622if (videoPlayer) { 6623 (videoPlayer as media.VideoPlayer).setSpeed(speed, (err: BusinessError, result: number) => { 6624 if (err) { 6625 console.error('Failed to set Speed!'); 6626 } else { 6627 console.info('Succeeded in setting Speed!'); 6628 } 6629 }); 6630} 6631``` 6632 6633### setSpeed<sup>(deprecated)</sup> 6634 6635setSpeed(speed: number): Promise\<number> 6636 6637Sets the playback speed. This API uses a promise to return the result. 6638 6639> **NOTE** 6640> 6641> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.setSpeed](#setspeed9) instead. 6642 6643**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6644 6645**Parameters** 6646 6647| Name| Type | Mandatory| Description | 6648| ------ | ------ | ---- | ---------------------------------------------------------- | 6649| speed | number | Yes | Video playback speed. For details, see [PlaybackSpeed](#playbackspeed8).| 6650 6651**Return value** 6652 6653| Type | Description | 6654| ---------------- | ------------------------------------------------------------ | 6655| Promise\<number>| Promise used to return the playback speed. For details, see [PlaybackSpeed](#playbackspeed8).| 6656 6657**Example** 6658 6659```ts 6660import { BusinessError } from '@kit.BasicServicesKit'; 6661 6662let videoPlayer: media.VideoPlayer | null = null; 6663media.createVideoPlayer((error: BusinessError, video: media.VideoPlayer) => { 6664 if (video != null) { 6665 videoPlayer = video; 6666 console.info('Succeeded in creating VideoPlayer'); 6667 } else { 6668 console.error(`Failed to create VideoPlayer, error:${error}`); 6669 } 6670}); 6671let speed = media.PlaybackSpeed.SPEED_FORWARD_2_00_X; 6672if (videoPlayer) { 6673 (videoPlayer as media.VideoPlayer).setSpeed(speed).then((result: number) => { 6674 console.info('Succeeded in setting Speed'); 6675 }).catch((error: BusinessError) => { 6676 console.error(`Failed to set Speed, error:${error}`);//todo:: error 6677 }); 6678} 6679``` 6680 6681### on('playbackCompleted')<sup>(deprecated)</sup> 6682 6683on(type: 'playbackCompleted', callback: Callback\<void>): void 6684 6685Subscribes to the video playback completion event. 6686 6687> **NOTE** 6688> 6689> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.on('stateChange')](#onstatechange9) instead. 6690 6691**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6692 6693**Parameters** 6694 6695| Name | Type | Mandatory| Description | 6696| -------- | -------- | ---- | ----------------------------------------------------------- | 6697| type | string | Yes | Event type, which is **'playbackCompleted'** in this case.| 6698| callback | Callback\<void> | Yes | Callback invoked when the event is triggered. | 6699 6700**Example** 6701 6702```ts 6703videoPlayer.on('playbackCompleted', () => { 6704 console.info('playbackCompleted called!'); 6705}); 6706``` 6707 6708### on('bufferingUpdate')<sup>(deprecated)</sup> 6709 6710on(type: 'bufferingUpdate', callback: (infoType: BufferingInfoType, value: number) => void): void 6711 6712Subscribes to the video buffering update event. This API works only under online playback. 6713 6714> **NOTE** 6715> 6716> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.on('bufferingUpdate')](#onbufferingupdate9) instead. 6717 6718**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6719 6720**Parameters** 6721 6722| Name | Type | Mandatory| Description | 6723| -------- | -------- | ---- | ------------------------------------------------------------ | 6724| type | string | Yes | Event type, which is **'bufferingUpdate'** in this case. | 6725| callback | function | Yes | Callback invoked when the event is triggered.<br>The value of [BufferingInfoType](#bufferinginfotype8) is fixed at **0**.| 6726 6727**Example** 6728 6729```ts 6730videoPlayer.on('bufferingUpdate', (infoType: media.BufferingInfoType, value: number) => { 6731 console.info('video bufferingInfo type: ' + infoType); 6732 console.info('video bufferingInfo value: ' + value); 6733}); 6734``` 6735 6736### on('startRenderFrame')<sup>(deprecated)</sup> 6737 6738on(type: 'startRenderFrame', callback: Callback\<void>): void 6739 6740Subscribes to the frame rendering start event. 6741 6742> **NOTE** 6743> 6744> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.on('startRenderFrame')](#onstartrenderframe9) instead. 6745 6746**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6747 6748**Parameters** 6749 6750| Name | Type | Mandatory| Description | 6751| -------- | --------------- | ---- | ------------------------------------------------------------ | 6752| type | string | Yes | Event type, which is **'startRenderFrame'** in this case.| 6753| callback | Callback\<void> | Yes | Callback invoked when the event is triggered. | 6754 6755**Example** 6756 6757```ts 6758videoPlayer.on('startRenderFrame', () => { 6759 console.info('startRenderFrame called!'); 6760}); 6761``` 6762 6763### on('videoSizeChanged')<sup>(deprecated)</sup> 6764 6765on(type: 'videoSizeChanged', callback: (width: number, height: number) => void): void 6766 6767Subscribes to the video width and height change event. 6768 6769> **NOTE** 6770> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.on('videoSizeChange')](#onvideosizechange9) instead. 6771 6772**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6773 6774**Parameters** 6775 6776| Name | Type | Mandatory| Description | 6777| -------- | -------- | ---- | ------------------------------------------------------------ | 6778| type | string | Yes | Event type, which is **'videoSizeChanged'** in this case.| 6779| callback | function | Yes | Callback invoked when the event is triggered. **width** indicates the video width, and **height** indicates the video height. | 6780 6781**Example** 6782 6783```ts 6784videoPlayer.on('videoSizeChanged', (width: number, height: number) => { 6785 console.info('video width is: ' + width); 6786 console.info('video height is: ' + height); 6787}); 6788``` 6789### on('audioInterrupt')<sup>(deprecated)</sup> 6790 6791on(type: 'audioInterrupt', callback: (info: audio.InterruptEvent) => void): void 6792 6793Subscribes to the audio interruption event. For details, see [audio.InterruptEvent](../apis-audio-kit/js-apis-audio.md#interruptevent9). 6794 6795> **NOTE** 6796> 6797> This API is supported in API version 9 and deprecated since API version 9. You are advised to use [AVPlayer.on('audioInterrupt')](#onaudiointerrupt9) instead. 6798 6799**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6800 6801**Parameters** 6802 6803| Name | Type | Mandatory| Description | 6804| -------- | ------------------------------------------------------------ | ---- | -------------------------------------------------------- | 6805| type | string | Yes | Event type, which is **'audioInterrupt'** in this case.| 6806| callback | function | Yes | Callback invoked when the event is triggered. | 6807 6808**Example** 6809 6810```ts 6811import { audio } from '@kit.AudioKit'; 6812 6813videoPlayer.on('audioInterrupt', (info: audio.InterruptEvent) => { 6814 console.info('audioInterrupt called,and InterruptEvent info is:' + info) 6815}) 6816``` 6817 6818### on('error')<sup>(deprecated)</sup> 6819 6820on(type: 'error', callback: ErrorCallback): void 6821 6822Subscribes to video playback error events. After an error event is reported, you must handle the event and exit the playback. 6823 6824> **NOTE** 6825> 6826> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.on('error')](#onerror9) instead. 6827 6828**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6829 6830**Parameters** 6831 6832| Name | Type | Mandatory| Description | 6833| -------- | ------------- | ---- | ------------------------------------------------------------ | 6834| type | string | Yes | Event type, which is **'error'** in this case.<br>This event is triggered when an error occurs during video playback.| 6835| callback | [ErrorCallback](../apis-basic-services-kit/js-apis-base.md#errorcallback) | Yes | Callback invoked when the event is triggered. | 6836 6837**Example** 6838 6839```ts 6840import { BusinessError } from '@kit.BasicServicesKit'; 6841 6842videoPlayer.on('error', (error: BusinessError) => { // Set the 'error' event callback. 6843 console.error(`video error called, error: ${error}`); 6844}); 6845videoPlayer.url = 'fd://error'; // Set an incorrect URL to trigger the 'error' event. 6846``` 6847 6848## VideoPlayState<sup>(deprecated)</sup> 6849 6850type VideoPlayState = 'idle' | 'prepared' | 'playing' | 'paused' | 'stopped' | 'error' 6851 6852Enumerates the video playback states. You can obtain the state through the **state** attribute. 6853 6854> **NOTE** 6855> 6856> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayerState](#avplayerstate9) instead. 6857 6858**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6859 6860| Type | Description | 6861| -------- | -------------- | 6862| 'idle' | The video player is idle.| 6863| 'prepared' | Video playback is being prepared.| 6864| 'playing' | Video playback is in progress.| 6865| 'paused' | Video playback is paused.| 6866| 'stopped' | Video playback is stopped.| 6867| 'error' | Video playback is in the error state. | 6868 6869## AudioRecorder<sup>(deprecated)</sup> 6870 6871> **NOTE** 6872> 6873> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVRecorder](#avrecorder9) instead. 6874 6875Implements audio recording. Before calling any API of **AudioRecorder**, you must use [createAudioRecorder()](#mediacreateaudiorecorderdeprecated) to create an **AudioRecorder** instance. 6876 6877### prepare<sup>(deprecated)</sup> 6878 6879prepare(config: AudioRecorderConfig): void 6880 6881Prepares for recording. 6882 6883> **NOTE** 6884> 6885> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVRecorder.prepare](#prepare9-2) instead. 6886 6887**Required permissions:** ohos.permission.MICROPHONE 6888 6889**System capability**: SystemCapability.Multimedia.Media.AudioRecorder 6890 6891**Parameters** 6892 6893| Name| Type | Mandatory| Description | 6894| ------ | ------------------------------------------- | ---- | ------------------------------------------------------------ | 6895| config | [AudioRecorderConfig](#audiorecorderconfigdeprecated) | Yes | Audio recording parameters, including the audio output URI, encoding format, sampling rate, number of audio channels, and output format.| 6896 6897**Error codes** 6898 6899For details about the error codes, see [Media Error Codes](errorcode-media.md). 6900 6901| ID| Error Message | 6902| -------- | --------------------- | 6903| 201 | permission denied | 6904 6905**Example** 6906 6907```ts 6908let audioRecorderConfig: media.AudioRecorderConfig = { 6909 audioEncoder : media.AudioEncoder.AAC_LC, 6910 audioEncodeBitRate : 22050, 6911 audioSampleRate : 22050, 6912 numberOfChannels : 2, 6913 format : media.AudioOutputFormat.AAC_ADTS, 6914 uri : 'fd://1', // The file must be created by the caller and granted with proper permissions. 6915 location : { latitude : 30, longitude : 130}, 6916} 6917audioRecorder.on('prepare', () => { // Set the 'prepare' event callback. 6918 console.info('prepare called'); 6919}); 6920audioRecorder.prepare(audioRecorderConfig); 6921``` 6922 6923### start<sup>(deprecated)</sup> 6924 6925start(): void 6926 6927Starts audio recording. This API can be called only after the **'prepare'** event is triggered. 6928 6929> **NOTE** 6930> 6931> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVRecorder.start](#start9) instead. 6932 6933**System capability**: SystemCapability.Multimedia.Media.AudioRecorder 6934 6935**Example** 6936 6937```ts 6938audioRecorder.on('start', () => { // Set the 'start' event callback. 6939 console.info('audio recorder start called'); 6940}); 6941audioRecorder.start(); 6942``` 6943 6944### pause<sup>(deprecated)</sup> 6945 6946pause():void 6947 6948Pauses audio recording. This API can be called only after the **'start'** event is triggered. 6949 6950> **NOTE** 6951> 6952> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVRecorder.pause](#pause9-2) instead. 6953 6954**System capability**: SystemCapability.Multimedia.Media.AudioRecorder 6955 6956**Example** 6957 6958```ts 6959audioRecorder.on('pause', () => { // Set the 'pause' event callback. 6960 console.info('audio recorder pause called'); 6961}); 6962audioRecorder.pause(); 6963``` 6964 6965### resume<sup>(deprecated)</sup> 6966 6967resume():void 6968 6969Resumes audio recording. This API can be called only after the **'pause'** event is triggered. 6970 6971> **NOTE** 6972> 6973> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVRecorder.resume](#resume9) instead. 6974 6975**System capability**: SystemCapability.Multimedia.Media.AudioRecorder 6976 6977**Example** 6978 6979```ts 6980audioRecorder.on('resume', () => { // Set the 'resume' event callback. 6981 console.info('audio recorder resume called'); 6982}); 6983audioRecorder.resume(); 6984``` 6985 6986### stop<sup>(deprecated)</sup> 6987 6988stop(): void 6989 6990Stops audio recording. 6991 6992> **NOTE** 6993> 6994> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVRecorder.stop](#stop9-2) instead. 6995 6996**System capability**: SystemCapability.Multimedia.Media.AudioRecorder 6997 6998**Example** 6999 7000```ts 7001audioRecorder.on('stop', () => { // Set the 'stop' event callback. 7002 console.info('audio recorder stop called'); 7003}); 7004audioRecorder.stop(); 7005``` 7006 7007### release<sup>(deprecated)</sup> 7008 7009release(): void 7010 7011Releases the audio recording resources. 7012 7013> **NOTE** 7014> 7015> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVRecorder.release](#release9-2) instead. 7016 7017**System capability**: SystemCapability.Multimedia.Media.AudioRecorder 7018 7019**Example** 7020 7021```ts 7022audioRecorder.on('release', () => { // Set the 'release' event callback. 7023 console.info('audio recorder release called'); 7024}); 7025audioRecorder.release(); 7026audioRecorder = undefined; 7027``` 7028 7029### reset<sup>(deprecated)</sup> 7030 7031reset(): void 7032 7033Resets audio recording. 7034 7035Before resetting audio recording, you must call **stop()** to stop recording. After audio recording is reset, you must call **prepare()** to set the recording configurations for another recording. 7036 7037> **NOTE** 7038> 7039> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVRecorder.reset](#reset9-2) instead. 7040 7041**System capability**: SystemCapability.Multimedia.Media.AudioRecorder 7042 7043**Example** 7044 7045```ts 7046audioRecorder.on('reset', () => { // Set the 'reset' event callback. 7047 console.info('audio recorder reset called'); 7048}); 7049audioRecorder.reset(); 7050``` 7051 7052### on('prepare' | 'start' | 'pause' | 'resume' | 'stop' | 'release' | 'reset')<sup>(deprecated)</sup> 7053 7054on(type: 'prepare' | 'start' | 'pause' | 'resume' | 'stop' | 'release' | 'reset', callback: () => void): void 7055 7056Subscribes to the audio recording events. 7057 7058> **NOTE** 7059> 7060> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVRecorder.on('stateChange')](#onstatechange9-1) instead. 7061 7062**System capability**: SystemCapability.Multimedia.Media.AudioRecorder 7063 7064**Parameters** 7065 7066| Name | Type | Mandatory| Description | 7067| -------- | -------- | ---- | ------------------------------------------------------------ | 7068| type | string | Yes | Event type. The following events are supported: 'prepare'\|'start'\| 'pause' \| 'resume' \|'stop'\|'release'\|'reset'<br>- 'prepare': triggered when the **prepare()** API is called and the audio recording parameters are set.<br>- 'start': triggered when the **start()** API is called and audio recording starts.<br>- 'pause': triggered when the **pause()** API is called and audio recording is paused.<br>- 'resume': triggered when the **resume()** API is called and audio recording is resumed.<br>- 'stop': triggered when the **stop()** API is called and audio recording stops.<br>- 'release': triggered when the **release()** API is called and the recording resources are released.<br>- 'reset': triggered when the **reset()** API is called and audio recording is reset.| 7069| callback | ()=>void | Yes | Callback invoked when the event is triggered. | 7070 7071**Example** 7072 7073```ts 7074import { BusinessError } from '@kit.BasicServicesKit'; 7075 7076let audioRecorder: media.AudioRecorder = media.createAudioRecorder(); // Create an AudioRecorder instance. 7077let audioRecorderConfig: media.AudioRecorderConfig = { 7078 audioEncoder : media.AudioEncoder.AAC_LC, 7079 audioEncodeBitRate : 22050, 7080 audioSampleRate : 22050, 7081 numberOfChannels : 2, 7082 format : media.AudioOutputFormat.AAC_ADTS, 7083 uri : 'fd://xx', // The file must be created by the caller and granted with proper permissions. 7084 location : { latitude : 30, longitude : 130} 7085} 7086audioRecorder.on('error', (error: BusinessError) => { // Set the 'error' event callback. 7087 console.error(`audio error called, error: ${error}`); 7088}); 7089audioRecorder.on('prepare', () => { // Set the 'prepare' event callback. 7090 console.info('prepare called'); 7091 audioRecorder.start(); // // Start recording and trigger the 'start' event callback. 7092}); 7093audioRecorder.on('start', () => { // Set the 'start' event callback. 7094 console.info('audio recorder start called'); 7095}); 7096audioRecorder.on('pause', () => { // Set the 'pause' event callback. 7097 console.info('audio recorder pause called'); 7098}); 7099audioRecorder.on('resume', () => { // Set the 'resume' event callback. 7100 console.info('audio recorder resume called'); 7101}); 7102audioRecorder.on('stop', () => { // Set the 'stop' event callback. 7103 console.info('audio recorder stop called'); 7104}); 7105audioRecorder.on('release', () => { // Set the 'release' event callback. 7106 console.info('audio recorder release called'); 7107}); 7108audioRecorder.on('reset', () => { // Set the 'reset' event callback. 7109 console.info('audio recorder reset called'); 7110}); 7111audioRecorder.prepare(audioRecorderConfig) // // Set recording parameters and trigger the 'prepare' event callback. 7112``` 7113 7114### on('error')<sup>(deprecated)</sup> 7115 7116on(type: 'error', callback: ErrorCallback): void 7117 7118Subscribes to audio recording error events. After an error event is reported, you must handle the event and exit the recording. 7119 7120> **NOTE** 7121> 7122> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVRecorder.on('error')](#onerror9-1) instead. 7123 7124**System capability**: SystemCapability.Multimedia.Media.AudioRecorder 7125 7126**Parameters** 7127 7128| Name | Type | Mandatory| Description | 7129| -------- | ------------- | ---- | ------------------------------------------------------------ | 7130| type | string | Yes | Event type, which is **'error'** in this case.<br>This event is triggered when an error occurs during audio recording.| 7131| callback | [ErrorCallback](../apis-basic-services-kit/js-apis-base.md#errorcallback) | Yes | Callback invoked when the event is triggered. | 7132 7133**Example** 7134 7135```ts 7136import { BusinessError } from '@kit.BasicServicesKit'; 7137 7138let audioRecorderConfig: media.AudioRecorderConfig = { 7139 audioEncoder : media.AudioEncoder.AAC_LC, 7140 audioEncodeBitRate : 22050, 7141 audioSampleRate : 22050, 7142 numberOfChannels : 2, 7143 format : media.AudioOutputFormat.AAC_ADTS, 7144 uri : 'fd://xx', // The file must be created by the caller and granted with proper permissions. 7145 location : { latitude : 30, longitude : 130} 7146} 7147audioRecorder.on('error', (error: BusinessError) => { // Set the 'error' event callback. 7148 console.error(`audio error called, error: ${error}`); 7149}); 7150audioRecorder.prepare(audioRecorderConfig); // // Do not set any parameter in prepare and trigger the 'error' event callback. 7151``` 7152 7153## AudioRecorderConfig<sup>(deprecated)</sup> 7154 7155> **NOTE** 7156> 7157> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVRecorderConfig](#avrecorderconfig9) instead. 7158 7159Describes audio recording configurations. 7160 7161**System capability**: SystemCapability.Multimedia.Media.AudioRecorder 7162 7163| Name | Type | Mandatory| Description | 7164| ----------------------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | 7165| audioEncoder | [AudioEncoder](#audioencoderdeprecated) | No | Audio encoding format. The default value is **AAC_LC**.<br>**Note**: This parameter is deprecated since API version 8. Use **audioEncoderMime** instead.| 7166| audioEncodeBitRate | number | No | Audio encoding bit rate. The default value is **48000**. | 7167| audioSampleRate | number | No | Audio sampling rate. The default value is **48000**.<br>Variable bit rate. The bit rate is for reference only. | 7168| numberOfChannels | number | No | Number of audio channels. The default value is **2**. | 7169| format | [AudioOutputFormat](#audiooutputformatdeprecated) | No | Audio output format. The default value is **MPEG_4**.<br>**Note**: This parameter is deprecated since API version 8. Use **fileFormat** instead.| 7170| location | [Location](#location) | No | Geographical location of the recorded audio. | 7171| uri | string | Yes | Audio output URI. Supported: fd://xx (fd number)<br> <br>The file must be created by the caller and granted with proper permissions.| 7172| audioEncoderMime<sup>8+</sup> | [CodecMimeType](#codecmimetype8) | No | Container encoding format. | 7173| fileFormat<sup>8+</sup> | [ContainerFormatType](#containerformattype8) | No | Audio encoding format. | 7174 7175## AudioEncoder<sup>(deprecated)</sup> 7176 7177> **NOTE** 7178> 7179> This API is supported since API version 6 and deprecated since API version 8. You are advised to use [CodecMimeType](#codecmimetype8) instead. 7180 7181Enumerates the audio encoding formats. 7182 7183**System capability**: SystemCapability.Multimedia.Media.AudioRecorder 7184 7185| Name | Value | Description | 7186| ------- | ---- | ------------------------------------------------------------ | 7187| DEFAULT | 0 | Default encoding format.<br>This API is defined but not implemented yet. | 7188| AMR_NB | 1 | AMR-NB.<br>This API is defined but not implemented yet.| 7189| AMR_WB | 2 | Adaptive Multi Rate-Wide Band Speech Codec (AMR-WB).<br>This API is defined but not implemented yet.| 7190| AAC_LC | 3 | Advanced Audio Coding Low Complexity (AAC-LC).| 7191| HE_AAC | 4 | High-Efficiency Advanced Audio Coding (HE_AAC).<br>This API is defined but not implemented yet.| 7192 7193## AudioOutputFormat<sup>(deprecated)</sup> 7194 7195> **NOTE** 7196> 7197> This API is supported since API version 6 and deprecated since API version 8. You are advised to use [ContainerFormatType](#containerformattype8) instead. 7198 7199Enumerates the audio output formats. 7200 7201**System capability**: SystemCapability.Multimedia.Media.AudioRecorder 7202 7203| Name | Value | Description | 7204| -------- | ---- | ------------------------------------------------------------ | 7205| DEFAULT | 0 | Default output format.<br>This API is defined but not implemented yet. | 7206| MPEG_4 | 2 | MPEG-4. | 7207| AMR_NB | 3 | AMR_NB.<br>This API is defined but not implemented yet. | 7208| AMR_WB | 4 | AMR_WB.<br>This API is defined but not implemented yet. | 7209| AAC_ADTS | 6 | Audio Data Transport Stream (ADTS), which is a transport stream format of AAC-based audio.| 7210 7211 7212## media.createAVImageGenerator<sup>12+</sup> 7213 7214createAVImageGenerator(callback: AsyncCallback\<AVImageGenerator>): void 7215 7216Creates an **AVImageGenerator** instance. This API uses an asynchronous callback to return the result. 7217 7218**System capability**: SystemCapability.Multimedia.Media.AVImageGenerator 7219 7220**Parameters** 7221 7222| Name | Type | Mandatory| Description | 7223| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ | 7224| callback | AsyncCallback\<[AVImageGenerator](#avimagegenerator12)> | Yes | Callback used to return the result. If the operation is successful, an **AVImageGenerator** instance is returned; otherwise, **null** is returned. The API can be used to obtain a video thumbnail.| 7225 7226**Error codes** 7227 7228For details about the error codes, see [Media Error Codes](errorcode-media.md). 7229 7230| ID| Error Message | 7231| -------- | ------------------------------ | 7232| 5400101 | No memory. Returned by callback. | 7233 7234**Example** 7235 7236```ts 7237import { BusinessError } from '@kit.BasicServicesKit'; 7238 7239let avImageGenerator: media.AVImageGenerator; 7240media.createAVImageGenerator((error: BusinessError, generator: media.AVImageGenerator) => { 7241 if (generator != null) { 7242 avImageGenerator = generator; 7243 console.info('Succeeded in creating AVImageGenerator'); 7244 } else { 7245 console.error(`Failed to creat AVImageGenerator, error message:${error.message}`); 7246 } 7247}); 7248``` 7249 7250## media.createAVImageGenerator<sup>12+</sup> 7251 7252createAVImageGenerator(): Promise\<AVImageGenerator> 7253 7254Creates an **AVImageGenerator** instance. This API uses a promise to return the result. 7255 7256**System capability**: SystemCapability.Multimedia.Media.AVImageGenerator 7257 7258**Return value** 7259 7260| Type | Description | 7261| ------------------------------- | ------------------------------------------------------------ | 7262| Promise\<[AVImageGenerator](#avimagegenerator12)> | Promise used to return the result. If the operation is successful, an **AVImageGenerator** instance is returned; otherwise, **null** is returned. The API can be used to obtain a video thumbnail.| 7263 7264**Error codes** 7265 7266For details about the error codes, see [Media Error Codes](errorcode-media.md). 7267 7268| ID| Error Message | 7269| -------- | ----------------------------- | 7270| 5400101 | No memory. Returned by promise. | 7271 7272**Example** 7273 7274```ts 7275import { BusinessError } from '@kit.BasicServicesKit'; 7276 7277let avImageGenerator: media.AVImageGenerator; 7278media.createAVImageGenerator().then((generator: media.AVImageGenerator) => { 7279 if (generator != null) { 7280 avImageGenerator = generator; 7281 console.info('Succeeded in creating AVImageGenerator'); 7282 } else { 7283 console.error('Failed to creat AVImageGenerator'); 7284 } 7285}).catch((error: BusinessError) => { 7286 console.error(`Failed to creat AVImageGenerator, error message:${error.message}`); 7287}); 7288``` 7289 7290## AVImageGenerator<sup>12+</sup> 7291 7292Provides APIs to obtain a thumbnail from a video. Before calling any API of **AVImageGenerator**, you must use [createAVImageGenerator()](#mediacreateavimagegenerator12) to create an **AVImageGenerator** instance. 7293 7294For details about the demo for obtaining video thumbnails, see [Obtaining Video Thumbnails](../../media/media/avimagegenerator.md). 7295 7296### Attributes 7297 7298**System capability**: SystemCapability.Multimedia.Media.AVImageGenerator 7299 7300| Name | Type | Readable| Writable| Description | 7301| --------------------------------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | 7302| fdSrc<sup>12+</sup> | [AVFileDescriptor](js-apis-media.md#avfiledescriptor9) | Yes | Yes | Media file descriptor, which specifies the data source.<br> **Example:**<br>There is a media file that stores continuous assets, the address offset is 0, and the byte length is 100. Its file descriptor is **AVFileDescriptor {fd = resourceHandle; offset = 0; length = 100; }**.<br>**NOTE**<br> - After the resource handle (FD) is transferred to an **AVImageGenerator** instance, do not use the resource handle to perform other read and write operations, including but not limited to transferring this handle to other **AVPlayer**, **AVMetadataExtractor**, **AVImageGenerator**, or **AVTranscoder** instance. Competition occurs when multiple AVImageGenerator use the same resource handle to read and write files at the same time, resulting in errors in obtaining data.| 7303 7304### fetchFrameByTime<sup>12+</sup> 7305 7306fetchFrameByTime(timeUs: number, options: AVImageQueryOptions, param: PixelMapParams, callback: AsyncCallback\<image.PixelMap>): void 7307 7308Obtains a video thumbnail. This API uses an asynchronous callback to return the result. 7309 7310**System capability**: SystemCapability.Multimedia.Media.AVImageGenerator 7311 7312**Parameters** 7313 7314| Name | Type | Mandatory| Description | 7315| -------- | -------------------------------------------- | ---- | ----------------------------------- | 7316| timeUs | number | Yes | Time of the video for which a thumbnail is to be obtained, in μs.| 7317| options | [AVImageQueryOptions](#avimagequeryoptions12) | Yes | Relationship between the time passed in and the video frame.| 7318| param | [PixelMapParams](#pixelmapparams12) | Yes | Format parameters of the thumbnail to be obtained.| 7319| callback | AsyncCallback\<[image.PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the **PixelMap** instance obtained; otherwise, **err** is an error object.| 7320 7321**Error codes** 7322 7323For details about the error codes, see [Media Error Codes](errorcode-media.md). 7324 7325| ID| Error Message | 7326| -------- | ------------------------------------------ | 7327| 5400102 | Operation not allowed. Returned by callback. | 7328| 5400106 | Unsupported format. Returned by callback. | 7329 7330**Example** 7331 7332```ts 7333import { BusinessError } from '@kit.BasicServicesKit'; 7334import { media } from '@kit.MediaKit'; 7335import { image } from '@kit.ImageKit'; 7336 7337let avImageGenerator: media.AVImageGenerator | undefined = undefined; 7338let pixel_map : image.PixelMap | undefined = undefined; 7339 7340// Initialize input parameters. 7341let timeUs: number = 0 7342 7343let queryOption: media.AVImageQueryOptions = media.AVImageQueryOptions.AV_IMAGE_QUERY_NEXT_SYNC 7344 7345let param: media.PixelMapParams = { 7346 width : 300, 7347 height : 300, 7348} 7349 7350// Obtain the thumbnail. 7351media.createAVImageGenerator((err: BusinessError, generator: media.AVImageGenerator) => { 7352 if(generator != null){ 7353 avImageGenerator = generator; 7354 console.info(`Succeeded in creating AVImageGenerator`); 7355 avImageGenerator.fetchFrameByTime(timeUs, queryOption, param, (error: BusinessError, pixelMap) => { 7356 if (error) { 7357 console.error(`Failed to fetch FrameByTime, err = ${JSON.stringify(error)}`) 7358 return 7359 } 7360 pixel_map = pixelMap; 7361 }); 7362 } else { 7363 console.error(`Failed to creat AVImageGenerator, error message:${err.message}`); 7364 }; 7365}); 7366``` 7367 7368### fetchFrameByTime<sup>12+</sup> 7369 7370fetchFrameByTime(timeUs: number, options: AVImageQueryOptions, param: PixelMapParams): Promise<image.PixelMap> 7371 7372Obtains a video thumbnail. This API uses a promise to return the result. 7373 7374**System capability**: SystemCapability.Multimedia.Media.AVImageGenerator 7375 7376**Parameters** 7377 7378| Name | Type | Mandatory| Description | 7379| -------- | -------------------------------------------- | ---- | ----------------------------------- | 7380| timeUs | number | Yes | Time of the video for which a thumbnail is to be obtained, in μs.| 7381| options | [AVImageQueryOptions](#avimagequeryoptions12) | Yes | Relationship between the time passed in and the video frame.| 7382| param | [PixelMapParams](#pixelmapparams12) | Yes | Format parameters of the thumbnail to be obtained.| 7383 7384**Return value** 7385 7386| Type | Description | 7387| -------------- | ---------------------------------------- | 7388| Promise\<[image.PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)> | Promise used to return the video thumbnail.| 7389 7390**Error codes** 7391 7392For details about the error codes, see [Media Error Codes](errorcode-media.md). 7393 7394| ID| Error Message | 7395| -------- | ----------------------------------------- | 7396| 5400102 | Operation not allowed. Returned by promise. | 7397| 5400106 | Unsupported format. Returned by promise. | 7398 7399**Example** 7400 7401```ts 7402import { BusinessError } from '@kit.BasicServicesKit'; 7403import { media } from '@kit.MediaKit'; 7404import { image } from '@kit.ImageKit'; 7405 7406let avImageGenerator: media.AVImageGenerator | undefined = undefined; 7407let pixel_map : image.PixelMap | undefined = undefined; 7408 7409// Initialize input parameters. 7410let timeUs: number = 0 7411 7412let queryOption: media.AVImageQueryOptions = media.AVImageQueryOptions.AV_IMAGE_QUERY_NEXT_SYNC 7413 7414let param: media.PixelMapParams = { 7415 width : 300, 7416 height : 300, 7417} 7418 7419// Obtain the thumbnail. 7420media.createAVImageGenerator((err: BusinessError, generator: media.AVImageGenerator) => { 7421 if(generator != null){ 7422 avImageGenerator = generator; 7423 console.info(`Succeeded in creating AVImageGenerator`); 7424 avImageGenerator.fetchFrameByTime(timeUs, queryOption, param).then((pixelMap: image.PixelMap) => { 7425 pixel_map = pixelMap; 7426 }).catch((error: BusinessError) => { 7427 console.error(`Failed to fetch FrameByTime, error message:${error.message}`); 7428 }); 7429 } else { 7430 console.error(`Failed to creat AVImageGenerator, error message:${err.message}`); 7431 }; 7432}); 7433``` 7434 7435### release<sup>12+</sup> 7436 7437release(callback: AsyncCallback\<void>): void 7438 7439Releases this **AVMetadataExtractor** instance. This API uses an asynchronous callback to return the result. 7440 7441**System capability**: SystemCapability.Multimedia.Media.AVImageGenerator 7442 7443**Parameters** 7444 7445| Name | Type | Mandatory| Description | 7446| -------- | -------------------------------------------- | ---- | ----------------------------------- | 7447| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 7448 7449**Error codes** 7450 7451For details about the error codes, see [Media Error Codes](errorcode-media.md). 7452 7453| ID| Error Message | 7454| -------- | ------------------------------------------ | 7455| 5400102 | Operation not allowed. Returned by callback. | 7456 7457**Example** 7458 7459```ts 7460import { BusinessError } from '@kit.BasicServicesKit'; 7461import { media } from '@kit.MediaKit'; 7462 7463let avImageGenerator: media.AVImageGenerator | undefined = undefined; 7464 7465// Release the instance. 7466media.createAVImageGenerator((err: BusinessError, generator: media.AVImageGenerator) => { 7467 if(generator != null){ 7468 avImageGenerator = generator; 7469 console.info(`Succeeded in creating AVImageGenerator`); 7470 avImageGenerator.release((error: BusinessError) => { 7471 if (error) { 7472 console.error(`Failed to release, err = ${JSON.stringify(error)}`); 7473 return; 7474 } 7475 console.info(`Succeeded in releasing`); 7476 }); 7477 } else { 7478 console.error(`Failed to creat AVImageGenerator, error message:${err.message}`); 7479 }; 7480}); 7481``` 7482 7483### release<sup>12+</sup> 7484 7485release(): Promise\<void> 7486 7487Releases this **AVMetadataExtractor** instance. This API uses a promise to return the result. 7488 7489**System capability**: SystemCapability.Multimedia.Media.AVImageGenerator 7490 7491**Return value** 7492 7493| Type | Description | 7494| -------------- | ---------------------------------------- | 7495| Promise\<void> | Promise that returns no value.| 7496 7497**Error codes** 7498 7499For details about the error codes, see [Media Error Codes](errorcode-media.md). 7500 7501| ID| Error Message | 7502| -------- | ----------------------------------------- | 7503| 5400102 | Operation not allowed. Returned by promise. | 7504 7505**Example** 7506 7507```ts 7508import { BusinessError } from '@kit.BasicServicesKit'; 7509import { media } from '@kit.MediaKit'; 7510 7511let avImageGenerator: media.AVImageGenerator | undefined = undefined; 7512 7513// Release the instance. 7514media.createAVImageGenerator((err: BusinessError, generator: media.AVImageGenerator) => { 7515 if(generator != null){ 7516 avImageGenerator = generator; 7517 console.info(`Succeeded in creating AVImageGenerator`); 7518 avImageGenerator.release().then(() => { 7519 console.info(`Succeeded in releasing.`); 7520 }).catch((error: BusinessError) => { 7521 console.error(`Failed to release, error message:${error.message}`); 7522 }); 7523 } else { 7524 console.error(`Failed to creat AVImageGenerator, error message:${err.message}`); 7525 }; 7526}); 7527``` 7528 7529## AVImageQueryOptions<sup>12+</sup> 7530 7531Enumerates the relationship between the video frame and the time at which the video thumbnail is obtained. 7532 7533The time passed in for obtaining the thumbnail may be different from the time of the video frame for which the thumbnail is actually obtained. Therefore, you need to specify their relationship. 7534 7535**System capability**: SystemCapability.Multimedia.Media.AVImageGenerator 7536 7537| Name | Value | Description | 7538| ------------------------ | --------------- | ------------------------------------------------------------ | 7539| AV_IMAGE_QUERY_NEXT_SYNC | 0 | The key frame at or next to the specified time is selected. | 7540| AV_IMAGE_QUERY_PREVIOUS_SYNC | 1 | The key frame at or prior to the specified time is selected.| 7541| AV_IMAGE_QUERY_CLOSEST_SYNC | 2 | The key frame closest to the specified time is selected. | 7542| AV_IMAGE_QUERY_CLOSEST | 3 | The frame (not necessarily a key frame) closest to the specified time is selected.| 7543 7544## PixelMapParams<sup>12+</sup> 7545 7546Defines the format parameters of the video thumbnail to be obtained. 7547 7548**System capability**: SystemCapability.Multimedia.Media.AVImageGenerator 7549 7550| Name | Type | Readable| Writable| Description | 7551|--------|--------|------|------|---------------------------------------------------------------------------------| 7552| width | number | Yes | Yes | Width of the thumbnail. The value must be greater than 0 and less than or equal to the width of the original video. Otherwise, the returned thumbnail will not be scaled.| 7553| height | number | Yes | Yes | Height of the thumbnail. The value must be greater than 0 and less than or equal to the height of the original video. Otherwise, the returned thumbnail will not be scaled.| 7554 7555## media.createMediaSourceWithUrl<sup>12+</sup> 7556 7557createMediaSourceWithUrl(url: string, headers?: Record\<string, string>): MediaSource 7558 7559Creates a media source for streaming media to be pre-downloaded. 7560 7561**System capability**: SystemCapability.Multimedia.Media.Core 7562 7563**Parameters** 7564 7565| Name | Type | Mandatory| Description | 7566| -------- | -------- | ---- | -------------------- | 7567| url | string | Yes | - URL of the media source. The following streaming media formats are supported: HLS, HTTP-FLV, DASH, and HTTPS.<br> - FD path of the local M3U8 file. | 7568| headers | Record\<string, string> | No | HTTP header customized for streaming media pre-download.| 7569 7570**Return value** 7571 7572| Type | Description | 7573| -------------- | ------------------------------------------ | 7574| [MediaSource](#mediasource12) | **MediaSource** instance.| 7575 7576**Error codes** 7577 7578For details about the error codes, see [Media Error Codes](errorcode-media.md). 7579 7580| ID| Error Message | 7581| -------- | ----------------------------------------- | 7582| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 7583| 5400101 | No memory. | 7584 7585**Example 1** 7586 7587```ts 7588import { media } from '@kit.MediaKit'; 7589 7590let headers: Record<string, string> = {"User-Agent" : "User-Agent-Value"}; 7591let mediaSource : media.MediaSource = media.createMediaSourceWithUrl("http://xxx", headers); 7592``` 7593 7594**Example 2** 7595 7596```ts 7597import { media } from '@kit.MediaKit'; 7598import { common } from '@kit.AbilityKit'; 7599import { resourceManager } from '@kit.LocalizationKit'; 7600 7601let context = getContext(this) as common.UIAbilityContext; 7602let mgr = context.resourceManager; 7603let fileDescriptor = await mgr.getRawFd("xxx.m3u8"); 7604 7605let fd:string = fileDescriptor.fd.toString(); 7606let offset:string = fileDescriptor.offset.toString(); 7607let length:string = fileDescriptor.length.toString(); 7608let fdUrl:string = "fd://" + fd + "?offset=" + offset + "&size=" + length; 7609 7610let headers: Record<string, string> = {"User-Agent" : "User-Agent-Value"}; 7611let mediaSource : media.MediaSource = media.createMediaSourceWithUrl(fdUrl, headers); 7612 7613let mimeType : media.AVMimeTypes = media.AVMimeTypes.APPLICATION_M3U8; 7614mediaSource.setMimeType(mimeType); 7615 7616``` 7617 7618## MediaSource<sup>12+</sup> 7619 7620Defines the media data information, which is from [createMediaSourceWithUrl](#mediacreatemediasourcewithurl12). 7621 7622**System capability**: SystemCapability.Multimedia.Media.Core 7623 7624### setMimeType<sup>12+</sup> 7625 7626setMimeType(mimeType: AVMimeTypes): void 7627 7628Sets the MIME type to help the player process extended media sources. 7629 7630**Atomic service API**: This API can be used in atomic services since API version 12. 7631 7632**System capability**: SystemCapability.Multimedia.Media.Core 7633 7634**Parameters** 7635 7636| Name | Type | Mandatory| Description | 7637| -------- | -------- | ---- | -------------------- | 7638| mimeType | [AVMimeTypes](#mediasource12) | Yes | MIME type.| 7639 7640## AVMimeTypes<sup>12+</sup> 7641 7642Enumerates the MIME type, which is set by using [setMimeType](#setmimetype12). 7643 7644**Atomic service API**: This API can be used in atomic services since API version 12. 7645 7646**System capability**: SystemCapability.Multimedia.Media.Core 7647 7648 7649| Name | Value | Description | 7650| ---------- | ---- | ------------------------------------------------------------ | 7651| APPLICATION_M3U8 | application/m3u8 | Local M3U8 file.| 7652 7653 7654## PlaybackStrategy<sup>12+</sup> 7655 7656Describes the playback strategy. 7657 7658**System capability**: SystemCapability.Multimedia.Media.Core 7659 7660| Name | Type | Mandatory| Description | 7661| -------- | -------- | ---- | -------------------- | 7662| preferredWidth| number | No | Preferred width, which is of the int type, for example, **1080**.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 7663| preferredHeight | number | No | Preferred height, which is of the int type, for example, **1920**.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 7664| preferredBufferDuration | number | No | Preferred buffer duration, in seconds. The value ranges from 1 to 20.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 7665| preferredHdr | boolean | No | Whether HDR is preferred. The value **true** means that HDR is preferred, and **false** means the opposite.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 7666| mutedMediaType | [MediaType](#mediatype8) | No| Media type for muted playback. Only **MediaType.MEDIA_TYPE_AUD** can be set.| 7667| preferredAudioLanguage | string | No| Preferred audio track language. Set this parameter based on service requirements in DASH scenarios. In non-DASH scenarios, this parameter is not invoked, and you are advised to retain the default value.| 7668| preferredSubtitleLanguage | string | No| Preferred subtitle language. Set this parameter based on service requirements in DASH scenarios. In non-DASH scenarios, this parameter is not invoked, and you are advised to retain the default value.| 7669 7670## AVScreenCaptureRecordPreset<sup>12+</sup> 7671 7672Enumerates the encoding and container formats used during screen capture. 7673 7674**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture 7675 7676| Name | Value | Description | 7677| --------------------------------- | ---- | -------------------------------------------- | 7678| SCREEN_RECORD_PRESET_H264_AAC_MP4 | 0 | The H.264 video encoding format, AAC audio encoding format, and MP4 container format are used.| 7679| SCREEN_RECORD_PRESET_H265_AAC_MP4 | 1 | The H.265 video encoding format, AAC audio encoding format, and MP4 container format are used.| 7680 7681## AVScreenCaptureStateCode<sup>12+</sup> 7682 7683Enumerates the screen capture states used in callbacks. 7684 7685**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture 7686 7687| Name | Value | Description | 7688| ---------------------------------------- | ---- | ------------------------ | 7689| SCREENCAPTURE_STATE_STARTED | 0 | Screen capture is started. | 7690| SCREENCAPTURE_STATE_CANCELED | 1 | Screen capture is canceled. | 7691| SCREENCAPTURE_STATE_STOPPED_BY_USER | 2 | Screen capture is manually stopped by the user. | 7692| SCREENCAPTURE_STATE_INTERRUPTED_BY_OTHER | 3 | Screen capture is interrupted by another screen capture. | 7693| SCREENCAPTURE_STATE_STOPPED_BY_CALL | 4 | Screen capture is interrupted by an incoming call. | 7694| SCREENCAPTURE_STATE_MIC_UNAVAILABLE | 5 | The microphone is unavailable during screen capture.| 7695| SCREENCAPTURE_STATE_MIC_MUTED_BY_USER | 6 | The microphone is muted by the user. | 7696| SCREENCAPTURE_STATE_MIC_UNMUTED_BY_USER | 7 | The microphone is unmuted by the user. | 7697| SCREENCAPTURE_STATE_ENTER_PRIVATE_SCENE | 8 | The system enters a privacy page during screen capture. | 7698| SCREENCAPTURE_STATE_EXIT_PRIVATE_SCENE | 9 | The system exits a privacy page during screen capture. | 7699| SCREENCAPTURE_STATE_STOPPED_BY_USER_SWITCHES | 10 | Screen capture is interrupted by system user switchover. | 7700 7701## AVScreenCaptureRecordConfig<sup>12+</sup> 7702 7703Defines the screen capture parameters. 7704 7705**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture 7706 7707| Name | Type | Mandatory| Description | 7708| ----------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 7709| fd | number | Yes | FD of the file output. | 7710| frameWidth | number | No | Video width, in px. The default value varies according to the display in use.| 7711| frameHeight | number | No | Video height, in px. The default value varies according to the display in use.| 7712| videoBitrate | number | No | Video bit rate. The default value is **10000000**. | 7713| audioSampleRate | number | No | Audio sampling rate. This value is used for both internal capture and external capture (using microphones). Only **48000** (default value) and **16000** are supported.| 7714| audioChannelCount | number | No | Number of audio channels. This value is used for both internal capture and external capture (using microphones). Only **1** and **2** (default) are supported.| 7715| audioBitrate | number | No | Audio bit rate. This value is used for both internal capture and external capture (using microphones). The default value is **96000**.| 7716| preset | [AVScreenCaptureRecordPreset](#avscreencapturerecordpreset12) | No | Encoding and container format used. The default value is **SCREEN_RECORD_PRESET_H264_AAC_MP4**.| 7717 7718## AVScreenCaptureRecorder<sup>12+</sup> 7719 7720Provides APIs to manage screen capture. Before calling any API in **AVScreenCaptureRecorder**, you must use [createAVScreenCaptureRecorder()](#mediacreateavscreencapturerecorder12) to create an **AVScreenCaptureRecorder** instance. 7721 7722### init<sup>12+</sup> 7723 7724init(config: AVScreenCaptureRecordConfig): Promise\<void> 7725 7726Initializes screen capture and sets screen capture parameters. This API uses a promise to return the result. 7727 7728**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture 7729 7730**Parameters** 7731 7732| Name| Type | Mandatory| Description | 7733| ------ | ------------------------------------------------------------ | ---- | ------------------------ | 7734| config | [AVScreenCaptureRecordConfig](#avscreencapturerecordconfig12) | Yes | Screen capture parameters to set.| 7735 7736**Return value** 7737 7738| Type | Description | 7739| -------------- | ----------------------------------- | 7740| Promise\<void> | Promise that returns no value.| 7741 7742**Error codes** 7743 7744| ID| Error Message | 7745| -------- | ---------------------------------------------- | 7746| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. Return by promise. | 7747| 5400103 | IO error. Return by promise. | 7748| 5400105 | Service died. Return by promise. | 7749 7750**Example** 7751 7752```ts 7753import { BusinessError } from '@kit.BasicServicesKit'; 7754 7755let avCaptureConfig: media.AVScreenCaptureRecordConfig = { 7756 fd: 0, // Before passing in an FD to this parameter, the file must be created by the caller and granted with the write permissions. 7757 frameWidth: 640, 7758 frameHeight: 480 7759 // Add other parameters. 7760} 7761 7762avScreenCaptureRecorder.init(avCaptureConfig).then(() => { 7763 console.info('Succeeded in initing avScreenCaptureRecorder'); 7764}).catch((err: BusinessError) => { 7765 console.info('Failed to init avScreenCaptureRecorder, error: ' + err.message); 7766}) 7767``` 7768 7769### startRecording<sup>12+</sup> 7770 7771startRecording(): Promise\<void> 7772 7773Starts screen capture. This API uses a promise to return the result. 7774 7775**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture 7776 7777**Return value** 7778 7779| Type | Description | 7780| -------------- | -------------------------------- | 7781| Promise\<void> | Promise that returns no value.| 7782 7783**Error codes** 7784 7785| ID| Error Message | 7786| -------- | -------------------------------- | 7787| 5400103 | IO error. Return by promise. | 7788| 5400105 | Service died. Return by promise. | 7789 7790**Example** 7791 7792```ts 7793import { BusinessError } from '@kit.BasicServicesKit'; 7794 7795avScreenCaptureRecorder.startRecording().then(() => { 7796 console.info('Succeeded in starting avScreenCaptureRecorder'); 7797}).catch((err: BusinessError) => { 7798 console.info('Failed to start avScreenCaptureRecorder, error: ' + err.message); 7799}) 7800``` 7801 7802### stopRecording<sup>12+</sup> 7803 7804stopRecording(): Promise\<void> 7805 7806Stops screen capture. This API uses a promise to return the result. 7807 7808**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture 7809 7810**Return value** 7811 7812| Type | Description | 7813| -------------- | --------------------------------- | 7814| Promise\<void> | Promise that returns no value.| 7815 7816**Error codes** 7817 7818| ID| Error Message | 7819| -------- | -------------------------------- | 7820| 5400103 | IO error. Return by promise. | 7821| 5400105 | Service died. Return by promise. | 7822 7823**Example** 7824 7825```ts 7826import { BusinessError } from '@kit.BasicServicesKit'; 7827 7828avScreenCaptureRecorder.stopRecording().then(() => { 7829 console.info('Succeeded in stopping avScreenCaptureRecorder'); 7830}).catch((err: BusinessError) => { 7831 console.info('Failed to stop avScreenCaptureRecorder, error: ' + err.message); 7832}) 7833``` 7834 7835### skipPrivacyMode<sup>12+</sup> 7836 7837skipPrivacyMode(windowIDs: Array\<number>): Promise\<void> 7838 7839During screen capture, the application can exempt its privacy windows from security purposes. This API uses a promise to return the result. 7840 7841For example, if a user enters a password in this application during screen capture, the application will not display a black screen. 7842 7843**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture 7844 7845**Parameters** 7846 7847| Name| Type | Mandatory| Description | 7848| ------ | ------- | ---- | --------------------------------------------------------- | 7849| windowIDs | Array\<number> | Yes | IDs of windows that require privacy exemption, including the main window IDs and subwindow IDs. For details about how to obtain window properties, see [Window API Reference](../apis-arkui/js-apis-window.md#getwindowproperties9).| 7850 7851**Return value** 7852 7853| Type | Description | 7854| -------------- | -------------------------------- | 7855| Promise\<void> | Promise used to return the window IDs.| 7856 7857**Error codes** 7858 7859| ID| Error Message | 7860| -------- | -------------------------------- | 7861| 5400103 | IO error. Return by promise. | 7862| 5400105 | Service died. Return by promise. | 7863 7864**Example** 7865 7866```ts 7867import { BusinessError } from '@kit.BasicServicesKit'; 7868 7869let windowIDs = []; 7870avScreenCaptureRecorder.skipPrivacyMode(windowIDs).then(() => { 7871 console.info('Succeeded in skipping privacy mode'); 7872}).catch((err: BusinessError) => { 7873 console.info('Failed to skip privacy mode, error: ' + err.message); 7874}) 7875``` 7876 7877### setMicEnabled<sup>12+</sup> 7878 7879setMicEnabled(enable: boolean): Promise\<void> 7880 7881Enables or disables the microphone. This API uses a promise to return the result. 7882 7883**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture 7884 7885**Parameters** 7886 7887| Name| Type | Mandatory| Description | 7888| ------ | ------- | ---- | --------------------------------------------------------- | 7889| enable | boolean | Yes | Whether to enable or disable the microphone. The value **true** means to enable the microphone, and **false** means the opposite.| 7890 7891**Return value** 7892 7893| Type | Description | 7894| -------------- | --------------------------------------- | 7895| Promise\<void> | Promise that returns no value.| 7896 7897**Error codes** 7898 7899| ID| Error Message | 7900| -------- | -------------------------------- | 7901| 5400103 | IO error. Return by promise. | 7902| 5400105 | Service died. Return by promise. | 7903 7904**Example** 7905 7906```ts 7907import { BusinessError } from '@kit.BasicServicesKit'; 7908 7909avScreenCaptureRecorder.setMicEnabled(true).then(() => { 7910 console.info('Succeeded in setMicEnabled avScreenCaptureRecorder'); 7911}).catch((err: BusinessError) => { 7912 console.info('Failed to setMicEnabled avScreenCaptureRecorder, error: ' + err.message); 7913}) 7914``` 7915 7916### release<sup>12+</sup> 7917 7918release(): Promise\<void> 7919 7920Releases this **AVScreenCaptureRecorder** instance. This API uses a promise to return the result. 7921 7922**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture 7923 7924**Return value** 7925 7926| Type | Description | 7927| -------------- | --------------------------------- | 7928| Promise\<void> | Promise that returns no value.| 7929 7930**Error codes** 7931 7932| ID| Error Message | 7933| -------- | -------------------------------- | 7934| 5400103 | IO error. Return by promise. | 7935| 5400105 | Service died. Return by promise. | 7936 7937**Example** 7938 7939```ts 7940import { BusinessError } from '@kit.BasicServicesKit'; 7941 7942avScreenCaptureRecorder.release().then(() => { 7943 console.info('Succeeded in releasing avScreenCaptureRecorder'); 7944}).catch((err: BusinessError) => { 7945 console.info('Faile to release avScreenCaptureRecorder, error: ' + err.message); 7946}) 7947``` 7948 7949### on('stateChange')<sup>12+</sup> 7950 7951on(type: 'stateChange', callback: Callback\<AVScreenCaptureStateCode>): void 7952 7953Subscribes to screen capture state changes. An application can subscribe to only one screen capture state change event. When the application initiates multiple subscriptions to this event, the last subscription prevails. 7954 7955**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture 7956 7957**Parameters** 7958 7959| Name | Type | Mandatory| Description | 7960| -------- | -------- | ---- | ------------------------------------------------------------ | 7961| type | string | Yes | Event type, which is **'stateChange'** in this case. | 7962| callback | function | Yes | Callback invoked when the event is triggered. [AVScreenCaptureStateCode](#avscreencapturestatecode12) indicates the new state.| 7963 7964**Example** 7965 7966```ts 7967avScreenCaptureRecorder.on('stateChange', (state: media.AVScreenCaptureStateCode) => { 7968 console.info('avScreenCaptureRecorder stateChange to ' + state); 7969}) 7970``` 7971 7972### on('error')<sup>12+</sup> 7973 7974on(type: 'error', callback: ErrorCallback): void 7975 7976Subscribes to AVScreenCaptureRecorder errors. You can handle the errors based on the application logic. An application can subscribe to only one AVScreenCaptureRecorder error event. When the application initiates multiple subscriptions to this event, the last subscription prevails. 7977 7978**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture 7979 7980**Parameters** 7981 7982| Name | Type | Mandatory| Description | 7983| -------- | ------------- | ---- | --------------------------------------- | 7984| type | string | Yes | Event type, which is **'error'** in this case.| 7985| callback | [ErrorCallback](../apis-basic-services-kit/js-apis-base.md#errorcallback) | Yes | Callback invoked when the event is triggered. | 7986 7987**Error codes** 7988 7989| ID| Error Message | 7990| -------- | -------------------------------- | 7991| 201 | permission denied. | 7992| 5400103 | IO error. Return by ErrorCallback. | 7993| 5400105 | Service died. Return by ErrorCallback. | 7994 7995**Example** 7996 7997```ts 7998avScreenCaptureRecorder.on('error', (err: BusinessError) => { 7999 console.error('avScreenCaptureRecorder error:' + err.message); 8000}) 8001``` 8002 8003### off('stateChange')<sup>12+</sup> 8004 8005 off(type: 'stateChange', callback?: Callback\<AVScreenCaptureStateCode>): void 8006 8007Unsubscribes from screen capture state changes. You can specify a callback to cancel the specified subscription. 8008 8009**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture 8010 8011**Parameters** 8012 8013| Name | Type | Mandatory| Description | 8014| -------- | -------- | ---- | ------------------------------------------------------------ | 8015| type | string | Yes | Event type, which is **'stateChange'** in this case. | 8016| callback | function | No | Callback used for unsubscription. [AVScreenCaptureStateCode](#avscreencapturestatecode12) indicates the new state. If this parameter is not specified, the last subscription is canceled.| 8017 8018**Example** 8019 8020```ts 8021avScreenCaptureRecorder.off('stateChange'); 8022``` 8023 8024### off('error')<sup>12+</sup> 8025 8026off(type: 'error', callback?: ErrorCallback): void 8027 8028Unsubscribes from AVScreenCaptureRecorder errors. You can specify a callback to cancel the specified subscription. 8029 8030**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture 8031 8032**Parameters** 8033 8034| Name | Type | Mandatory| Description | 8035| -------- | -------- | ---- | ---------------------------------------------------------- | 8036| type | string | Yes | Event type, which is **'error'** in this case. | 8037| callback | [ErrorCallback](../apis-basic-services-kit/js-apis-base.md#errorcallback) | No | Callback used for unsubscription. If this parameter is not specified, the last subscription is canceled.| 8038 8039**Example** 8040 8041```ts 8042avScreenCaptureRecorder.off('error'); 8043``` 8044