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- Screen capture ([AVScreenCaptureRecorder](#avscreencapturerecorder12)<sup>12+</sup>) 22 23## Modules to Import 24 25```ts 26import { media } from '@kit.MediaKit'; 27``` 28 29## media.createAVPlayer<sup>9+</sup> 30 31createAVPlayer(callback: AsyncCallback\<AVPlayer>): void 32 33Creates an **AVPlayer** instance. This API uses an asynchronous callback to return the result. 34 35> **NOTE** 36> 37> - You are advised to create a maximum of 16 **AVPlayer** instances for an application in both audio and video playback scenarios.<!--Del--> 38> - 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--> 39 40**Atomic service API**: This API can be used in atomic services since API version 11. 41 42**System capability**: SystemCapability.Multimedia.Media.AVPlayer 43 44**Parameters** 45 46| Name | Type | Mandatory| Description | 47| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ | 48| 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.| 49 50**Error codes** 51 52For details about the error codes, see [Media Error Codes](errorcode-media.md). 53 54| ID| Error Message | 55| -------- | ------------------------------ | 56| 5400101 | No memory. Return by callback. | 57 58**Example** 59 60```ts 61import { BusinessError } from '@kit.BasicServicesKit'; 62 63let avPlayer: media.AVPlayer; 64media.createAVPlayer((error: BusinessError, video: media.AVPlayer) => { 65 if (video != null) { 66 avPlayer = video; 67 console.info('Succeeded in creating AVPlayer'); 68 } else { 69 console.error(`Failed to create AVPlayer, error message:${error.message}`); 70 } 71}); 72``` 73 74## media.createAVPlayer<sup>9+</sup> 75 76createAVPlayer(): Promise\<AVPlayer> 77 78Creates an **AVPlayer** instance. This API uses a promise to return the result. 79 80> **NOTE** 81> 82> - You are advised to create a maximum of 16 **AVPlayer** instances for an application in both audio and video playback scenarios.<!--Del--> 83> - 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--> 84 85**Atomic service API**: This API can be used in atomic services since API version 11. 86 87**System capability**: SystemCapability.Multimedia.Media.AVPlayer 88 89**Return value** 90 91| Type | Description | 92| ------------------------------- | ------------------------------------------------------------ | 93| 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.| 94 95**Error codes** 96 97For details about the error codes, see [Media Error Codes](errorcode-media.md). 98 99| ID| Error Message | 100| -------- | ----------------------------- | 101| 5400101 | No memory. Return by promise. | 102 103**Example** 104 105```ts 106import { BusinessError } from '@kit.BasicServicesKit'; 107 108let avPlayer: media.AVPlayer; 109media.createAVPlayer().then((video: media.AVPlayer) => { 110 if (video != null) { 111 avPlayer = video; 112 console.info('Succeeded in creating AVPlayer'); 113 } else { 114 console.error('Failed to create AVPlayer'); 115 } 116}).catch((error: BusinessError) => { 117 console.error(`Failed to create AVPlayer, error message:${error.message}`); 118}); 119``` 120 121## media.createAVRecorder<sup>9+</sup> 122 123createAVRecorder(callback: AsyncCallback\<AVRecorder>): void 124 125Creates an **AVRecorder** instance. This API uses an asynchronous callback to return the result. 126 127> **NOTE** 128> 129> - A maximum of 2 **AVRecorder** instances can be created. 130> - 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. 131 132**System capability**: SystemCapability.Multimedia.Media.AVRecorder 133 134**Parameters** 135 136| Name | Type | Mandatory| Description | 137| -------- | ------------------------------------------ | ---- | ------------------------------------------------------------ | 138| 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.| 139 140**Error codes** 141 142For details about the error codes, see [Media Error Codes](errorcode-media.md). 143 144| ID| Error Message | 145| -------- | ------------------------------ | 146| 5400101 | No memory. Return by callback. | 147 148**Example** 149 150```ts 151import { BusinessError } from '@kit.BasicServicesKit'; 152let avRecorder: media.AVRecorder; 153 154media.createAVRecorder((error: BusinessError, recorder: media.AVRecorder) => { 155 if (recorder != null) { 156 avRecorder = recorder; 157 console.info('Succeeded in creating AVRecorder'); 158 } else { 159 console.error(`Failed to create AVRecorder, error message:${error.message}`); 160 } 161}); 162``` 163 164## media.createAVRecorder<sup>9+</sup> 165 166createAVRecorder(): Promise\<AVRecorder> 167 168Creates an **AVRecorder** instance. This API uses a promise to return the result. 169 170> **NOTE** 171> 172> - A maximum of 2 **AVRecorder** instances can be created. 173> - 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. 174 175**Atomic service API**: This API can be used in atomic services since API version 12. 176 177**System capability**: SystemCapability.Multimedia.Media.AVRecorder 178 179**Return value** 180 181| Type | Description | 182| ------------------------------------ | ------------------------------------------------------------ | 183| 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.| 184 185**Error codes** 186 187For details about the error codes, see [Media Error Codes](errorcode-media.md). 188 189| ID| Error Message | 190| -------- | ----------------------------- | 191| 5400101 | No memory. Return by promise. | 192 193**Example** 194 195```ts 196import { BusinessError } from '@kit.BasicServicesKit'; 197 198let avRecorder: media.AVRecorder; 199media.createAVRecorder().then((recorder: media.AVRecorder) => { 200 if (recorder != null) { 201 avRecorder = recorder; 202 console.info('Succeeded in creating AVRecorder'); 203 } else { 204 console.error('Failed to create AVRecorder'); 205 } 206}).catch((error: BusinessError) => { 207 console.error(`Failed to create AVRecorder, error message:${error.message}`); 208}); 209``` 210 211## media.createAVTranscoder<sup>12+</sup> 212 213createAVTranscoder(): Promise\<AVTranscoder> 214 215Creates an **AVTranscoder** instance. This API uses a promise to return the result. 216 217> **NOTE** 218 219> A maximum of 2 **AVTranscoder** instances can be created. 220 221**System capability**: SystemCapability.Multimedia.Media.AVTranscoder 222 223**Return value** 224 225| Type | Description | 226| ------------------------------- | ------------------------------------------------------------ | 227| 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.| 228 229**Error codes** 230 231For details about the error codes, see [Media Error Codes](errorcode-media.md). 232 233| ID| Error Message | 234| -------- | ----------------------------- | 235| 5400101 | No memory. Return by promise. | 236 237**Example** 238 239```ts 240import { BusinessError } from '@kit.BasicServicesKit'; 241 242let avTranscoder: media.AVTranscoder; 243media.createAVTranscoder().then((transcoder: media.AVTranscoder) => { 244 if (transcoder != null) { 245 avTranscoder = transcoder; 246 console.info('Succeeded in creating AVTranscoder'); 247 } else { 248 console.error('Failed to create AVTranscoder'); 249 } 250}).catch((error: BusinessError) => { 251 console.error(`Failed to create AVTranscoder, error message:${error.message}`); 252}); 253``` 254 255## media.createAVMetadataExtractor<sup>11+</sup> 256 257createAVMetadataExtractor(callback: AsyncCallback\<AVMetadataExtractor>): void 258 259Creates an **AVMetadataExtractor** instance. This API uses an asynchronous callback to return the result. 260 261**System capability**: SystemCapability.Multimedia.Media.AVMetadataExtractor 262 263**Parameters** 264 265| Name | Type | Mandatory| Description | 266| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ | 267| 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.| 268 269**Error codes** 270 271For details about the error codes, see [Media Error Codes](errorcode-media.md). 272 273| ID| Error Message | 274| -------- | ------------------------------ | 275| 5400101 | No memory. Returned by callback. | 276 277**Example** 278 279```ts 280import { BusinessError } from '@kit.BasicServicesKit'; 281 282let avMetadataExtractor: media.AVMetadataExtractor; 283media.createAVMetadataExtractor((error: BusinessError, extractor: media.AVMetadataExtractor) => { 284 if (extractor != null) { 285 avMetadataExtractor = extractor; 286 console.info('Succeeded in creating AVMetadataExtractor'); 287 } else { 288 console.error(`Failed to create AVMetadataExtractor, error message:${error.message}`); 289 } 290}); 291``` 292 293## media.createAVMetadataExtractor<sup>11+</sup> 294 295createAVMetadataExtractor(): Promise\<AVMetadataExtractor> 296 297Creates an **AVMetadataExtractor** instance. This API uses a promise to return the result. 298 299**System capability**: SystemCapability.Multimedia.Media.AVMetadataExtractor 300 301**Error codes** 302 303For details about the error codes, see [Media Error Codes](errorcode-media.md). 304 305| ID| Error Message | 306| -------- | ------------------------------ | 307| 5400101 | No memory. Returned by promise. | 308 309**Example** 310 311```ts 312import { BusinessError } from '@kit.BasicServicesKit'; 313 314let avMetadataExtractor: media.AVMetadataExtractor; 315media.createAVMetadataExtractor().then((extractor: media.AVMetadataExtractor) => { 316 if (extractor != null) { 317 avMetadataExtractor = extractor; 318 console.info('Succeeded in creating AVMetadataExtractor'); 319 } else { 320 console.error(`Failed to create AVMetadataExtractor`); 321 } 322}).catch((error: BusinessError) => { 323 console.error(`Failed to create AVMetadataExtractor, error message:${error.message}`); 324}); 325``` 326 327## media.createSoundPool<sup>10+</sup> 328 329createSoundPool(maxStreams: number, audioRenderInfo: audio.AudioRendererInfo, callback: AsyncCallback\<SoundPool>): void 330 331Creates a **SoundPool** instance. This API uses an asynchronous callback to return the result. 332 333**System capability**: SystemCapability.Multimedia.Media.SoundPool 334 335**Parameters** 336 337| Name | Type | Mandatory| Description | 338| -------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | 339| maxStreams | number | Yes | Maximum number of streams that can be played by the **SoundPool** instance.| 340| 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.| 341| 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.| 342 343**Error codes** 344 345For details about the error codes, see [Media Error Codes](errorcode-media.md). 346 347| ID| Error Message | 348| -------- | ------------------------------ | 349| 5400101 | No memory. Return by callback. | 350 351**Example** 352 353```js 354import { audio } from '@kit.AudioKit'; 355 356let soundPool: media.SoundPool; 357let audioRendererInfo: audio.AudioRendererInfo = { 358 usage : audio.StreamUsage.STREAM_USAGE_MUSIC, 359 rendererFlags : 0 360} 361 362media.createSoundPool(5, audioRendererInfo, (error, soundPool_: media.SoundPool) => { 363 if (error) { 364 console.error(`Failed to createSoundPool`) 365 return; 366 } else { 367 soundPool = soundPool_; 368 console.info(`Succeeded in createSoundPool`) 369 } 370}); 371``` 372 373## media.createSoundPool<sup>10+</sup> 374 375createSoundPool(maxStreams: number, audioRenderInfo: audio.AudioRendererInfo): Promise\<SoundPool> 376 377Creates a **SoundPool** instance. This API uses a promise to return the result. 378 379**System capability**: SystemCapability.Multimedia.Media.SoundPool 380 381**Parameters** 382 383| Name | Type | Mandatory| Description | 384| -------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | 385| maxStreams | number | Yes | Maximum number of streams that can be played by the **SoundPool** instance.| 386| audioRenderInfo | [audio.AudioRendererInfo](../apis-audio-kit/js-apis-audio.md#audiorendererinfo8) | Yes | Audio renderer parameters.| 387 388**Return value** 389 390| Type | Description | 391| ----------------------------------------- | ------------------------------------------------------------ | 392| 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.| 393 394**Error codes** 395 396For details about the error codes, see [Media Error Codes](errorcode-media.md). 397 398| ID| Error Message | 399| -------- | ----------------------------- | 400| 5400101 | No memory. Return by promise. | 401 402**Example** 403 404```js 405import { audio } from '@kit.AudioKit'; 406import { BusinessError } from '@kit.BasicServicesKit'; 407 408let soundPool: media.SoundPool; 409let audioRendererInfo: audio.AudioRendererInfo = { 410 usage : audio.StreamUsage.STREAM_USAGE_MUSIC, 411 rendererFlags : 0 412} 413 414media.createSoundPool(5, audioRendererInfo).then((soundpool_: media.SoundPool) => { 415 if (soundpool_ != null) { 416 soundPool = soundpool_; 417 console.info('Succceeded in creating SoundPool'); 418 } else { 419 console.error('Failed to create SoundPool'); 420 } 421}, (error: BusinessError) => { 422 console.error(`soundpool catchCallback, error message:${error.message}`); 423}); 424``` 425 426## media.createAVScreenCaptureRecorder<sup>12+</sup> 427 428createAVScreenCaptureRecorder(): Promise\<AVScreenCaptureRecorder> 429 430Creates an **AVScreenCaptureRecorder** instance. This API uses a promise to return the result. 431 432**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture 433 434**Return value** 435 436| Type | Description | 437| ------------------------------------------------------------ | ------------------------------------------------------------ | 438| 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.| 439 440**Error codes** 441 442| ID| Error Message | 443| -------- | ------------------------------ | 444| 5400101 | No memory. Return by promise. | 445 446**Example** 447 448```ts 449import { BusinessError } from '@kit.BasicServicesKit'; 450 451let avScreenCaptureRecorder: media.AVScreenCaptureRecorder; 452media.createAVScreenCaptureRecorder().then((captureRecorder: media.AVScreenCaptureRecorder) => { 453 if (captureRecorder != null) { 454 avScreenCaptureRecorder = captureRecorder; 455 console.info('Succeeded in createAVScreenCaptureRecorder'); 456 } else { 457 console.error('Failed to createAVScreenCaptureRecorder'); 458 } 459}).catch((error: BusinessError) => { 460 console.error(`createAVScreenCaptureRecorder catchCallback, error message:${error.message}`); 461}); 462``` 463 464## SoundPool<sup>10+</sup> 465 466type SoundPool = _SoundPool 467 468SoundPool, which APIs for loading, unloading, playing, and stopping playing system sounds, setting the volume, and setting the number of loops. 469 470**System capability**: SystemCapability.Multimedia.Media.SoundPool 471 472| Type | Description | 473| -------- | ------------------------------ | 474| [SoundPool](js-apis-inner-multimedia-soundPool.md#soundpool) | Provides APIs for loading, unloading, playing, and stopping playing system sounds, setting the volume, and setting the number of loops.| 475 476## PlayParameters<sup>10+</sup> 477 478type PlayParameters = _PlayParameters 479 480Describes the playback parameters of the sound pool. 481 482**System capability**: SystemCapability.Multimedia.Media.SoundPool 483 484| Type | Description | 485| -------- | ------------------------------ | 486| [PlayParameters](js-apis-inner-multimedia-soundPool.md#playparameters) | Playback parameters of the sound pool.| 487 488## AVErrorCode<sup>9+</sup> 489 490Enumerates the [media error codes](errorcode-media.md). 491 492**Atomic service API**: This API can be used in atomic services since API version 11. 493 494**System capability**: SystemCapability.Multimedia.Media.Core 495 496| Name | Value | Description | 497| :------------------------------------ | ------- | ------------------------------------ | 498| AVERR_OK | 0 | The operation is successful. | 499| AVERR_NO_PERMISSION | 201 | No permission to perform the operation. | 500| AVERR_INVALID_PARAMETER | 401 | Invalid input parameter. | 501| AVERR_UNSUPPORT_CAPABILITY | 801 | Unsupported API. | 502| AVERR_NO_MEMORY | 5400101 | The system memory is insufficient or the number of services reaches the upper limit.| 503| 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.| 504| AVERR_IO | 5400103 | The data stream is abnormal. | 505| AVERR_TIMEOUT | 5400104 | The system or network response times out. | 506| AVERR_SERVICE_DIED | 5400105 | The service process is dead. | 507| AVERR_UNSUPPORT_FORMAT | 5400106 | The format of the media asset is not supported. | 508| AVERR_AUDIO_INTERRUPTED<sup>11+</sup> | 5400107 | The audio focus is interrupted. | 509| AVERR_IO_HOST_NOT_FOUND<sup>14+</sup> | 5411001 | Failed to parse the server address or connect to the server. <br>**Atomic service API**: This API can be used in atomic services since API version 14. | 510| AVERR_IO_CONNECTION_TIMEOUT<sup>14+</sup> | 5411002 | Network connection times out. <br>**Atomic service API**: This API can be used in atomic services since API version 14. | 511| AVERR_IO_NETWORK_ABNORMAL<sup>14+</sup> | 5411003 | Data or links are abnormal due to network exceptions. <br>**Atomic service API**: This API can be used in atomic services since API version 14. | 512| AVERR_IO_NETWORK_UNAVAILABLE<sup>14+</sup> | 5411004 | The network is disabled. <br>**Atomic service API**: This API can be used in atomic services since API version 14. | 513| AVERR_IO_NO_PERMISSION<sup>14+</sup> | 5411005 | No access permission. <br>**Atomic service API**: This API can be used in atomic services since API version 14. | 514| AVERR_IO_REQUEST_DENIED<sup>14+</sup> | 5411006 | The client request parameter is incorrect or exceeds the processing capability. <br>**Atomic service API**: This API can be used in atomic services since API version 14. | 515| AVERR_IO_RESOURCE_NOT_FOUND<sup>14+</sup> | 5411007 | No network resource is available. <br>**Atomic service API**: This API can be used in atomic services since API version 14. | 516| AVERR_IO_SSL_CLIENT_CERT_NEEDED<sup>14+</sup> | 5411008 | The server fails to verify the client certificate. <br>**Atomic service API**: This API can be used in atomic services since API version 14. | 517| AVERR_IO_SSL_CONNECTION_FAILED<sup>14+</sup> | 5411009 | The SSL connection fails. <br>**Atomic service API**: This API can be used in atomic services since API version 14. | 518| AVERR_IO_SSL_SERVER_CERT_UNTRUSTED<sup>14+</sup> | 5411010 | The client fails to verify the server certificate. <br>**Atomic service API**: This API can be used in atomic services since API version 14. | 519| AVERR_IO_UNSUPPORTED_REQUEST<sup>14+</sup> | 5411011 | The request is not supported due to a network protocol error. <br>**Atomic service API**: This API can be used in atomic services since API version 14. | 520 521## MediaType<sup>8+</sup> 522 523Enumerates the media types. 524 525**System capability**: SystemCapability.Multimedia.Media.Core 526 527| Name | Value | Description | 528| -------------- | --------------------- | ------------------- | 529| MEDIA_TYPE_AUD | 0 | Media.<br>**Atomic service API**: This API can be used in atomic services since API version 11. | 530| MEDIA_TYPE_VID | 1 | Video.<br>**Atomic service API**: This API can be used in atomic services since API version 11. | 531| MEDIA_TYPE_SUBTITLE<sup>12+</sup> | 2 | Subtitle.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 532 533## CodecMimeType<sup>8+</sup> 534 535Enumerates the codec MIME types. 536 537**System capability**: SystemCapability.Multimedia.Media.Core 538 539| Name | Value | Description | 540| ------------ | --------------------- | ------------------------ | 541| VIDEO_H263 | 'video/h263' | Video in H.263 format. | 542| VIDEO_AVC | 'video/avc' | Video in AVC format. | 543| VIDEO_MPEG2 | 'video/mpeg2' | Video in MPEG-2 format. | 544| VIDEO_MPEG4 | 'video/mp4v-es' | Video in MPEG-4 format. | 545| VIDEO_VP8 | 'video/x-vnd.on2.vp8' | Video in VP8 format. | 546| VIDEO_HEVC<sup>11+</sup> | 'video/hevc' | Video in H.265 format.| 547| 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.| 548| AUDIO_VORBIS | 'audio/vorbis' | Audio in Vorbis format. | 549| AUDIO_FLAC | 'audio/flac' | Audio in FLAC format. | 550| AUDIO_MP3<sup>12+</sup> | 'audio/mpeg' | Audio in MPEG format. | 551| AUDIO_G711MU<sup>12+</sup> | 'audio/g711mu' | Audio in G.711 μ-law format.| 552 553## MediaDescriptionKey<sup>8+</sup> 554 555Enumerates the media description keys. 556 557**System capability**: SystemCapability.Multimedia.Media.Core 558 559| Name | Value | Description | 560| ------------------------ | --------------- | ------------------------------------------------------------ | 561| 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.| 562| 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.| 563| 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.| 564| 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.| 565| 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.| 566| 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.| 567| 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.| 568| 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.| 569| 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.| 570| 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.| 571| 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.| 572| MD_KEY_LANGUAGE<sup>12+</sup> | 'language' | Subtitle language, which is a string.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 573| 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.| 574| 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.| 575 576## PlaybackInfoKey<sup>12+</sup> 577 578Enumerates the playback description keys. 579 580**System capability**: SystemCapability.Multimedia.Media.Core 581 582| Name | Value | Description | 583| ------------------------ | --------------- | ------------------------------------------------------------ | 584| SERVER_IP_ADDRESS | 'server_ip_address' | IP address of the server, which is a string. | 585| AVG_DOWNLOAD_RATE | 'average_download_rate'| Average download rate, which is a number, in units of bit/s.| 586| DOWNLOAD_RATE | 'download_rate' | Download rate in one second, which is a number, in units of bit/s.| 587| 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.| 588| BUFFER_DURATION | 'buffer_duration' | Duration that the cached data can be played, which is a number, in units of seconds.| 589 590## BufferingInfoType<sup>8+</sup> 591 592Enumerates the buffering event types. 593 594**Atomic service API**: This API can be used in atomic services since API version 12. 595 596**System capability**: SystemCapability.Multimedia.Media.Core 597 598| Name | Value | Description | 599| ----------------- | ---- | -------------------------------- | 600| BUFFERING_START | 1 | Buffering starts. When this event is triggered, the player pauses the playback.<br>**Atomic service API**: This API can be used in atomic services since API version 12. | 601| BUFFERING_END | 2 | Buffering ends. When this event is triggered, the player resumes the playback.<br>**Atomic service API**: This API can be used in atomic services since API version 12. | 602| BUFFERING_PERCENT | 3 | Buffering percentage. You can use this event to monitor the buffering status.<br>**Atomic service API**: This API can be used in atomic services since API version 12. | 603| CACHED_DURATION | 4 | Estimated duration, in ms, that the buffered data can be played. This event is triggered once the data change amount in the buffer exceeds 500 ms. You can use this event to develop a progress bar.<br>**Atomic service API**: This API can be used in atomic services since API version 12. | 604 605## StateChangeReason<sup>9+</sup> 606 607Enumerates the reasons for the state transition of the **AVPlayer** or **AVRecorder** instance. The enum value is reported together with **state**. 608 609**Atomic service API**: This API can be used in atomic services since API version 11. 610 611**System capability**: SystemCapability.Multimedia.Media.Core 612 613| Name | Value | Description | 614| ---------- | ---- | ------------------------------------------------------------ | 615| USER | 1 | State transition triggered by user behavior. It happens when a user or the client calls an API.| 616| 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.| 617 618## AVPlayer<sup>9+</sup> 619 620A 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. 621 622For 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). 623 624> **NOTE** 625> 626> When using the **AVPlayer** instance, you are advised to register the following callbacks to proactively obtain status changes: 627> - [on('stateChange')](#onstatechange9): listens for AVPlayer state changes. 628> - [on('error')](#onerror9): listens for error events. 629 630### Attributes 631 632**System capability**: SystemCapability.Multimedia.Media.AVPlayer 633 634| Name | Type | Read-Only| Optional| Description | 635| --------------------------------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | 636| 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.| 637| 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.| 638| 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.| 639| 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.| 640| 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.| 641| 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.| 642| 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.| 643| 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.| 644| 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.| 645| 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. | 646| 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.| 647| 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.| 648| 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.| 649| 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.| 650 651### on('stateChange')<sup>9+</sup> 652 653on(type: 'stateChange', callback: OnAVPlayerStateChangeHandle): void 654 655Subscribes to AVPlayer state changes. 656 657**Atomic service API**: This API can be used in atomic services since API version 11. 658 659**System capability**: SystemCapability.Multimedia.Media.AVPlayer 660 661**Parameters** 662 663| Name | Type | Mandatory| Description | 664| -------- | -------- | ---- | ------------------------------------------------------------ | 665| type | string | Yes | Event type, which is **'stateChange'** in this case. This event can be triggered by both user operations and the system.| 666| callback | [OnAVPlayerStateChangeHandle](#onavplayerstatechangehandle12) | Yes | Callback invoked when the event is triggered.| 667 668**Example** 669 670```ts 671avPlayer.on('stateChange', async (state: string, reason: media.StateChangeReason) => { 672 switch (state) { 673 case 'idle': 674 console.info('state idle called'); 675 break; 676 case 'initialized': 677 console.info('initialized prepared called'); 678 break; 679 case 'prepared': 680 console.info('state prepared called'); 681 break; 682 case 'playing': 683 console.info('state playing called'); 684 break; 685 case 'paused': 686 console.info('state paused called'); 687 break; 688 case 'completed': 689 console.info('state completed called'); 690 break; 691 case 'stopped': 692 console.info('state stopped called'); 693 break; 694 case 'released': 695 console.info('state released called'); 696 break; 697 case 'error': 698 console.info('state error called'); 699 break; 700 default: 701 console.info('unknown state :' + state); 702 break; 703 } 704}) 705``` 706 707### off('stateChange')<sup>9+</sup> 708 709off(type: 'stateChange', callback?: OnAVPlayerStateChangeHandle): void 710 711Unsubscribes from AVPlayer state changes. 712 713**Atomic service API**: This API can be used in atomic services since API version 11. 714 715**System capability**: SystemCapability.Multimedia.Media.AVPlayer 716 717**Parameters** 718 719| Name| Type | Mandatory| Description | 720| ------ | ------ | ---- | ----------------------------------------------------- | 721| type | string | Yes | Event type, which is **'stateChange'** in this case.| 722| callback | [OnAVPlayerStateChangeHandle](#onavplayerstatechangehandle12) | No | Callback invoked when the event is triggered.<br>This parameter is supported since API version 12.| 723 724**Example** 725 726```ts 727avPlayer.off('stateChange') 728``` 729 730### on('error')<sup>9+</sup> 731 732on(type: 'error', callback: ErrorCallback): void 733 734Subscribes 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. 735 736**Atomic service API**: This API can be used in atomic services since API version 11. 737 738**System capability**: SystemCapability.Multimedia.Media.AVPlayer 739 740**Parameters** 741 742| Name | Type | Mandatory| Description | 743| -------- | -------- | ---- | ------------------------------------------------------------ | 744| type | string | Yes | Event type, which is **'error'** in this case. This event can be triggered by both user operations and the system.| 745| callback | [ErrorCallback](../apis-basic-services-kit/js-apis-base.md#errorcallback) | Yes | Callback used to return the error code ID and error message.| 746 747**Error codes** 748 749For details about the error codes, see [Media Error Codes](errorcode-media.md). 750 751In API versions 9 to 13, error code 5400103 is reported when the network or server data flow is abnormal. In API version 14 and later, error codes 5411001 to 5411011 are reported for refined management. 752 753| ID| Error Message | 754| -------- | --------------------- | 755| 201 | Permission denied | 756| 401 | The parameter check failed. | 757| 801 | Capability not supported. | 758| 5400101 | No memory. | 759| 5400102 | Operation not allowed.| 760| 5400103 | I/O error | 761| 5400104 | Time out | 762| 5400105 | Service died. | 763| 5400106 | Unsupported format. | 764| 5411001 | IO can not find host. | 765| 5411002 | IO connection timeout. | 766| 5411003 | IO network abnormal. | 767| 5411004 | IO network unavailable. | 768| 5411005 | IO no permission. | 769| 5411006 | IO request denied. | 770| 5411007 | IO resource not found. | 771| 5411008 | IO SSL client cert needed. | 772| 5411009 | IO SSL connect fail. | 773| 5411010 | IO SSL server cert untrusted. | 774| 5411011 | IO unsupported request. | 775 776**Example** 777 778```ts 779import { BusinessError } from '@kit.BasicServicesKit'; 780 781avPlayer.on('error', (error: BusinessError) => { 782 console.info('error happened,and error message is :' + error.message) 783 console.info('error happened,and error code is :' + error.code) 784}) 785``` 786 787### off('error')<sup>9+</sup> 788 789off(type: 'error', callback?: ErrorCallback): void 790 791Unsubscribes from AVPlayer errors. 792 793**Atomic service API**: This API can be used in atomic services since API version 11. 794 795**System capability**: SystemCapability.Multimedia.Media.AVPlayer 796 797**Parameters** 798 799| Name| Type | Mandatory| Description | 800| ------ | ------ | ---- | ----------------------------------------- | 801| type | string | Yes | Event type, which is **'error'** in this case.| 802| 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.| 803 804**Example** 805 806```ts 807avPlayer.off('error') 808``` 809 810### setMediaSource<sup>12+</sup> 811 812setMediaSource(src:MediaSource, strategy?: PlaybackStrategy): Promise\<void> 813 814Sets 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. 815 816**Atomic service API**: This API can be used in atomic services since API version 12. 817 818**System capability**: SystemCapability.Multimedia.Media.AVPlayer 819 820**Parameters** 821 822| Name | Type | Mandatory| Description | 823| -------- | -------- | ---- | -------------------- | 824| src | [MediaSource](#mediasource12) | Yes | Source of the streaming media to pre-download.| 825| strategy | [PlaybackStrategy](#playbackstrategy12) | No | strategy for playing the pre-downloaded streaming media.| 826 827**Return value** 828 829| Type | Description | 830| -------------- | ------------------------------------------ | 831| Promise\<void> | Promise that returns no value.| 832 833**Error codes** 834 835For details about the error codes, see [Media Error Codes](errorcode-media.md). 836 837| ID| Error Message | 838| -------- | ----------------------------------------- | 839| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 840| 5400102 | Operation not allowed. Return by promise. | 841 842**Example** 843 844```ts 845let player = await media.createAVPlayer(); 846let headers: Record<string, string> = {"User-Agent" : "User-Agent-Value"}; 847let mediaSource : media.MediaSource = media.createMediaSourceWithUrl("http://xxx", headers); 848let playStrategy : media.PlaybackStrategy = {preferredWidth: 1, preferredHeight: 2, preferredBufferDuration: 3, preferredHdr: false}; 849player.setMediaSource(mediaSource, playStrategy); 850``` 851 852### setPlaybackStrategy<sup>12+</sup> 853 854setPlaybackStrategy(strategy: PlaybackStrategy): Promise\<void> 855 856Sets a playback strategy. This API can be called only when the AVPlayer is in the initialized state. 857 858**Atomic service API**: This API can be used in atomic services since API version 12. 859 860**System capability**: SystemCapability.Multimedia.Media.AVPlayer 861 862**Parameters** 863 864| Name | Type | Mandatory| Description | 865| -------- | -------- | ---- | -------------------- | 866| strategy | [PlaybackStrategy](#playbackstrategy12) | Yes | Playback strategy.| 867 868**Return value** 869 870| Type | Description | 871| -------------- | ------------------------------------ | 872| Promise\<void> | Promise that returns no value.| 873 874**Error codes** 875 876For details about the error codes, see [Media Error Codes](errorcode-media.md). 877 878| ID| Error Message | 879| -------- | ----------------------------------------- | 880| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. 2. Parameter verification failed. | 881| 5400102 | Operation not allowed. Return by promise. | 882 883**Example** 884 885```ts 886import { common } from '@kit.AbilityKit'; 887 888let player = await media.createAVPlayer(); 889let context = getContext(this) as common.UIAbilityContext 890let fileDescriptor = await context.resourceManager.getRawFd('xxx.mp4') 891player.fdSrc = fileDescriptor 892let playStrategy : media.PlaybackStrategy = {preferredWidth: 1, preferredHeight: 2, preferredBufferDuration: 3, 893 preferredHdr: false, mutedMediaType: media.MediaType.MEDIA_TYPE_AUD}; 894player.setPlaybackStrategy(playStrategy); 895``` 896 897### prepare<sup>9+</sup> 898 899prepare(callback: AsyncCallback\<void>): void 900 901Prepares 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. 902 903**Atomic service API**: This API can be used in atomic services since API version 11. 904 905**System capability**: SystemCapability.Multimedia.Media.AVPlayer 906 907**Parameters** 908 909| Name | Type | Mandatory| Description | 910| -------- | -------- | ---- | -------------------- | 911| callback | AsyncCallback\<void> | Yes | Callback used to return the result.| 912 913**Error codes** 914 915For details about the error codes, see [Media Error Codes](errorcode-media.md). 916 917| ID| Error Message | 918| -------- | ------------------------------------------ | 919| 5400102 | Operation not allowed. Return by callback. | 920| 5400106 | Unsupported format. Return by callback. | 921 922**Example** 923 924```ts 925import { BusinessError } from '@kit.BasicServicesKit'; 926 927avPlayer.prepare((err: BusinessError) => { 928 if (err) { 929 console.error('Failed to prepare,error message is :' + err.message) 930 } else { 931 console.info('Succeeded in preparing'); 932 } 933}) 934``` 935 936### prepare<sup>9+</sup> 937 938prepare(): Promise\<void> 939 940Prepares 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. 941 942**Atomic service API**: This API can be used in atomic services since API version 11. 943 944**System capability**: SystemCapability.Multimedia.Media.AVPlayer 945 946**Return value** 947 948| Type | Description | 949| -------------- | ------------------------- | 950| Promise\<void> | Promise that returns no value.| 951 952**Error codes** 953 954For details about the error codes, see [Media Error Codes](errorcode-media.md). 955 956| ID| Error Message | 957| -------- | ----------------------------------------- | 958| 5400102 | Operation not allowed. Return by promise. | 959| 5400106 | Unsupported format. Return by promise. | 960 961**Example** 962 963```ts 964import { BusinessError } from '@kit.BasicServicesKit'; 965 966avPlayer.prepare().then(() => { 967 console.info('Succeeded in preparing'); 968}, (err: BusinessError) => { 969 console.error('Failed to prepare,error message is :' + err.message) 970}) 971``` 972 973### setMediaMuted<sup>12+</sup> 974 975setMediaMuted(mediaType: MediaType, muted: boolean ): Promise\<void> 976 977Mutes 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. 978 979**Atomic service API**: This API can be used in atomic services since API version 12. 980 981**System capability**: SystemCapability.Multimedia.Media.AVPlayer 982 983**Parameters** 984 985| Name | Type | Mandatory| Description | 986| -------- | -------- | ---- | -------------------- | 987| mediaType | [MediaType](#mediatype8) | Yes | Media type.| 988| muted | boolean | Yes | Whether to mute the audio.| 989 990**Return value** 991 992| Type | Description | 993| -------------- | ------------------------- | 994| Promise\<void> | Promise that returns no value.| 995 996**Error codes** 997 998For details about the error codes, see [Media Error Codes](errorcode-media.md). 999 1000| ID| Error Message| 1001| -------- | ----------------------------------------- | 1002| 401 | The parameter check failed. Return by promise. | 1003| 5400102 | Operation not allowed. Return by promise. | 1004 1005**Example** 1006 1007```ts 1008import { BusinessError } from '@kit.BasicServicesKit'; 1009 1010avPlayer.prepare().then(() => { 1011 console.info('Succeeded in preparing'); 1012 avPlayer.setMediaMuted(media.MediaType.MEDIA_TYPE_AUD, true) 1013}, (err: BusinessError) => { 1014 console.error('Failed to prepare,error message is :' + err.message) 1015}) 1016``` 1017 1018### play<sup>9+</sup> 1019 1020play(callback: AsyncCallback\<void>): void 1021 1022Starts 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. 1023 1024**Atomic service API**: This API can be used in atomic services since API version 11. 1025 1026**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1027 1028**Parameters** 1029 1030| Name | Type | Mandatory| Description | 1031| -------- | -------- | ---- | -------------------- | 1032| callback | AsyncCallback\<void> | Yes | Callback used to return the result.| 1033 1034**Error codes** 1035 1036For details about the error codes, see [Media Error Codes](errorcode-media.md). 1037 1038| ID| Error Message | 1039| -------- | ------------------------------------------ | 1040| 5400102 | Operation not allowed. Return by callback. | 1041 1042**Example** 1043 1044```ts 1045import { BusinessError } from '@kit.BasicServicesKit'; 1046 1047avPlayer.play((err: BusinessError) => { 1048 if (err) { 1049 console.error('Failed to play,error message is :' + err.message) 1050 } else { 1051 console.info('Succeeded in playing'); 1052 } 1053}) 1054``` 1055 1056### play<sup>9+</sup> 1057 1058play(): Promise\<void> 1059 1060Starts 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. 1061 1062**Atomic service API**: This API can be used in atomic services since API version 11. 1063 1064**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1065 1066**Return value** 1067 1068| Type | Description | 1069| -------------- | ------------------------- | 1070| Promise\<void> | Promise that returns no value.| 1071 1072**Error codes** 1073 1074For details about the error codes, see [Media Error Codes](errorcode-media.md). 1075 1076| ID| Error Message | 1077| -------- | ----------------------------------------- | 1078| 5400102 | Operation not allowed. Return by promise. | 1079 1080**Example** 1081 1082```ts 1083import { BusinessError } from '@kit.BasicServicesKit'; 1084 1085avPlayer.play().then(() => { 1086 console.info('Succeeded in playing'); 1087}, (err: BusinessError) => { 1088 console.error('Failed to play,error message is :' + err.message) 1089}) 1090``` 1091 1092### pause<sup>9+</sup> 1093 1094pause(callback: AsyncCallback\<void>): void 1095 1096Pauses 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. 1097 1098**Atomic service API**: This API can be used in atomic services since API version 11. 1099 1100**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1101 1102**Parameters** 1103 1104| Name | Type | Mandatory| Description | 1105| -------- | -------- | ---- | -------------------- | 1106| callback | AsyncCallback\<void> | Yes | Callback used to return the result.| 1107 1108**Error codes** 1109 1110For details about the error codes, see [Media Error Codes](errorcode-media.md). 1111 1112| ID| Error Message | 1113| -------- | ------------------------------------------ | 1114| 5400102 | Operation not allowed. Return by callback. | 1115 1116**Example** 1117 1118```ts 1119import { BusinessError } from '@kit.BasicServicesKit'; 1120 1121avPlayer.pause((err: BusinessError) => { 1122 if (err) { 1123 console.error('Failed to pause,error message is :' + err.message) 1124 } else { 1125 console.info('Succeeded in pausing'); 1126 } 1127}) 1128``` 1129 1130### pause<sup>9+</sup> 1131 1132pause(): Promise\<void> 1133 1134Pauses 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. 1135 1136**Atomic service API**: This API can be used in atomic services since API version 11. 1137 1138**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1139 1140**Return value** 1141 1142| Type | Description | 1143| -------------- | ------------------------- | 1144| Promise\<void> | Promise that returns no value.| 1145 1146**Error codes** 1147 1148For details about the error codes, see [Media Error Codes](errorcode-media.md). 1149 1150| ID| Error Message | 1151| -------- | ----------------------------------------- | 1152| 5400102 | Operation not allowed. Return by promise. | 1153 1154**Example** 1155 1156```ts 1157import { BusinessError } from '@kit.BasicServicesKit'; 1158 1159avPlayer.pause().then(() => { 1160 console.info('Succeeded in pausing'); 1161}, (err: BusinessError) => { 1162 console.error('Failed to pause,error message is :' + err.message) 1163}) 1164``` 1165 1166### stop<sup>9+</sup> 1167 1168stop(callback: AsyncCallback\<void>): void 1169 1170Stops 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. 1171 1172**Atomic service API**: This API can be used in atomic services since API version 11. 1173 1174**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1175 1176**Parameters** 1177 1178| Name | Type | Mandatory| Description | 1179| -------- | -------- | ---- | -------------------- | 1180| callback | AsyncCallback\<void> | Yes | Callback used to return the result.| 1181 1182**Error codes** 1183 1184For details about the error codes, see [Media Error Codes](errorcode-media.md). 1185 1186| ID| Error Message | 1187| -------- | ------------------------------------------ | 1188| 5400102 | Operation not allowed. Return by callback. | 1189 1190**Example** 1191 1192```ts 1193import { BusinessError } from '@kit.BasicServicesKit'; 1194 1195avPlayer.stop((err: BusinessError) => { 1196 if (err) { 1197 console.error('Failed to stop,error message is :' + err.message) 1198 } else { 1199 console.info('Succeeded in stopping'); 1200 } 1201}) 1202``` 1203 1204### stop<sup>9+</sup> 1205 1206stop(): Promise\<void> 1207 1208Stops 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. 1209 1210**Atomic service API**: This API can be used in atomic services since API version 11. 1211 1212**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1213 1214**Return value** 1215 1216| Type | Description | 1217| -------------- | ------------------------- | 1218| Promise\<void> | Promise that returns no value.| 1219 1220**Error codes** 1221 1222For details about the error codes, see [Media Error Codes](errorcode-media.md). 1223 1224| ID| Error Message | 1225| -------- | ----------------------------------------- | 1226| 5400102 | Operation not allowed. Return by promise. | 1227 1228**Example** 1229 1230```ts 1231import { BusinessError } from '@kit.BasicServicesKit'; 1232 1233avPlayer.stop().then(() => { 1234 console.info('Succeeded in stopping'); 1235}, (err: BusinessError) => { 1236 console.error('Failed to stop,error message is :' + err.message) 1237}) 1238``` 1239 1240### reset<sup>9+</sup> 1241 1242reset(callback: AsyncCallback\<void>): void 1243 1244Resets 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. 1245 1246**Atomic service API**: This API can be used in atomic services since API version 11. 1247 1248**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1249 1250**Parameters** 1251 1252| Name | Type | Mandatory| Description | 1253| -------- | -------- | ---- | -------------------- | 1254| callback | AsyncCallback\<void> | Yes | Callback used to return the result.| 1255 1256**Error codes** 1257 1258For details about the error codes, see [Media Error Codes](errorcode-media.md). 1259 1260| ID| Error Message | 1261| -------- | ------------------------------------------ | 1262| 5400102 | Operation not allowed. Return by callback. | 1263 1264**Example** 1265 1266```ts 1267import { BusinessError } from '@kit.BasicServicesKit'; 1268 1269avPlayer.reset((err: BusinessError) => { 1270 if (err) { 1271 console.error('Failed to reset,error message is :' + err.message) 1272 } else { 1273 console.info('Succeeded in resetting'); 1274 } 1275}) 1276``` 1277 1278### reset<sup>9+</sup> 1279 1280reset(): Promise\<void> 1281 1282Resets 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. 1283 1284**Atomic service API**: This API can be used in atomic services since API version 11. 1285 1286**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1287 1288**Return value** 1289 1290| Type | Description | 1291| -------------- | ------------------------- | 1292| Promise\<void> | Promise that returns no value.| 1293 1294**Error codes** 1295 1296For details about the error codes, see [Media Error Codes](errorcode-media.md). 1297 1298| ID| Error Message | 1299| -------- | ----------------------------------------- | 1300| 5400102 | Operation not allowed. Return by promise. | 1301 1302**Example** 1303 1304```ts 1305import { BusinessError } from '@kit.BasicServicesKit'; 1306 1307avPlayer.reset().then(() => { 1308 console.info('Succeeded in resetting'); 1309}, (err: BusinessError) => { 1310 console.error('Failed to reset,error message is :' + err.message) 1311}) 1312``` 1313 1314### release<sup>9+</sup> 1315 1316release(callback: AsyncCallback\<void>): void 1317 1318Releases 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. 1319 1320**Atomic service API**: This API can be used in atomic services since API version 11. 1321 1322**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1323 1324**Parameters** 1325 1326| Name | Type | Mandatory| Description | 1327| -------- | -------- | ---- | -------------------- | 1328| callback | AsyncCallback\<void> | Yes | Callback used to return the result.| 1329 1330**Error codes** 1331 1332For details about the error codes, see [Media Error Codes](errorcode-media.md). 1333 1334| ID| Error Message | 1335| -------- | ------------------------------------------ | 1336| 5400102 | Operation not allowed. Return by callback. | 1337 1338**Example** 1339 1340```ts 1341import { BusinessError } from '@kit.BasicServicesKit'; 1342 1343avPlayer.release((err: BusinessError) => { 1344 if (err) { 1345 console.error('Failed to release,error message is :' + err.message) 1346 } else { 1347 console.info('Succeeded in releasing'); 1348 } 1349}) 1350``` 1351 1352### release<sup>9+</sup> 1353 1354release(): Promise\<void> 1355 1356Releases 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. 1357 1358**Atomic service API**: This API can be used in atomic services since API version 11. 1359 1360**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1361 1362**Return value** 1363 1364| Type | Description | 1365| -------------- | ------------------------- | 1366| Promise\<void> | Promise that returns no value.| 1367 1368**Error codes** 1369 1370For details about the error codes, see [Media Error Codes](errorcode-media.md). 1371 1372| ID| Error Message | 1373| -------- | ----------------------------------------- | 1374| 5400102 | Operation not allowed. Return by promise. | 1375 1376**Example** 1377 1378```ts 1379import { BusinessError } from '@kit.BasicServicesKit'; 1380 1381avPlayer.release().then(() => { 1382 console.info('Succeeded in releasing'); 1383}, (err: BusinessError) => { 1384 console.error('Failed to release,error message is :' + err.message) 1385}) 1386``` 1387 1388### getTrackDescription<sup>9+</sup> 1389 1390getTrackDescription(callback: AsyncCallback\<Array\<MediaDescription>>): void 1391 1392Obtains 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. 1393 1394**Atomic service API**: This API can be used in atomic services since API version 11. 1395 1396**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1397 1398**Parameters** 1399 1400| Name | Type | Mandatory| Description | 1401| -------- | ------------------------------------------------------------ | ---- | -------------------------------------------- | 1402| 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.| 1403 1404**Error codes** 1405 1406For details about the error codes, see [Media Error Codes](errorcode-media.md). 1407 1408| ID| Error Message | 1409| -------- | ------------------------------------------ | 1410| 5400102 | Operation not allowed. Return by callback. | 1411 1412**Example** 1413 1414```ts 1415import { BusinessError } from '@kit.BasicServicesKit'; 1416 1417avPlayer.getTrackDescription((error: BusinessError, arrList: Array<media.MediaDescription>) => { 1418 if ((arrList) != null) { 1419 console.info('Succeeded in doing getTrackDescription'); 1420 } else { 1421 console.error(`Failed to do getTrackDescription, error:${error}`); 1422 } 1423}); 1424``` 1425 1426### getTrackDescription<sup>9+</sup> 1427 1428getTrackDescription(): Promise\<Array\<MediaDescription>> 1429 1430Obtains 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. 1431 1432**Atomic service API**: This API can be used in atomic services since API version 11. 1433 1434**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1435 1436**Return value** 1437 1438| Type | Description | 1439| ------------------------------------------------------ | ------------------------------------------------- | 1440| Promise<Array<[MediaDescription](#mediadescription8)>> | Promise used to return the MediaDescription array that holds the audio and video track information.| 1441 1442**Error codes** 1443 1444For details about the error codes, see [Media Error Codes](errorcode-media.md). 1445 1446| ID| Error Message | 1447| -------- | ----------------------------------------- | 1448| 5400102 | Operation not allowed. Return by promise. | 1449 1450**Example** 1451 1452```ts 1453import { BusinessError } from '@kit.BasicServicesKit'; 1454 1455avPlayer.getTrackDescription().then((arrList: Array<media.MediaDescription>) => { 1456 console.info('Succeeded in getting TrackDescription'); 1457}).catch((error: BusinessError) => { 1458 console.error(`Failed to get TrackDescription, error:${error}`); 1459}); 1460``` 1461 1462### getSelectedTracks<sup>12+</sup> 1463 1464getSelectedTracks(): Promise\<Array\<number>> 1465 1466Obtains 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. 1467 1468**Atomic service API**: This API can be used in atomic services since API version 12. 1469 1470**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1471 1472**Return value** 1473 1474| Type | Description | 1475| ------------------------------------------------------ | ------------------------------------------------- | 1476| Promise<Array<[number]>> | Promise used to return the index array.| 1477 1478**Error codes** 1479 1480For details about the error codes, see [Media Error Codes](errorcode-media.md). 1481 1482| ID| Error Message | 1483| -------- | ----------------------------------------- | 1484| 5400102 | Operation not allowed. | 1485 1486**Example** 1487 1488```ts 1489import { BusinessError } from '@kit.BasicServicesKit'; 1490 1491avPlayer.getSelectedTracks().then((arrList: Array<number>) => { 1492 console.info('Succeeded in getting SelectedTracks'); 1493}).catch((error: BusinessError) => { 1494 console.error(`Failed to get SelectedTracks, error:${error}`); 1495}); 1496``` 1497 1498### getPlaybackInfo<sup>12+</sup> 1499 1500getPlaybackInfo(): Promise\<PlaybackInfo> 1501 1502Obtains 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. 1503 1504**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1505 1506**Return value** 1507 1508| Type | Description | 1509| ------------------------------------------------------ | ------------------------------------------------- | 1510| Promise<[PlaybackInfo](#playbackinfo12)> | Promise used to return **PlaybackInfo**.| 1511 1512**Example** 1513 1514```ts 1515import { BusinessError } from '@kit.BasicServicesKit'; 1516 1517let avPlayer: media.AVPlayer | undefined = undefined; 1518let playbackInfo: media.PlaybackInfo | undefined = undefined; 1519media.createAVPlayer(async (err: BusinessError, player: media.AVPlayer) => { 1520 if (player != null) { 1521 avPlayer = player; 1522 console.info(`Succeeded in creating AVPlayer`); 1523 if (avPlayer) { 1524 try { 1525 playbackInfo = await avPlayer.getPlaybackInfo(); 1526 console.info(`AVPlayer getPlaybackInfo = ${JSON.stringify(playbackInfo)}`); // Print PlaybackInfo. 1527 } catch (error) { 1528 console.error(`error = ${error}`); 1529 } 1530 } 1531 } else { 1532 console.error(`Failed to create AVPlayer, error message:${err.message}`); 1533 } 1534}); 1535``` 1536 1537### selectTrack<sup>12+</sup> 1538 1539selectTrack(index: number, mode?: SwitchMode): Promise\<void> 1540 1541Selects a track when the AVPlayer is used to play a resource with multiple audio and video tracks. This API uses a promise to return the result. 1542 1543**Atomic service API**: This API can be used in atomic services since API version 12. 1544 1545**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1546 1547**Parameters** 1548 1549| Name | Type | Mandatory| Description | 1550| -------- | -------- | ---- | -------------------- | 1551| index | number | Yes | Index of the track. You can call [getTrackDescription](#gettrackdescription9-1) to obtain all track information [MediaDescription](#mediadescription8) of the current resource.| 1552| mode | [SwitchMode](#switchmode12) | No | Video track switch mode. The default mode is **SMOOTH**. This parameter takes effect only for the switch of a video track for DASH streams.| 1553 1554**Return value** 1555 1556| Type | Description | 1557| -------------- | ------------------------- | 1558| Promise\<void> | Promise that returns no value.| 1559 1560**Error codes** 1561 1562For details about the error codes, see [Media Error Codes](errorcode-media.md). 1563 1564| ID| Error Message | 1565| -------- | ----------------------------------------- | 1566| 401 | The parameter check failed. Return by promise. | 1567| 5400102 | Operation not allowed. Return by promise. | 1568 1569**Example** 1570 1571```ts 1572import { BusinessError } from '@kit.BasicServicesKit'; 1573 1574let avPlayer: media.AVPlayer = await media.createAVPlayer(); 1575let audioTrackIndex: Object = 0; 1576avPlayer.getTrackDescription((error: BusinessError, arrList: Array<media.MediaDescription>) => { 1577 if (arrList != null) { 1578 for (let i = 0; i < arrList.length; i++) { 1579 if (i != 0) { 1580 // Obtain the audio track list. 1581 audioTrackIndex = arrList[i][media.MediaDescriptionKey.MD_KEY_TRACK_INDEX]; 1582 } 1583 } 1584 } else { 1585 console.error(`Failed to get TrackDescription, error:${error}`); 1586 } 1587}); 1588 1589// Select an audio track. 1590avPlayer.selectTrack(parseInt(audioTrackIndex.toString())); 1591``` 1592 1593### deselectTrack<sup>12+</sup> 1594 1595deselectTrack(index: number): Promise\<void> 1596 1597Deselects a track when the AVPlayer is used to play a resource with multiple audio and video tracks. This API uses a promise to return the result. 1598 1599**Atomic service API**: This API can be used in atomic services since API version 12. 1600 1601**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1602 1603**Parameters** 1604 1605| Name | Type | Mandatory| Description | 1606| -------- | -------- | ---- | -------------------- | 1607| index | number | Yes | Track index, which is obtained from [MediaDescription](#mediadescription8) by calling [getTrackDescription](#gettrackdescription9-1).| 1608 1609**Return value** 1610 1611| Type | Description | 1612| -------------- | ------------------------- | 1613| Promise\<void> | Promise that returns no value.| 1614 1615**Error codes** 1616 1617For details about the error codes, see [Media Error Codes](errorcode-media.md). 1618 1619| ID| Error Message | 1620| -------- | ----------------------------------------- | 1621| 401 | The parameter check failed. Return by promise. | 1622| 5400102 | Operation not allowed. Return by promise. | 1623 1624**Example** 1625 1626```ts 1627import { BusinessError } from '@kit.BasicServicesKit'; 1628 1629let avPlayer: media.AVPlayer = await media.createAVPlayer(); 1630let audioTrackIndex: Object = 0; 1631avPlayer.getTrackDescription((error: BusinessError, arrList: Array<media.MediaDescription>) => { 1632 if (arrList != null) { 1633 for (let i = 0; i < arrList.length; i++) { 1634 if (i != 0) { 1635 // Obtain the audio track list. 1636 audioTrackIndex = arrList[i][media.MediaDescriptionKey.MD_KEY_TRACK_INDEX]; 1637 } 1638 } 1639 } else { 1640 console.error(`Failed to get TrackDescription, error:${error}`); 1641 } 1642}); 1643 1644// Select an audio track. 1645avPlayer.selectTrack(parseInt(audioTrackIndex.toString())); 1646// Deselect the audio track and restore to the default audio track. 1647avPlayer.deselectTrack(parseInt(audioTrackIndex.toString())); 1648``` 1649 1650### setDecryptionConfig<sup>11+</sup> 1651 1652setDecryptionConfig(mediaKeySession: drm.MediaKeySession, secureVideoPath: boolean): void 1653 1654Sets 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. 1655 1656**Atomic service API**: This API can be used in atomic services since API version 12. 1657 1658**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1659 1660**Parameters** 1661 1662| Name | Type | Mandatory| Description | 1663| -------- | ------------------------------------------------------------ | ---- | -------------------------------------------- | 1664| mediaKeySession | [drm.MediaKeySession](../apis-drm-kit/js-apis-drm.md#mediakeysession) | Yes | Decryption session.| 1665| 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.| 1666 1667**Error codes** 1668 1669For details about the error codes, see [Media Error Codes](errorcode-media.md). 1670 1671| ID| Error Message | 1672| -------- | ----------------------------------------- | 1673| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 1674 1675**Example** 1676 1677For details about the DRM module, see [js-apis-drm.md](../apis-drm-kit/js-apis-drm.md). 1678```ts 1679import { drm } from '@kit.DrmKit'; 1680 1681// Create a media key system. 1682let keySystem:drm.MediaKeySystem = drm.createMediaKeySystem('com.clearplay.drm'); 1683// Create a media key session. 1684let keySession:drm.MediaKeySession = keySystem.createMediaKeySession(drm.ContentProtectionLevel.CONTENT_PROTECTION_LEVEL_SW_CRYPTO); 1685// Generate a media key request and set the response to the media key request. 1686// Flag indicating whether a secure video channel is used. 1687let secureVideoPath:boolean = false; 1688// Set the decryption configuration. 1689avPlayer.setDecryptionConfig(keySession, secureVideoPath); 1690``` 1691 1692### getMediaKeySystemInfos<sup>11+</sup> 1693 1694getMediaKeySystemInfos(): Array\<drm.MediaKeySystemInfo> 1695 1696Obtains 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. 1697 1698**Atomic service API**: This API can be used in atomic services since API version 12. 1699 1700**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1701 1702**Return value** 1703 1704| Type | Description | 1705| ------------------------------------------------------ | ------------------------------------------------- | 1706| Array<[drm.MediaKeySystemInfo](../apis-drm-kit/js-apis-drm.md#mediakeysysteminfo)> | Array of **MediaKeySystemInfo** objects, each of which contains the **uuid** and **pssh** attributes.| 1707 1708**Example** 1709 1710```ts 1711import { drm } from '@kit.DrmKit'; 1712 1713const infos = avPlayer.getMediaKeySystemInfos(); 1714console.info('GetMediaKeySystemInfos count: ' + infos.length); 1715for (let i = 0; i < infos.length; i++) { 1716 console.info('GetMediaKeySystemInfos uuid: ' + infos[i]["uuid"]); 1717 console.info('GetMediaKeySystemInfos pssh: ' + infos[i]["pssh"]); 1718} 1719``` 1720 1721### seek<sup>9+</sup> 1722 1723seek(timeMs: number, mode?:SeekMode): void 1724 1725Seeks 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. 1726This API is not supported in live mode. 1727 1728**Atomic service API**: This API can be used in atomic services since API version 11. 1729 1730**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1731 1732**Parameters** 1733 1734| Name| Type | Mandatory| Description | 1735| ------ | ---------------------- | ---- | ------------------------------------------------------------ | 1736| timeMs | number | Yes | Position to seek to, in ms. The value range is [0, [duration](#attributes)].| 1737| 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.**| 1738 1739**Example** 1740 1741```ts 1742let seekTime: number = 1000 1743avPlayer.seek(seekTime, media.SeekMode.SEEK_PREV_SYNC) 1744``` 1745 1746### on('seekDone')<sup>9+</sup> 1747 1748on(type: 'seekDone', callback: Callback\<number>): void 1749 1750Subscribes to the event to check whether the seek operation takes effect. 1751 1752**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1753 1754**Atomic service API**: This API can be used in atomic services since API version 11. 1755 1756**Parameters** 1757 1758| Name | Type | Mandatory| Description | 1759| -------- | -------- | ---- | ------------------------------------------------------------ | 1760| type | string | Yes | Event type, which is **'seekDone'** in this case. This event is triggered each time **seek()** is called.| 1761| 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.| 1762 1763**Example** 1764 1765```ts 1766avPlayer.on('seekDone', (seekDoneTime:number) => { 1767 console.info('seekDone called,and seek time is:' + seekDoneTime) 1768}) 1769``` 1770 1771### off('seekDone')<sup>9+</sup> 1772 1773off(type: 'seekDone', callback?: Callback\<number>): void 1774 1775Unsubscribes from the event that checks whether the seek operation takes effect. 1776 1777**Atomic service API**: This API can be used in atomic services since API version 11. 1778 1779**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1780 1781**Parameters** 1782 1783| Name| Type | Mandatory| Description | 1784| ------ | ------ | ---- | ---------------------------------------------------- | 1785| type | string | Yes | Event type, which is **'seekDone'** in this case.| 1786| 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.| 1787 1788**Example** 1789 1790```ts 1791avPlayer.off('seekDone') 1792``` 1793 1794### setSpeed<sup>9+</sup> 1795 1796setSpeed(speed: PlaybackSpeed): void 1797 1798Sets 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. 1799This API is not supported in live mode. 1800 1801**Atomic service API**: This API can be used in atomic services since API version 12. 1802 1803**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1804 1805**Parameters** 1806 1807| Name| Type | Mandatory| Description | 1808| ------ | -------------------------------- | ---- | ------------------ | 1809| speed | [PlaybackSpeed](#playbackspeed8) | Yes | Playback speed to set.| 1810 1811**Example** 1812 1813```ts 1814avPlayer.setSpeed(media.PlaybackSpeed.SPEED_FORWARD_2_00_X) 1815``` 1816 1817### on('speedDone')<sup>9+</sup> 1818 1819on(type: 'speedDone', callback: Callback\<number>): void 1820 1821Subscribes to the event to check whether the playback speed is successfully set. 1822 1823**Atomic service API**: This API can be used in atomic services since API version 12. 1824 1825**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1826 1827**Parameters** 1828 1829| Name | Type | Mandatory| Description | 1830| -------- | -------- | ---- | ------------------------------------------------------------ | 1831| type | string | Yes | Event type, which is **'speedDone'** in this case. This event is triggered each time **setSpeed()** is called.| 1832| 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).| 1833 1834**Example** 1835 1836```ts 1837avPlayer.on('speedDone', (speed:number) => { 1838 console.info('speedDone called,and speed value is:' + speed) 1839}) 1840``` 1841 1842### off('speedDone')<sup>9+</sup> 1843 1844off(type: 'speedDone', callback?: Callback\<number>): void 1845 1846Unsubscribes from the event that checks whether the playback speed is successfully set. 1847 1848**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1849 1850**Parameters** 1851 1852| Name| Type | Mandatory| Description | 1853| ------ | ------ | ---- | --------------------------------------------------------- | 1854| type | string | Yes | Event type, which is **'speedDone'** in this case.| 1855| 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.| 1856 1857**Example** 1858 1859```ts 1860avPlayer.off('speedDone') 1861``` 1862 1863### setBitrate<sup>9+</sup> 1864 1865setBitrate(bitrate: number): void 1866 1867Sets the bit rate for the streaming media. This API is valid only for HLS/DASH streams. By default, the AVPlayer selects a proper bit rate based on the network connection 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 [bitrateDone](#onbitratedone9) event. 1868 1869**Atomic service API**: This API can be used in atomic services since API version 12. 1870 1871**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1872 1873**Parameters** 1874 1875| Name | Type | Mandatory| Description | 1876| ------- | ------ | ---- | ------------------------------------------------------------ | 1877| bitrate | number | Yes | Bit rate to set. You can obtain the available bit rates of the current HLS/DASH 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 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.| 1878 1879**Example** 1880 1881```ts 1882let bitrate: number = 96000 1883avPlayer.setBitrate(bitrate) 1884``` 1885 1886### on('bitrateDone')<sup>9+</sup> 1887 1888on(type: 'bitrateDone', callback: Callback\<number>): void 1889 1890Subscribes to the event to check whether the bit rate is successfully set. 1891 1892**Atomic service API**: This API can be used in atomic services since API version 12. 1893 1894**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1895 1896**Parameters** 1897 1898| Name | Type | Mandatory| Description | 1899| -------- | -------- | ---- | ------------------------------------------------------------ | 1900| type | string | Yes | Event type, which is **'bitrateDone'** in this case. This event is triggered each time **setBitrate()** is called.| 1901| callback | Callback\<number> | Yes | Callback invoked when the event is triggered. It reports the effective bit rate. | 1902 1903**Example** 1904 1905```ts 1906avPlayer.on('bitrateDone', (bitrate:number) => { 1907 console.info('bitrateDone called,and bitrate value is:' + bitrate) 1908}) 1909``` 1910 1911### off('bitrateDone')<sup>9+</sup> 1912 1913off(type: 'bitrateDone', callback?: Callback\<number>): void 1914 1915Unsubscribes from the event that checks whether the bit rate is successfully set. 1916 1917**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1918 1919**Parameters** 1920 1921| Name| Type | Mandatory| Description | 1922| ------ | ------ | ---- | ------------------------------------------------------------ | 1923| type | string | Yes | Event type, which is **'bitrateDone'** in this case.| 1924| 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. | 1925 1926**Example** 1927 1928```ts 1929avPlayer.off('bitrateDone') 1930``` 1931 1932### on('availableBitrates')<sup>9+</sup> 1933 1934on(type: 'availableBitrates', callback: Callback\<Array\<number>>): void 1935 1936Subscribes to available bit rates of HLS/DASH streams. This event is reported only after the AVPlayer switches to the prepared state. 1937 1938**Atomic service API**: This API can be used in atomic services since API version 12. 1939 1940**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1941 1942**Parameters** 1943 1944| Name | Type | Mandatory| Description | 1945| -------- | -------- | ---- | ------------------------------------------------------------ | 1946| type | string | Yes | Event type, which is **'availableBitrates'** in this case. This event is triggered once after the AVPlayer switches to the prepared state.| 1947| 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.| 1948 1949**Example** 1950 1951```ts 1952avPlayer.on('availableBitrates', (bitrates: Array<number>) => { 1953 console.info('availableBitrates called,and availableBitrates length is:' + bitrates.length) 1954}) 1955``` 1956 1957### off('availableBitrates')<sup>9+</sup> 1958 1959off(type: 'availableBitrates', callback?: Callback\<Array\<number>>): void 1960 1961Unsubscribes from available bit rates of HLS/DASH streams. This event is reported after [prepare](#prepare9) is called. 1962 1963**Atomic service API**: This API can be used in atomic services since API version 12. 1964 1965**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1966 1967**Parameters** 1968 1969| Name| Type | Mandatory| Description | 1970| ------ | ------ | ---- | ------------------------------------------------------------ | 1971| type | string | Yes | Event type, which is **'availableBitrates'** in this case.| 1972| 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.| 1973 1974**Example** 1975 1976```ts 1977avPlayer.off('availableBitrates') 1978``` 1979 1980 1981### on('mediaKeySystemInfoUpdate')<sup>11+</sup> 1982 1983on(type: 'mediaKeySystemInfoUpdate', callback: Callback\<Array\<drm.MediaKeySystemInfo>>): void 1984 1985Subscribes to media key system information changes. 1986 1987**Atomic service API**: This API can be used in atomic services since API version 12. 1988 1989**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1990 1991**Parameters** 1992 1993| Name | Type | Mandatory| Description | 1994| -------- | -------- | ---- | ------------------------------------------------------------ | 1995| 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.| 1996| 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.| 1997 1998**Example** 1999 2000```ts 2001import { drm } from '@kit.DrmKit'; 2002 2003avPlayer.on('mediaKeySystemInfoUpdate', (mediaKeySystemInfo: Array<drm.MediaKeySystemInfo>) => { 2004 for (let i = 0; i < mediaKeySystemInfo.length; i++) { 2005 console.info('mediaKeySystemInfoUpdate happened uuid: ' + mediaKeySystemInfo[i]["uuid"]); 2006 console.info('mediaKeySystemInfoUpdate happened pssh: ' + mediaKeySystemInfo[i]["pssh"]); 2007 } 2008}) 2009``` 2010 2011### off('mediaKeySystemInfoUpdate')<sup>11+</sup> 2012 2013off(type: 'mediaKeySystemInfoUpdate', callback?: Callback\<Array\<drm.MediaKeySystemInfo>>): void; 2014 2015Unsubscribes from media key system information changes. 2016 2017**Atomic service API**: This API can be used in atomic services since API version 12. 2018 2019**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2020 2021**Parameters** 2022 2023| Name| Type | Mandatory| Description | 2024| ------ | ------ | ---- | ------------------------------------------------------------ | 2025| type | string | Yes | Event type, which is **'mediaKeySystemInfoUpdate'** in this case.| 2026| 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.| 2027 2028**Example** 2029 2030```ts 2031avPlayer.off('mediaKeySystemInfoUpdate') 2032``` 2033 2034### setVolume<sup>9+</sup> 2035 2036setVolume(volume: number): void 2037 2038Sets 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. 2039 2040**Atomic service API**: This API can be used in atomic services since API version 12. 2041 2042**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2043 2044**Parameters** 2045 2046| Name| Type | Mandatory| Description | 2047| ------ | ------ | ---- | ------------------------------------------------------------ | 2048| volume | number | Yes | Relative volume. The value ranges from 0.00 to 1.00. The value **1.00** indicates the maximum volume (100%).| 2049 2050**Example** 2051 2052```ts 2053let volume: number = 1.0 2054avPlayer.setVolume(volume) 2055``` 2056 2057### on('volumeChange')<sup>9+</sup> 2058 2059on(type: 'volumeChange', callback: Callback\<number>): void 2060 2061Subscribes to the event to check whether the volume is successfully set. 2062 2063**Atomic service API**: This API can be used in atomic services since API version 12. 2064 2065**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2066 2067**Parameters** 2068 2069| Name | Type | Mandatory| Description | 2070| -------- | -------- | ---- | ------------------------------------------------------------ | 2071| type | string | Yes | Event type, which is **'volumeChange'** in this case. This event is triggered each time **setVolume()** is called.| 2072| callback | Callback\<number> | Yes | Callback invoked when the event is triggered. It reports the effective volume. | 2073 2074**Example** 2075 2076```ts 2077avPlayer.on('volumeChange', (vol: number) => { 2078 console.info('volumeChange called,and new volume is :' + vol) 2079}) 2080``` 2081 2082### off('volumeChange')<sup>9+</sup> 2083 2084off(type: 'volumeChange', callback?: Callback\<number>): void 2085 2086Unsubscribes from the event that checks whether the volume is successfully set. 2087 2088**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2089 2090**Parameters** 2091 2092| Name| Type | Mandatory| Description | 2093| ------ | ------ | ---- | ------------------------------------------------------------ | 2094| type | string | Yes | Event type, which is **'volumeChange'** in this case.| 2095| 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. | 2096 2097**Example** 2098 2099```ts 2100avPlayer.off('volumeChange') 2101``` 2102 2103### on('endOfStream')<sup>9+</sup> 2104 2105on(type: 'endOfStream', callback: Callback\<void>): void 2106 2107Subscribes 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. 2108 2109**Atomic service API**: This API can be used in atomic services since API version 12. 2110 2111**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2112 2113**Parameters** 2114 2115| Name | Type | Mandatory| Description | 2116| -------- | -------- | ---- | ------------------------------------------------------------ | 2117| type | string | Yes | Event type, which is **'endOfStream'** in this case. This event is triggered when the AVPlayer finishes playing the media asset.| 2118| callback | Callback\<void> | Yes | Callback invoked when the event is triggered. | 2119 2120**Example** 2121 2122```ts 2123avPlayer.on('endOfStream', () => { 2124 console.info('endOfStream called') 2125}) 2126``` 2127 2128### off('endOfStream')<sup>9+</sup> 2129 2130off(type: 'endOfStream', callback?: Callback\<void>): void 2131 2132Unsubscribes from the event that indicates the end of the stream being played. 2133 2134**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2135 2136**Parameters** 2137 2138| Name| Type | Mandatory| Description | 2139| ------ | ------ | ---- | ------------------------------------------------------------ | 2140| type | string | Yes | Event type, which is **'endOfStream'** in this case.| 2141| callback | Callback\<void> | No | Callback invoked when the event is triggered.<br>This parameter is supported since API version 12. | 2142 2143**Example** 2144 2145```ts 2146avPlayer.off('endOfStream') 2147``` 2148 2149### on('timeUpdate')<sup>9+</sup> 2150 2151on(type: 'timeUpdate', callback: Callback\<number>): void 2152 2153Subscribes 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. 2154 2155The **'timeUpdate'** event is not supported in live mode. 2156 2157**Atomic service API**: This API can be used in atomic services since API version 11. 2158 2159**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2160 2161**Parameters** 2162 2163| Name | Type | Mandatory| Description | 2164| -------- | -------- | ---- | ---------------------------------------------- | 2165| type | string | Yes | Event type, which is **'timeUpdate'** in this case.| 2166| callback | Callback\<number> | Yes | Callback used to return the current time. | 2167 2168**Example** 2169 2170```ts 2171avPlayer.on('timeUpdate', (time:number) => { 2172 console.info('timeUpdate called,and new time is :' + time) 2173}) 2174``` 2175 2176### off('timeUpdate')<sup>9+</sup> 2177 2178off(type: 'timeUpdate', callback?: Callback\<number>): void 2179 2180Unsubscribes from playback position changes. 2181 2182**Atomic service API**: This API can be used in atomic services since API version 11. 2183 2184**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2185 2186**Parameters** 2187 2188| Name| Type | Mandatory| Description | 2189| ------ | ------ | ---- | -------------------------------------------------- | 2190| type | string | Yes | Event type, which is **'timeUpdate'** in this case.| 2191| callback | Callback\<number> | No | Callback used to return the current time.<br>This parameter is supported since API version 12. | 2192 2193**Example** 2194 2195```ts 2196avPlayer.off('timeUpdate') 2197``` 2198 2199### on('durationUpdate')<sup>9+</sup> 2200 2201 2202on(type: 'durationUpdate', callback: Callback\<number>): void 2203 2204Subscribes 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. 2205The **'durationUpdate'** event is not supported in live mode. 2206 2207**Atomic service API**: This API can be used in atomic services since API version 12. 2208 2209**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2210 2211**Parameters** 2212 2213| Name | Type | Mandatory| Description | 2214| -------- | -------- | ---- | -------------------------------------------------- | 2215| type | string | Yes | Event type, which is **'durationUpdate'** in this case.| 2216| callback | Callback\<number> | Yes | Callback used to return the resource duration. | 2217 2218**Example** 2219 2220```ts 2221avPlayer.on('durationUpdate', (duration: number) => { 2222 console.info('durationUpdate called,new duration is :' + duration) 2223}) 2224``` 2225 2226### off('durationUpdate')<sup>9+</sup> 2227 2228off(type: 'durationUpdate', callback?: Callback\<number>): void 2229 2230Unsubscribes from media asset duration changes. 2231 2232**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2233 2234**Parameters** 2235 2236| Name| Type | Mandatory| Description | 2237| ------ | ------ | ---- | ------------------------------------------------------ | 2238| type | string | Yes | Event type, which is **'durationUpdate'** in this case.| 2239| callback | Callback\<number> | No | Callback used to return the resource duration.<br>This parameter is supported since API version 12. | 2240 2241**Example** 2242 2243```ts 2244avPlayer.off('durationUpdate') 2245``` 2246 2247### on('bufferingUpdate')<sup>9+</sup> 2248 2249on(type: 'bufferingUpdate', callback: OnBufferingUpdateHandler): void 2250 2251Subscribes to audio and video buffer changes. This subscription is supported only in network playback scenarios. 2252 2253**Atomic service API**: This API can be used in atomic services since API version 12. 2254 2255**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2256 2257**Parameters** 2258 2259| Name | Type | Mandatory| Description | 2260| -------- | -------- | ---- | ------------------------------------------------------------ | 2261| type | string | Yes | Event type, which is **'bufferingUpdate'** in this case. | 2262| callback | [OnBufferingUpdateHandler](#onbufferingupdatehandler12) | Yes | Callback invoked when the event is triggered.| 2263 2264**Example** 2265 2266```ts 2267avPlayer.on('bufferingUpdate', (infoType: media.BufferingInfoType, value: number) => { 2268 console.info('bufferingUpdate called,and infoType value is:' + infoType + ', value is :' + value) 2269}) 2270``` 2271 2272### off('bufferingUpdate')<sup>9+</sup> 2273 2274off(type: 'bufferingUpdate', callback?: OnBufferingUpdateHandler): void 2275 2276Unsubscribes from audio and video buffer changes. 2277 2278**Atomic service API**: This API can be used in atomic services since API version 12. 2279 2280**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2281 2282**Parameters** 2283 2284| Name| Type | Mandatory| Description | 2285| ------ | ------ | ---- | --------------------------------------------------------- | 2286| type | string | Yes | Event type, which is **'bufferingUpdate'** in this case.| 2287| callback | [OnBufferingUpdateHandler](#onbufferingupdatehandler12) | No | Callback invoked when the event is triggered.| 2288 2289**Example** 2290 2291```ts 2292avPlayer.off('bufferingUpdate') 2293``` 2294 2295### on('startRenderFrame')<sup>9+</sup> 2296 2297on(type: 'startRenderFrame', callback: Callback\<void>): void 2298 2299Subscribes 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. 2300 2301**Atomic service API**: This API can be used in atomic services since API version 12. 2302 2303**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2304 2305**Parameters** 2306 2307| Name | Type | Mandatory| Description | 2308| -------- | -------- | ---- | ------------------------------------------------------------ | 2309| type | string | Yes | Event type, which is **'startRenderFrame'** in this case.| 2310| callback | Callback\<void> | Yes | Callback invoked when the event is triggered. | 2311 2312**Example** 2313 2314```ts 2315avPlayer.on('startRenderFrame', () => { 2316 console.info('startRenderFrame called') 2317}) 2318``` 2319 2320### off('startRenderFrame')<sup>9+</sup> 2321 2322off(type: 'startRenderFrame', callback?: Callback\<void>): void 2323 2324Unsubscribes from the event that indicates rendering starts for the first frame. 2325 2326**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2327 2328**Parameters** 2329 2330| Name| Type | Mandatory| Description | 2331| ------ | ------ | ---- | ------------------------------------------------------------ | 2332| type | string | Yes | Event type, which is **'startRenderFrame'** in this case.| 2333| callback | Callback\<void> | No | Callback invoked when the event is triggered.<br>This parameter is supported since API version 12. | 2334 2335**Example** 2336 2337```ts 2338avPlayer.off('startRenderFrame') 2339``` 2340 2341### on('videoSizeChange')<sup>9+</sup> 2342 2343on(type: 'videoSizeChange', callback: OnVideoSizeChangeHandler): void 2344 2345Subscribes 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. 2346 2347**Atomic service API**: This API can be used in atomic services since API version 12. 2348 2349**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2350 2351**Parameters** 2352 2353| Name | Type | Mandatory| Description | 2354| -------- | -------- | ---- | ------------------------------------------------------------ | 2355| type | string | Yes | Event type, which is **'videoSizeChange'** in this case.| 2356| callback | [OnVideoSizeChangeHandler](#onvideosizechangehandler12) | Yes | Callback invoked when the event is triggered. | 2357 2358**Example** 2359 2360```ts 2361avPlayer.on('videoSizeChange', (width: number, height: number) => { 2362 console.info('videoSizeChange called,and width is:' + width + ', height is :' + height) 2363}) 2364``` 2365 2366### off('videoSizeChange')<sup>9+</sup> 2367 2368off(type: 'videoSizeChange', callback?: OnVideoSizeChangeHandler): void 2369 2370Unsubscribes from video size changes. 2371 2372**Atomic service API**: This API can be used in atomic services since API version 12. 2373 2374**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2375 2376**Parameters** 2377 2378| Name| Type | Mandatory| Description | 2379| ------ | ------ | ---- | ------------------------------------------------------------ | 2380| type | string | Yes | Event type, which is **'videoSizeChange'** in this case.| 2381| callback | [OnVideoSizeChangeHandler](#onvideosizechangehandler12) | No | Callback invoked when the event is triggered.<br>This parameter is supported since API version 12. | 2382 2383**Example** 2384 2385```ts 2386avPlayer.off('videoSizeChange') 2387``` 2388 2389### on('audioInterrupt')<sup>9+</sup> 2390 2391on(type: 'audioInterrupt', callback: Callback\<audio.InterruptEvent>): void 2392 2393Subscribes 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). 2394 2395**Atomic service API**: This API can be used in atomic services since API version 12. 2396 2397**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2398 2399**Parameters** 2400 2401| Name | Type | Mandatory| Description | 2402| -------- | ------------------------------------------------------------ | ---- | -------------------------------------------------------- | 2403| type | string | Yes | Event type, which is **'audioInterrupt'** in this case.| 2404| callback | Callback\<[audio.InterruptEvent](../apis-audio-kit/js-apis-audio.md#interruptevent9)> | Yes | Callback invoked when the event is triggered. | 2405 2406**Example** 2407 2408```ts 2409import { audio } from '@kit.AudioKit'; 2410 2411avPlayer.on('audioInterrupt', (info: audio.InterruptEvent) => { 2412 console.info('audioInterrupt called,and InterruptEvent info is:' + info) 2413}) 2414``` 2415 2416### off('audioInterrupt')<sup>9+</sup> 2417 2418off(type: 'audioInterrupt', callback?: Callback<audio.InterruptEvent>): void 2419 2420Unsubscribes from the audio interruption event. 2421 2422**Atomic service API**: This API can be used in atomic services since API version 12. 2423 2424**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2425 2426**Parameters** 2427 2428| Name| Type | Mandatory| Description | 2429| ------ | ------ | ---- | ------------------------------------------------------------ | 2430| type | string | Yes | Event type, which is **'audioInterrupt'** in this case.| 2431| 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. | 2432 2433**Example** 2434 2435```ts 2436avPlayer.off('audioInterrupt') 2437``` 2438 2439### on('audioOutputDeviceChangeWithInfo')<sup>11+</sup> 2440 2441on(type: 'audioOutputDeviceChangeWithInfo', callback: Callback\<audio.AudioStreamDeviceChangeInfo>): void 2442 2443Subscribes to audio stream output device changes and reasons. This API uses an asynchronous callback to return the result. 2444 2445When 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). 2446 2447**Atomic service API**: This API can be used in atomic services since API version 12. 2448 2449**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2450 2451**Parameters** 2452 2453| Name | Type | Mandatory| Description | 2454| :------- | :------------------------- | :--- | :------------------------------------------ | 2455| type | string | Yes | Event type, which is **'outputDeviceChangeWithInfo'** in this case. The event is triggered when the output device is changed.| 2456| 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.| 2457 2458**Error codes** 2459 2460| ID| Error Message | 2461| -------- | ------------------------------------------ | 2462| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 2463 2464**Example** 2465 2466```ts 2467import { audio } from '@kit.AudioKit'; 2468 2469avPlayer.on('audioOutputDeviceChangeWithInfo', (data: audio.AudioStreamDeviceChangeInfo) => { 2470 console.info(`${JSON.stringify(data)}`); 2471}); 2472``` 2473 2474### off('audioOutputDeviceChangeWithInfo')<sup>11+</sup> 2475 2476off(type: 'audioOutputDeviceChangeWithInfo', callback?: Callback\<audio.AudioStreamDeviceChangeInfo>): void 2477 2478Unsubscribes from audio stream output device changes and reasons. This API uses an asynchronous callback to return the result. 2479 2480**Atomic service API**: This API can be used in atomic services since API version 12. 2481 2482**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2483 2484**Parameters** 2485 2486| Name | Type | Mandatory| Description | 2487| :------- | :------------------------- | :--- | :------------------------------------------ | 2488| type | string | Yes | Event type, which is **'outputDeviceChange'** in this case. The event is triggered when the audio output device is changed.| 2489| 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.| 2490 2491**Error codes** 2492 2493| ID| Error Message | 2494| -------- | ------------------------------------------ | 2495| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 2496 2497**Example** 2498 2499```ts 2500avPlayer.off('audioOutputDeviceChangeWithInfo'); 2501``` 2502 2503### addSubtitleFromFd<sup>12+</sup> 2504 2505addSubtitleFromFd(fd: number, offset?: number, length?: number): Promise\<void> 2506 2507Adds 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. 2508 2509**Atomic service API**: This API can be used in atomic services since API version 12. 2510 2511**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2512 2513**Parameters** 2514 2515| Name| Type | Mandatory| Description | 2516| ------ | ---------------------- | ---- | ------------------------------------------------------------ | 2517| fd | number | Yes | Resource handle, which is obtained by calling [resourceManager.getRawFd](../apis-localization-kit/js-apis-resource-manager.md#getrawfd9).| 2518| 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.| 2519| 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.| 2520 2521**Return value** 2522 2523| Type | Description | 2524| -------------- | ------------------------------------------ | 2525| Promise\<void> | Promise that returns no value.| 2526 2527**Error codes** 2528 2529| ID| Error Message | 2530| -------- | ------------------------------------------ | 2531| 401 | The parameter check failed. Return by promise. | 2532| 5400102 | Operation not allowed. Return by promise. | 2533 2534**Example** 2535 2536```ts 2537import { common } from '@kit.AbilityKit' 2538 2539let context = getContext(this) as common.UIAbilityContext 2540let fileDescriptor = await context.resourceManager.getRawFd('xxx.srt') 2541 2542avPlayer.addSubtitleFromFd(fileDescriptor.fd, fileDescriptor.offset, fileDescriptor.length) 2543``` 2544 2545### addSubtitleFromUrl<sup>12+</sup> 2546 2547addSubtitleFromUrl(url: string): Promise\<void> 2548 2549Adds 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. 2550 2551**Atomic service API**: This API can be used in atomic services since API version 12. 2552 2553**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2554 2555**Parameters** 2556 2557| Name| Type | Mandatory| Description | 2558| ------ | ------ | ---- | ------------------------------------------------------------ | 2559| url | string | Yes | Address of the external subtitle file.| 2560 2561**Return value** 2562 2563| Type | Description | 2564| -------------- | ------------------------------------------ | 2565| Promise\<void> | Promise that returns no value.| 2566 2567**Error codes** 2568 2569| ID| Error Message | 2570| -------- | ------------------------------------------ | 2571| 401 | The parameter check failed. Return by promise. | 2572| 5400102 | Operation not allowed. Return by promise. | 2573 2574**Example** 2575 2576```ts 2577let fdUrl:string = 'http://xxx.xxx.xxx/xx/index.srt' 2578 2579let avPlayer: media.AVPlayer = await media.createAVPlayer() 2580avPlayer.addSubtitleFromUrl(fdUrl) 2581``` 2582 2583### on('subtitleUpdate')<sup>12+</sup> 2584 2585on(type: 'subtitleUpdate', callback: Callback\<SubtitleInfo>): void 2586 2587Subscribes 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. 2588 2589**Atomic service API**: This API can be used in atomic services since API version 12. 2590 2591**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2592 2593**Parameters** 2594 2595| Name | Type | Mandatory| Description | 2596| -------- | -------- | ---- | ------------------------------------------------------------ | 2597| type | string | Yes | Event type, which is **'subtitleUpdate'** in this case. The event is triggered when the external subtitle is updated.| 2598| callback | function | Yes | Callback invoked when the subtitle is updated.| 2599 2600**Example** 2601 2602```ts 2603avPlayer.on('subtitleUpdate', async (info: media.SubtitleInfo) => { 2604 if (info) { 2605 let text = (!info.text) ? '' : info.text 2606 let startTime = (!info.startTime) ? 0 : info.startTime 2607 let duration = (!info.duration) ? 0 : info.duration 2608 console.info('subtitleUpdate info: text=' + text + ' startTime=' + startTime +' duration=' + duration) 2609 } else { 2610 console.info('subtitleUpdate info is null') 2611 } 2612}) 2613``` 2614 2615### off('subtitleUpdate')<sup>12+</sup> 2616 2617off(type: 'subtitleUpdate', callback?: Callback\<SubtitleInfo>): void 2618 2619Unsubscribes from subtitle update events. 2620 2621**Atomic service API**: This API can be used in atomic services since API version 12. 2622 2623**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2624 2625**Parameters** 2626 2627| Name | Type | Mandatory| Description | 2628| -------- | -------- | ---- | ------------------------------------------------------------ | 2629| type | string | Yes | Event type, which is **'subtitleUpdate'** in this case. The event is triggered when the external subtitle is updated.| 2630| callback | function | No | Callback that has been registered to listen for subtitle update events.| 2631 2632**Example** 2633 2634```ts 2635avPlayer.off('subtitleUpdate') 2636``` 2637 2638### on('trackChange')<sup>12+</sup> 2639 2640on(type: 'trackChange', callback: OnTrackChangeHandler): void 2641 2642Subscribes 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. 2643 2644**Atomic service API**: This API can be used in atomic services since API version 12. 2645 2646**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2647 2648**Parameters** 2649 2650| Name | Type | Mandatory| Description | 2651| -------- | -------- | ---- | ------------------------------------------------------------ | 2652| type | string | Yes | Event type, which is **'trackChange'** in this case. The event is triggered when the track changes.| 2653| callback | [OnTrackChangeHandler](#ontrackchangehandler12) | Yes | Callback invoked when the event is triggered.| 2654 2655**Example** 2656 2657```ts 2658avPlayer.on('trackChange', (index: number, isSelect: boolean) => { 2659 console.info('trackChange info: index=' + index + ' isSelect=' + isSelect) 2660}) 2661``` 2662 2663### off('trackChange')<sup>12+</sup> 2664 2665off(type: 'trackChange', callback?: OnTrackChangeHandler): void 2666 2667Unsubscribes from track change events. 2668 2669**Atomic service API**: This API can be used in atomic services since API version 12. 2670 2671**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2672 2673**Parameters** 2674 2675| Name | Type | Mandatory| Description | 2676| -------- | -------- | ---- | ------------------------------------------------------------ | 2677| type | string | Yes | Event type, which is **'trackChange'** in this case. The event is triggered when the track changes.| 2678| callback | [OnTrackChangeHandler](#ontrackchangehandler12) | No | Callback that has been registered to listen for track changes.| 2679 2680**Example** 2681 2682```ts 2683avPlayer.off('trackChange') 2684``` 2685 2686### on('trackInfoUpdate')<sup>12+</sup> 2687 2688on(type: 'trackInfoUpdate', callback: Callback\<Array\<MediaDescription>>): void 2689 2690Subscribes 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. 2691 2692**Atomic service API**: This API can be used in atomic services since API version 12. 2693 2694**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2695 2696**Parameters** 2697 2698| Name | Type | Mandatory| Description | 2699| -------- | -------- | ---- | ------------------------------------------------------------ | 2700| type | string | Yes | Event type, which is **'trackInfoUpdate'** in this case. The event is triggered when the track information is updated.| 2701| callback | Callback\<Array\<[MediaDescription](#mediadescription8)>> | Yes | Callback invoked when the event is triggered.| 2702 2703**Example** 2704 2705```ts 2706avPlayer.on('trackInfoUpdate', (info: Array<media.MediaDescription>) => { 2707 if (info) { 2708 for (let i = 0; i < info.length; i++) { 2709 let propertyIndex: Object = info[i][media.MediaDescriptionKey.MD_KEY_TRACK_INDEX]; 2710 let propertyType: Object = info[i][media.MediaDescriptionKey.MD_KEY_TRACK_TYPE]; 2711 console.info('track info: index=' + propertyIndex + ' tracktype=' + propertyType) 2712 } 2713 } else { 2714 console.info('track info is null') 2715 } 2716}) 2717``` 2718 2719### off('trackInfoUpdate')<sup>12+</sup> 2720 2721off(type: 'trackInfoUpdate', callback?: Callback\<Array\<MediaDescription>>): void 2722 2723Unsubscribes from track information update events. 2724 2725**Atomic service API**: This API can be used in atomic services since API version 12. 2726 2727**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2728 2729**Parameters** 2730 2731| Name | Type | Mandatory| Description | 2732| -------- | -------- | ---- | ------------------------------------------------------------ | 2733| type | string | Yes | Event type, which is **'trackInfoUpdate'** in this case. The event is triggered when the track information is updated.| 2734| callback | Callback\<Array\<[MediaDescription](#mediadescription8)>> | No | Callback that has been registered to listen for track information updates.| 2735 2736**Example** 2737 2738```ts 2739avPlayer.off('trackInfoUpdate') 2740``` 2741 2742### on('amplitudeUpdate')<sup>13+</sup> 2743 2744on(type: 'amplitudeUpdate', callback: Callback\<Array\<number>>): void 2745 2746Subscribes to update events of the maximum audio level value, which is periodically reported when audio resources are played. 2747 2748**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2749 2750**Parameters** 2751 2752| Name | Type | Mandatory| Description | 2753| -------- | -------- | ---- | ------------------------------------------------------------ | 2754| type | string | Yes | Event type, which is **'amplitudeUpdate'** in this case. The event is triggered when the amplitude changes.| 2755| callback | Callback\<Array\<number>> | Yes | Callback invoked when the event is triggered.| 2756 2757**Example** 2758 2759```ts 2760avPlayer.on('amplitudeUpdate', (value: Array<number>) => { 2761 console.info('amplitudeUpdate called,and amplitudeUpdate = ${value}') 2762}) 2763``` 2764 2765### off('amplitudeUpdate')<sup>13+</sup> 2766 2767off(type: 'amplitudeUpdate', callback?: Callback\<Array\<number>>): void 2768 2769Unsubscribes from update events of the maximum amplitude. 2770 2771**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2772 2773**Parameters** 2774 2775| Name| Type | Mandatory| Description | 2776| ------ | ------ | ---- | ------------------------------------------------------------ | 2777| type | string | Yes | Event type, which is **'amplitudeUpdate'** in this case. The event is triggered when the amplitude changes.| 2778| callback | Callback\<Array\<number>> | No | Callback that has been registered to listen for amplitude updates.| 2779 2780**Example** 2781 2782```ts 2783avPlayer.off('amplitudeUpdate') 2784``` 2785 2786## AVPlayerState<sup>9+</sup> 2787 2788type AVPlayerState = 'idle' | 'initialized' | 'prepared' | 'playing' | 'paused' | 'completed' | 'stopped' | 'released' | 'error' 2789 2790Enumerates 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). 2791 2792**Atomic service API**: This API can be used in atomic services since API version 11. 2793 2794**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2795 2796| Type | Description | 2797| :-----------------------------: | :----------------------------------------------------------- | 2798| '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.| 2799| '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.| 2800| '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.| 2801| 'playing' | The AVPlayer enters this state when [play()](#play9) is called in the prepared, paused, or completed state.| 2802| 'paused' | The AVPlayer enters this state when **pause()** is called in the playing state.| 2803| '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.| 2804| '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.| 2805| '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.| 2806| '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.| 2807 2808## OnTrackChangeHandler<sup>12+</sup> 2809 2810type OnTrackChangeHandler = (index: number, isSelected: boolean) => void 2811 2812Describes the callback invoked for the track change event. 2813 2814**Atomic service API**: This API can be used in atomic services since API version 12. 2815 2816**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2817 2818| Name | Type | Mandatory| Description | 2819| ------ | ------ | ------ | ---------------------------------------------------------- | 2820| index | number | Yes| Index of a track. | 2821| isSelected | boolean | Yes| Status of the track, that is, whether the track is selected.| 2822 2823## OnAVPlayerStateChangeHandle<sup>12+</sup> 2824 2825type OnAVPlayerStateChangeHandle = (state: AVPlayerState, reason: StateChangeReason) => void 2826 2827Describes the callback invoked for the AVPlayer state change event. 2828 2829**Atomic service API**: This API can be used in atomic services since API version 12. 2830 2831**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2832 2833| Name | Type | Mandatory| Description | 2834| ------ | ------ | ------ | ---------------------------------------------------------- | 2835| state | [AVPlayerState](#avplayerstate9) | Yes| State of the AVPlayer. | 2836| reason | [StateChangeReason](#statechangereason9) | Yes| Reason for the state change.| 2837 2838## OnBufferingUpdateHandler<sup>12+</sup> 2839 2840type OnBufferingUpdateHandler = (infoType: BufferingInfoType, value: number) => void 2841 2842Describes the callback invoked for the buffering update event. 2843 2844**Atomic service API**: This API can be used in atomic services since API version 12. 2845 2846**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2847 2848| Name | Type | Mandatory| Description | 2849| ------ | ------ | ------ | ------------------------------------------------------------ | 2850| infoType | [BufferingInfoType](#bufferinginfotype8) | Yes| Buffering information type. | 2851| value | number | Yes| The value is fixed at **0**.| 2852 2853## OnVideoSizeChangeHandler<sup>12+</sup> 2854 2855type OnVideoSizeChangeHandler = (width: number, height: number) => void 2856 2857Describes the callback invoked for the video size change event. 2858 2859**Atomic service API**: This API can be used in atomic services since API version 12. 2860 2861**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2862 2863| Name | Type | Mandatory| Description | 2864| ------ | ------ | ------ | ------------------------------------------------------------ | 2865| width | number | Yes| Video width. | 2866| height | number | Yes| Video height.| 2867 2868## AVFileDescriptor<sup>9+</sup> 2869 2870Describes 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. 2871 2872**Atomic service API**: This API can be used in atomic services since API version 11. 2873 2874**System capability**: SystemCapability.Multimedia.Media.Core 2875 2876| Name | Type | Mandatory| Description | 2877| ------ | ------ | ---- | ------------------------------------------------------------ | 2878| 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). | 2879| 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.| 2880| 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.| 2881 2882## AVDataSrcDescriptor<sup>10+</sup> 2883 2884Defines 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. 2885 2886**Atomic service API**: This API can be used in atomic services since API version 11. 2887 2888**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2889 2890| Name | Type | Mandatory| Description | 2891| ------ | ------ | ---- | ------------------------------------------------------------ | 2892| 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.| 2893| 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 filled, which is of the number type. If **-1** is returned, the end of stream is reached. If **-2** is returned, an unrecoverable error occurs.| 2894 2895## SubtitleInfo<sup>12+</sup> 2896 2897Describes the external subtitle information. When a subtitle update event is subscribed to, the information about the external subtitle is returned through a callback. 2898 2899**Atomic service API**: This API can be used in atomic services since API version 12. 2900 2901**System capability**: SystemCapability.Multimedia.Media.Core 2902 2903| Name | Type | Mandatory| Description | 2904| ------ | ------ | ---- | ------------------------------------------------------------ | 2905| text | string | No | Text information of the subtitle.| 2906| startTime | number | No | Start time for displaying the subtitle, in milliseconds.| 2907| duration | number | No| Duration for displaying the subtitle, in milliseconds.| 2908 2909## SeekMode<sup>8+</sup> 2910 2911Enumerates the video playback seek modes, which can be passed in the **seek** API. 2912 2913**System capability**: SystemCapability.Multimedia.Media.Core 2914 2915| Name | Value | Description | 2916| -------------- | ---- | ------------------------------------------------------------ | 2917| 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.| 2918| 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.| 2919| 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.| 2920 2921## SwitchMode<sup>12+</sup> 2922 2923Enumerates 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. 2924 2925**System capability**: SystemCapability.Multimedia.Media.Core 2926 2927| Name | Value | Description | 2928| -------------- | ---- | ------------------------------------------------------------ | 2929| 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.| 2930| 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.| 2931| 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.| 2932 2933## PlaybackSpeed<sup>8+</sup> 2934 2935Enumerates the video playback speeds, which can be passed in the **setSpeed** API. 2936 2937**Atomic service API**: This API can be used in atomic services since API version 12. 2938 2939**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 2940 2941| Name | Value | Description | 2942| -------------------- | ---- | ------------------------------ | 2943| 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.| 2944| 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. | 2945| 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.| 2946| 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.| 2947| 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.| 2948| 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.| 2949| 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.| 2950| SPEED_FORWARD_3_00_X<sup>13+</sup> | 7 | Plays the video at 3.00 times the normal speed.<br>**Atomic service API**: This API can be used in atomic services since API version 13.| 2951| SPEED_FORWARD_0_25_X<sup>12+</sup> | 8 | Plays the video at 0.25 times the normal speed.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 2952| SPEED_FORWARD_0_125_X<sup>12+</sup> | 9 | Plays the video at 0.125 times the normal speed.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 2953 2954## VideoScaleType<sup>9+</sup> 2955 2956Enumerates the video scale modes. 2957 2958**Atomic service API**: This API can be used in atomic services since API version 12. 2959 2960**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 2961 2962| Name | Value | Description | 2963| ------------------------- | ---- | ------------------------------------------------ | 2964| VIDEO_SCALE_TYPE_FIT | 0 | Default mode. The video will be stretched to fit the window. | 2965| 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.| 2966 2967## MediaDescription<sup>8+</sup> 2968 2969Defines media information in key-value mode. 2970 2971**Atomic service API**: This API can be used in atomic services since API version 11. 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 [MediaDescriptionKey](#mediadescriptionkey8).| 2978 2979**Example** 2980 2981```ts 2982import { BusinessError } from '@kit.BasicServicesKit'; 2983 2984function printfItemDescription(obj: media.MediaDescription, key: string) { 2985 let property: Object = obj[key]; 2986 console.info('audio key is ' + key); // Specify a key. For details about the keys, see [MediaDescriptionKey]. 2987 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]. 2988} 2989 2990let avPlayer: media.AVPlayer | undefined = undefined; 2991media.createAVPlayer((err: BusinessError, player: media.AVPlayer) => { 2992 if(player != null) { 2993 avPlayer = player; 2994 console.info(`Succeeded in creating AVPlayer`); 2995 avPlayer.getTrackDescription((error: BusinessError, arrList: Array<media.MediaDescription>) => { 2996 if (arrList != null) { 2997 for (let i = 0; i < arrList.length; i++) { 2998 printfItemDescription(arrList[i], media.MediaDescriptionKey.MD_KEY_TRACK_TYPE); // Print the MD_KEY_TRACK_TYPE value of each track. 2999 } 3000 } else { 3001 console.error(`Failed to get TrackDescription, error:${error}`); 3002 } 3003 }); 3004 } else { 3005 console.error(`Failed to create AVPlayer, error message:${err.message}`); 3006 } 3007}); 3008``` 3009 3010## PlaybackInfo<sup>12+</sup> 3011 3012Defines the playback information in key-value pairs. 3013 3014**System capability**: SystemCapability.Multimedia.Media.Core 3015 3016| Name | Type | Mandatory| Description | 3017| ------------- | ------ | ---- | ------------------------------------------------------------ | 3018| [key: string] | Object | Yes | For details about the key range supported and the object type and range of each key, see [PlaybackInfoKey](#playbackinfokey12).| 3019 3020**Example** 3021 3022```ts 3023import { BusinessError } from '@kit.BasicServicesKit'; 3024 3025function printfPlaybackInfo(obj: media.PlaybackInfo, key: string) { 3026 let property: Object = obj[key]; 3027 console.info('key is ' + key); // // Specify a key. For details about the keys, see [PlaybackInfoKey]. 3028 console.info('value is ' + property); // Obtain the value of the key. The value can be any type. For details about the types, see [PlaybackInfoKey]. 3029} 3030 3031let avPlayer: media.AVPlayer | undefined = undefined; 3032let playbackInfo: media.PlaybackInfo | undefined = undefined; 3033media.createAVPlayer(async (err: BusinessError, player: media.AVPlayer) => { 3034 if (player != null) { 3035 avPlayer = player; 3036 console.info(`Succeeded in creating AVPlayer`); 3037 if (avPlayer) { 3038 try { 3039 playbackInfo = await avPlayer.getPlaybackInfo(); 3040 console.info(`AVPlayer getPlaybackInfo = ${JSON.stringify(playbackInfo)}`); // Print PlaybackInfo. 3041 printfPlaybackInfo(playbackInfo, media.PlaybackInfoKey.SERVER_IP_ADDRESS); // Print the IP address. 3042 } catch (error) { 3043 console.error(`error = ${error}`); 3044 } 3045 } 3046 } else { 3047 console.error(`Failed to create AVPlayer, error message:${err.message}`); 3048 } 3049}); 3050``` 3051 3052## AVRecorder<sup>9+</sup> 3053 3054A 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. 3055 3056For 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). 3057 3058> **NOTE** 3059> 3060> 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). 3061 3062### Attributes 3063 3064**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3065 3066| Name | Type | Read-Only| Optional| Description | 3067| ------- | ------------------------------------ | ---- | ---- | ------------------ | 3068| state9+ | [AVRecorderState](#avrecorderstate9) | Yes | No | AVRecorder state.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 3069 3070### prepare<sup>9+</sup> 3071 3072prepare(config: AVRecorderConfig, callback: AsyncCallback\<void>): void 3073 3074Sets audio and video recording parameters. This API uses an asynchronous callback to return the result. 3075 3076**Required permissions:** ohos.permission.MICROPHONE 3077 3078This permission is required only if audio recording is involved. 3079 3080To 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). 3081 3082**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3083 3084**Parameters** 3085 3086| Name | Type | Mandatory| Description | 3087| -------- | -------------------------------------- | ---- | ------------------------------------- | 3088| config | [AVRecorderConfig](#avrecorderconfig9) | Yes | Audio and video recording parameters to set. | 3089| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 3090 3091**Error codes** 3092 3093For details about the error codes, see [Media Error Codes](errorcode-media.md). 3094 3095| ID| Error Message | 3096| -------- | --------------------------------------- | 3097| 201 | Permission denied. Return by callback. | 3098| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 3099| 5400102 | Operate not permit. Return by callback. | 3100| 5400105 | Service died. Return by callback. | 3101 3102**Example** 3103 3104```ts 3105import { BusinessError } from '@kit.BasicServicesKit'; 3106 3107// Configure the parameters based on those supported by the hardware device. 3108let avRecorderProfile: media.AVRecorderProfile = { 3109 audioBitrate : 48000, 3110 audioChannels : 2, 3111 audioCodec : media.CodecMimeType.AUDIO_AAC, 3112 audioSampleRate : 48000, 3113 fileFormat : media.ContainerFormatType.CFT_MPEG_4, 3114 videoBitrate : 2000000, 3115 videoCodec : media.CodecMimeType.VIDEO_AVC, 3116 videoFrameWidth : 640, 3117 videoFrameHeight : 480, 3118 videoFrameRate : 30 3119} 3120let avRecorderConfig: media.AVRecorderConfig = { 3121 audioSourceType : media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC, 3122 videoSourceType : media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV, 3123 profile : avRecorderProfile, 3124 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. 3125 rotation: 0, // The value can be 0, 90, 180, or 270. If any other value is used, prepare() reports an error. 3126 location : { latitude : 30, longitude : 130 } 3127} 3128 3129avRecorder.prepare(avRecorderConfig, (err: BusinessError) => { 3130 if (err) { 3131 console.error('Failed to prepare and error is ' + err.message); 3132 } else { 3133 console.info('Succeeded in preparing'); 3134 } 3135}) 3136``` 3137 3138### prepare<sup>9+</sup> 3139 3140prepare(config: AVRecorderConfig): Promise\<void> 3141 3142Sets audio and video recording parameters. This API uses a promise to return the result. 3143 3144**Required permissions:** ohos.permission.MICROPHONE 3145 3146This permission is required only if audio recording is involved. 3147 3148To 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). 3149 3150**Atomic service API**: This API can be used in atomic services since API version 12. 3151 3152**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3153 3154**Parameters** 3155 3156| Name| Type | Mandatory| Description | 3157| ------ | -------------------------------------- | ---- | -------------------------- | 3158| config | [AVRecorderConfig](#avrecorderconfig9) | Yes | Audio and video recording parameters to set.| 3159 3160**Return value** 3161 3162| Type | Description | 3163| -------------- | ------------------------------------------ | 3164| Promise\<void> | Promise that returns no value.| 3165 3166**Error codes** 3167 3168For details about the error codes, see [Media Error Codes](errorcode-media.md). 3169 3170| ID| Error Message | 3171| -------- | -------------------------------------- | 3172| 201 | Permission denied. Return by promise. | 3173| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 3174| 5400102 | Operate not permit. Return by promise. | 3175| 5400105 | Service died. Return by promise. | 3176 3177**Example** 3178 3179```ts 3180import { BusinessError } from '@kit.BasicServicesKit'; 3181 3182// Configure the parameters based on those supported by the hardware device. 3183let avRecorderProfile: media.AVRecorderProfile = { 3184 audioBitrate : 48000, 3185 audioChannels : 2, 3186 audioCodec : media.CodecMimeType.AUDIO_AAC, 3187 audioSampleRate : 48000, 3188 fileFormat : media.ContainerFormatType.CFT_MPEG_4, 3189 videoBitrate : 2000000, 3190 videoCodec : media.CodecMimeType.VIDEO_AVC, 3191 videoFrameWidth : 640, 3192 videoFrameHeight : 480, 3193 videoFrameRate : 30 3194} 3195let avRecorderConfig: media.AVRecorderConfig = { 3196 audioSourceType : media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC, 3197 videoSourceType : media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV, 3198 profile : avRecorderProfile, 3199 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. 3200 rotation: 0, // The value can be 0, 90, 180, or 270. If any other value is used, prepare() reports an error. 3201 location : { latitude : 30, longitude : 130 } 3202} 3203 3204avRecorder.prepare(avRecorderConfig).then(() => { 3205 console.info('Succeeded in preparing'); 3206}).catch((err: BusinessError) => { 3207 console.error('Failed to prepare and catch error is ' + err.message); 3208}); 3209``` 3210 3211### getInputSurface<sup>9+</sup> 3212 3213getInputSurface(callback: AsyncCallback\<string>): void 3214 3215Obtains 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. 3216 3217Note 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. 3218 3219This API can be called only after the [prepare()](#prepare9-2) API is called. 3220 3221**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3222 3223**Parameters** 3224 3225| Name | Type | Mandatory| Description | 3226| -------- | ---------------------- | ---- | --------------------------- | 3227| 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.| 3228 3229**Error codes** 3230 3231For details about the error codes, see [Media Error Codes](errorcode-media.md). 3232 3233| ID| Error Message | 3234| -------- | --------------------------------------- | 3235| 5400102 | Operate not permit. Return by callback. | 3236| 5400103 | IO error. Return by callback. | 3237| 5400105 | Service died. Return by callback. | 3238 3239**Example** 3240 3241```ts 3242import { BusinessError } from '@kit.BasicServicesKit'; 3243let surfaceID: string; // The surfaceID is transferred to the camera API to create a videoOutput instance. 3244 3245avRecorder.getInputSurface((err: BusinessError, surfaceId: string) => { 3246 if (err) { 3247 console.error('Failed to do getInputSurface and error is ' + err.message); 3248 } else { 3249 console.info('Succeeded in doing getInputSurface'); 3250 surfaceID = surfaceId; 3251 } 3252}); 3253 3254``` 3255 3256### getInputSurface<sup>9+</sup> 3257 3258getInputSurface(): Promise\<string> 3259 3260Obtains 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. 3261 3262Note 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. 3263 3264This API can be called only after the [prepare()](#prepare9-3) API is called. 3265 3266**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3267 3268**Return value** 3269 3270| Type | Description | 3271| ---------------- | -------------------------------- | 3272| Promise\<string> | Promise used to return the result.| 3273 3274**Error codes** 3275 3276For details about the error codes, see [Media Error Codes](errorcode-media.md). 3277 3278| ID| Error Message | 3279| -------- | -------------------------------------- | 3280| 5400102 | Operate not permit. Return by promise. | 3281| 5400103 | IO error. Return by promise. | 3282| 5400105 | Service died. Return by promise. | 3283 3284**Example** 3285 3286```ts 3287import { BusinessError } from '@kit.BasicServicesKit'; 3288let surfaceID: string; // The surfaceID is transferred to the camera API to create a videoOutput instance. 3289 3290avRecorder.getInputSurface().then((surfaceId: string) => { 3291 console.info('Succeeded in getting InputSurface'); 3292 surfaceID = surfaceId; 3293}).catch((err: BusinessError) => { 3294 console.error('Failed to get InputSurface and catch error is ' + err.message); 3295}); 3296``` 3297 3298### updateRotation<sup>12+</sup> 3299 3300updateRotation(rotation: number): Promise\<void> 3301 3302Updates the video rotation angle. This API uses a promise to return the result. 3303 3304This API can be called only after the [prepare()](#prepare9-3) event is triggered and before the [start()](#start9) API is called. 3305 3306**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3307 3308**Parameters** 3309 3310| Name | Type | Mandatory| Description | 3311| -------- | -------------------- | ---- | --------------------------- | 3312| rotation | number | Yes | Rotation angle, which can only be 0, 90, 180, or 270 degrees.| 3313 3314**Return value** 3315 3316| Type | Description | 3317| ---------------- | -------------------------------- | 3318| Promise\<void> | Promise that returns no value.| 3319 3320**Error codes** 3321 3322For details about the error codes, see [Media Error Codes](errorcode-media.md). 3323 3324| ID| Error Message | 3325| -------- | -------------------------------------- | 3326| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 3327| 5400102 | Operation not allowed. Return by promise. | 3328| 5400103 | IO error. Return by promise. | 3329| 5400105 | Service died. Return by promise. | 3330 3331**Example** 3332 3333```ts 3334import { BusinessError } from '@kit.BasicServicesKit'; 3335 3336let rotation = 90 3337 3338avRecorder.updateRotation(rotation).then(() => { 3339 console.info('Succeeded in updateRotation'); 3340}).catch((err: BusinessError) => { 3341 console.error('Failed to updateRotation and catch error is ' + err.message); 3342}); 3343``` 3344 3345### start<sup>9+</sup> 3346 3347start(callback: AsyncCallback\<void>): void 3348 3349Starts recording. This API uses an asynchronous callback to return the result. 3350 3351For 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. 3352 3353**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3354 3355**Parameters** 3356 3357| Name | Type | Mandatory| Description | 3358| -------- | -------------------- | ---- | ---------------------------- | 3359| callback | AsyncCallback\<void> | Yes |Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 3360 3361**Error codes** 3362 3363For details about the error codes, see [Media Error Codes](errorcode-media.md). 3364 3365| ID| Error Message | 3366| -------- | --------------------------------------- | 3367| 5400102 | Operate not permit. Return by callback. | 3368| 5400103 | IO error. Return by callback. | 3369| 5400105 | Service died. Return by callback. | 3370 3371**Example** 3372 3373```ts 3374import { BusinessError } from '@kit.BasicServicesKit'; 3375 3376avRecorder.start((err: BusinessError) => { 3377 if (err) { 3378 console.error('Failed to start AVRecorder and error is ' + err.message); 3379 } else { 3380 console.info('Succeeded in starting AVRecorder'); 3381 } 3382}); 3383``` 3384 3385### start<sup>9+</sup> 3386 3387start(): Promise\<void> 3388 3389Starts recording. This API uses a promise to return the result. 3390 3391For 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. 3392 3393**Atomic service API**: This API can be used in atomic services since API version 12. 3394 3395**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3396 3397**Return value** 3398 3399| Type | Description | 3400| -------------- | ------------------------------------- | 3401| Promise\<void> | Promise that returns no value.| 3402 3403**Error codes** 3404 3405For details about the error codes, see [Media Error Codes](errorcode-media.md). 3406 3407| ID| Error Message | 3408| -------- | -------------------------------------- | 3409| 5400102 | Operate not permit. Return by promise. | 3410| 5400103 | IO error. Return by promise. | 3411| 5400105 | Service died. Return by promise. | 3412 3413**Example** 3414 3415```ts 3416import { BusinessError } from '@kit.BasicServicesKit'; 3417 3418avRecorder.start().then(() => { 3419 console.info('Succeeded in starting AVRecorder'); 3420}).catch((err: BusinessError) => { 3421 console.error('Failed to start AVRecorder and catch error is ' + err.message); 3422}); 3423``` 3424 3425### pause<sup>9+</sup> 3426 3427pause(callback: AsyncCallback\<void>): void 3428 3429Pauses recording. This API uses an asynchronous callback to return the result. 3430 3431This API can be called only after the [start()](#start9) API is called. You can call [resume()](#resume9) to resume recording. 3432 3433**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3434 3435**Parameters** 3436 3437| Name | Type | Mandatory| Description | 3438| -------- | -------------------- | ---- | --------------------------- | 3439| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 3440 3441**Error codes** 3442 3443For details about the error codes, see [Media Error Codes](errorcode-media.md). 3444 3445| ID| Error Message | 3446| -------- | --------------------------------------- | 3447| 5400102 | Operate not permit. Return by callback. | 3448| 5400103 | IO error. Return by callback. | 3449| 5400105 | Service died. Return by callback. | 3450 3451**Example** 3452 3453```ts 3454import { BusinessError } from '@kit.BasicServicesKit'; 3455 3456avRecorder.pause((err: BusinessError) => { 3457 if (err) { 3458 console.error('Failed to pause AVRecorder and error is ' + err.message); 3459 } else { 3460 console.info('Succeeded in pausing'); 3461 } 3462}); 3463``` 3464 3465### pause<sup>9+</sup> 3466 3467pause(): Promise\<void> 3468 3469Pauses recording. This API uses a promise to return the result. 3470 3471This API can be called only after the [start()](#start9-1) API is called. You can call [resume()](#resume9-1) to resume recording. 3472 3473**Atomic service API**: This API can be used in atomic services since API version 12. 3474 3475**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3476 3477**Return value** 3478 3479| Type | Description | 3480| -------------- | ------------------------------------- | 3481| Promise\<void> | Promise that returns no value.| 3482 3483**Error codes** 3484 3485For details about the error codes, see [Media Error Codes](errorcode-media.md). 3486 3487| ID| Error Message | 3488| -------- | -------------------------------------- | 3489| 5400102 | Operate not permit. Return by promise. | 3490| 5400103 | IO error. Return by promise. | 3491| 5400105 | Service died. Return by promise. | 3492 3493**Example** 3494 3495```ts 3496import { BusinessError } from '@kit.BasicServicesKit'; 3497 3498avRecorder.pause().then(() => { 3499 console.info('Succeeded in pausing'); 3500}).catch((err: BusinessError) => { 3501 console.error('Failed to pause AVRecorder and catch error is ' + err.message); 3502}); 3503``` 3504 3505### resume<sup>9+</sup> 3506 3507resume(callback: AsyncCallback\<void>): void 3508 3509Resumes recording. This API uses an asynchronous callback to return the result. 3510 3511This API can be called only after the [pause()](#pause9-2) API is called. 3512 3513**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3514 3515**Parameters** 3516 3517| Name | Type | Mandatory| Description | 3518| -------- | -------------------- | ---- | ---------------------------- | 3519| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 3520 3521**Error codes** 3522 3523For details about the error codes, see [Media Error Codes](errorcode-media.md). 3524 3525| ID| Error Message | 3526| -------- | --------------------------------------- | 3527| 5400102 | Operate not permit. Return by callback. | 3528| 5400103 | IO error. Return by callback. | 3529| 5400105 | Service died. Return by callback. | 3530 3531**Example** 3532 3533```ts 3534import { BusinessError } from '@kit.BasicServicesKit'; 3535 3536avRecorder.resume((err: BusinessError) => { 3537 if (err) { 3538 console.error('Failed to resume AVRecorder and error is ' + err.message); 3539 } else { 3540 console.info('Succeeded in resuming AVRecorder'); 3541 } 3542}); 3543``` 3544 3545### resume<sup>9+</sup> 3546 3547resume(): Promise\<void> 3548 3549Resumes recording. This API uses a promise to return the result. 3550 3551This API can be called only after the [pause()](#pause9-3) API is called. 3552 3553**Atomic service API**: This API can be used in atomic services since API version 12. 3554 3555**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3556 3557**Return value** 3558 3559| Type | Description | 3560| -------------- | ------------------------------------- | 3561| Promise\<void> | Promise that returns no value.| 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 promise. | 3570| 5400103 | IO error. Return by promise. | 3571| 5400105 | Service died. Return by promise. | 3572 3573**Example** 3574 3575```ts 3576import { BusinessError } from '@kit.BasicServicesKit'; 3577 3578avRecorder.resume().then(() => { 3579 console.info('Succeeded in resuming AVRecorder'); 3580}).catch((err: BusinessError) => { 3581 console.error('Failed to resume AVRecorder failed and catch error is ' + err.message); 3582}); 3583``` 3584 3585### stop<sup>9+</sup> 3586 3587stop(callback: AsyncCallback\<void>): void 3588 3589Stops recording. This API uses an asynchronous callback to return the result. 3590 3591This API can be called only after the [start()](#start9) or [pause()](#pause9-2) API is called. 3592 3593For 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. 3594 3595**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3596 3597**Parameters** 3598 3599| Name | Type | Mandatory| Description | 3600| -------- | -------------------- | ---- | ---------------------------- | 3601| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 3602 3603**Error codes** 3604 3605For details about the error codes, see [Media Error Codes](errorcode-media.md). 3606 3607| ID| Error Message | 3608| -------- | --------------------------------------- | 3609| 5400102 | Operate not permit. Return by callback. | 3610| 5400103 | IO error. Return by callback. | 3611| 5400105 | Service died. Return by callback. | 3612 3613**Example** 3614 3615```ts 3616import { BusinessError } from '@kit.BasicServicesKit'; 3617 3618avRecorder.stop((err: BusinessError) => { 3619 if (err) { 3620 console.error('Failed to stop AVRecorder and error is ' + err.message); 3621 } else { 3622 console.info('Succeeded in stopping AVRecorder'); 3623 } 3624}); 3625``` 3626 3627### stop<sup>9+</sup> 3628 3629stop(): Promise\<void> 3630 3631Stops recording. This API uses a promise to return the result. 3632 3633This API can be called only after the [start()](#start9-1) or [pause()](#pause9-3) API is called. 3634 3635For 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. 3636 3637**Atomic service API**: This API can be used in atomic services since API version 12. 3638 3639**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3640 3641**Return value** 3642 3643| Type | Description | 3644| -------------- | ------------------------------------- | 3645| Promise\<void> | Promise that returns no value.| 3646 3647**Error codes** 3648 3649For details about the error codes, see [Media Error Codes](errorcode-media.md). 3650 3651| ID| Error Message | 3652| -------- | -------------------------------------- | 3653| 5400102 | Operate not permit. Return by promise. | 3654| 5400103 | IO error. Return by promise. | 3655| 5400105 | Service died. Return by promise. | 3656 3657**Example** 3658 3659```ts 3660import { BusinessError } from '@kit.BasicServicesKit'; 3661 3662avRecorder.stop().then(() => { 3663 console.info('Succeeded in stopping AVRecorder'); 3664}).catch((err: BusinessError) => { 3665 console.error('Failed to stop AVRecorder and catch error is ' + err.message); 3666}); 3667``` 3668 3669### reset<sup>9+</sup> 3670 3671reset(callback: AsyncCallback\<void>): void 3672 3673Resets audio and video recording. This API uses an asynchronous callback to return the result. 3674 3675For 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. 3676 3677**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3678 3679**Parameters** 3680 3681| Name | Type | Mandatory| Description | 3682| -------- | -------------------- | ---- | ------------------------------ | 3683| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 3684 3685**Error codes** 3686 3687For details about the error codes, see [Media Error Codes](errorcode-media.md). 3688 3689| ID| Error Message | 3690| -------- | --------------------------------- | 3691| 5400103 | IO error. Return by callback. | 3692| 5400105 | Service died. Return by callback. | 3693 3694**Example** 3695 3696```ts 3697import { BusinessError } from '@kit.BasicServicesKit'; 3698 3699avRecorder.reset((err: BusinessError) => { 3700 if (err) { 3701 console.error('Failed to reset AVRecorder and error is ' + err.message); 3702 } else { 3703 console.info('Succeeded in resetting AVRecorder'); 3704 } 3705}); 3706``` 3707 3708### reset<sup>9+</sup> 3709 3710reset(): Promise\<void> 3711 3712Resets audio and video recording. This API uses a promise to return the result. 3713 3714For 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. 3715 3716**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3717 3718**Return value** 3719 3720| Type | Description | 3721| -------------- | --------------------------------------- | 3722| Promise\<void> | Promise that returns no value.| 3723 3724**Error codes** 3725 3726For details about the error codes, see [Media Error Codes](errorcode-media.md). 3727 3728| ID| Error Message | 3729| -------- | -------------------------------- | 3730| 5400103 | IO error. Return by promise. | 3731| 5400105 | Service died. Return by promise. | 3732 3733**Example** 3734 3735```ts 3736import { BusinessError } from '@kit.BasicServicesKit'; 3737 3738avRecorder.reset().then(() => { 3739 console.info('Succeeded in resetting AVRecorder'); 3740}).catch((err: BusinessError) => { 3741 console.error('Failed to reset and catch error is ' + err.message); 3742}); 3743``` 3744 3745### release<sup>9+</sup> 3746 3747release(callback: AsyncCallback\<void>): void 3748 3749Releases the audio and video recording resources. This API uses an asynchronous callback to return the result. 3750 3751After the resources are released, you can no longer perform any operation on the **AVRecorder** instance. 3752 3753**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3754 3755**Parameters** 3756 3757| Name | Type | Mandatory| Description | 3758| -------- | -------------------- | ---- | ---------------------------------- | 3759| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 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((err: BusinessError) => { 3775 if (err) { 3776 console.error('Failed to release AVRecorder and error is ' + err.message); 3777 } else { 3778 console.info('Succeeded in releasing AVRecorder'); 3779 } 3780}); 3781``` 3782 3783### release<sup>9+</sup> 3784 3785release(): Promise\<void> 3786 3787Releases the audio and video recording resources. This API uses a promise to return the result. 3788 3789After the resources are released, you can no longer perform any operation on the **AVRecorder** instance. 3790 3791**Atomic service API**: This API can be used in atomic services since API version 12. 3792 3793**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3794 3795**Return value** 3796 3797| Type | Description | 3798| -------------- | ------------------------------------------- | 3799| Promise\<void> | Promise that returns no value.| 3800 3801**Error codes** 3802 3803For details about the error codes, see [Media Error Codes](errorcode-media.md). 3804 3805| ID| Error Message | 3806| -------- | --------------------------------- | 3807| 5400105 | Service died. Return by callback. | 3808 3809**Example** 3810 3811```ts 3812import { BusinessError } from '@kit.BasicServicesKit'; 3813 3814avRecorder.release().then(() => { 3815 console.info('Succeeded in releasing AVRecorder'); 3816}).catch((err: BusinessError) => { 3817 console.error('Failed to release AVRecorder and catch error is ' + err.message); 3818}); 3819``` 3820 3821### getCurrentAudioCapturerInfo<sup>11+</sup> 3822 3823getCurrentAudioCapturerInfo(callback: AsyncCallback\<audio.AudioCapturerChangeInfo>): void 3824 3825Obtains the information about the current audio capturer. This API uses an asynchronous callback to return the result. 3826 3827This 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. 3828 3829**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3830 3831**Parameters** 3832 3833| Name | Type | Mandatory| Description | 3834| -------- | ------------------------------------------------------------ | ---- | ------------------------------------ | 3835| 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.| 3836 3837**Error codes** 3838 3839For details about the error codes, see [Media Error Codes](errorcode-media.md). 3840 3841| ID| Error Message | 3842| -------- | ------------------------------------------ | 3843| 5400102 | Operation not allowed. | 3844| 5400103 | I/O error. | 3845| 5400105 | Service died. Return by callback. | 3846 3847**Example** 3848 3849```ts 3850import { audio } from '@kit.AudioKit'; 3851 3852let currentCapturerInfo: audio.AudioCapturerChangeInfo; 3853 3854avRecorder.getCurrentAudioCapturerInfo((err: BusinessError, capturerInfo: audio.AudioCapturerChangeInfo) => { 3855 if (err) { 3856 console.error('Failed to get CurrentAudioCapturerInfo and error is ' + err.message); 3857 } else { 3858 console.info('Succeeded in getting CurrentAudioCapturerInfo'); 3859 currentCapturerInfo = capturerInfo; 3860 } 3861}); 3862``` 3863 3864### getCurrentAudioCapturerInfo<sup>11+</sup> 3865 3866getCurrentAudioCapturerInfo(): Promise\<audio.AudioCapturerChangeInfo> 3867 3868Obtains the information about the current audio capturer. This API uses a promise to return the result. 3869 3870This 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. 3871 3872**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3873 3874**Return value** 3875 3876| Type | Description | 3877| ------------------------------------------------------------ | ------------------------------------------------- | 3878| Promise\<[audio.AudioCapturerChangeInfo](../apis-audio-kit/js-apis-audio.md#audiocapturerchangeinfo9)> | Promise used to return the audio capturer information.| 3879 3880**Error codes** 3881 3882For details about the error codes, see [Media Error Codes](errorcode-media.md). 3883 3884| ID| Error Message | 3885| -------- | -------------------------------- | 3886| 5400102 | Operation not allowed. | 3887| 5400103 | I/O error. | 3888| 5400105 | Service died. Return by promise. | 3889 3890**Example** 3891 3892```ts 3893import { audio } from '@kit.AudioKit'; 3894 3895let currentCapturerInfo: audio.AudioCapturerChangeInfo; 3896 3897avRecorder.getCurrentAudioCapturerInfo().then((capturerInfo: audio.AudioCapturerChangeInfo) => { 3898 console.info('Succeeded in getting CurrentAudioCapturerInfo'); 3899 currentCapturerInfo = capturerInfo; 3900}).catch((err: BusinessError) => { 3901 console.error('Failed to get CurrentAudioCapturerInfo and catch error is ' + err.message); 3902}); 3903``` 3904 3905### getAudioCapturerMaxAmplitude<sup>11+</sup> 3906 3907getAudioCapturerMaxAmplitude(callback: AsyncCallback\<number>): void 3908 3909Obtains the maximum amplitude of the current audio capturer. This API uses an asynchronous callback to return the result. 3910 3911This 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. 3912 3913The 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. 3914 3915**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3916 3917**Parameters** 3918 3919| Name | Type | Mandatory| Description | 3920| -------- | ---------------------- | ---- | ------------------------------------ | 3921| 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.| 3922 3923**Error codes** 3924 3925For details about the error codes, see [Media Error Codes](errorcode-media.md). 3926 3927| ID| Error Message | 3928| -------- | ------------------------------------------ | 3929| 5400102 | Operation not allowed. | 3930| 5400105 | Service died. Return by callback. | 3931 3932**Example** 3933 3934```ts 3935let maxAmplitude: number; 3936 3937avRecorder.getAudioCapturerMaxAmplitude((err: BusinessError, amplitude: number) => { 3938 if (err) { 3939 console.error('Failed to get AudioCapturerMaxAmplitude and error is ' + err.message); 3940 } else { 3941 console.info('Succeeded in getting AudioCapturerMaxAmplitude'); 3942 maxAmplitude = amplitude; 3943 } 3944}); 3945``` 3946 3947### getAudioCapturerMaxAmplitude<sup>11+</sup> 3948 3949getAudioCapturerMaxAmplitude(): Promise\<number> 3950 3951Obtains the maximum amplitude of the current audio capturer. This API uses a promise to return the result. 3952 3953This 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. 3954 3955The 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. 3956 3957**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3958 3959**Return value** 3960 3961| Type | Description | 3962| ---------------- | ------------------------------------------------- | 3963| Promise\<number>| Promise used to return the maximum amplitude obtained.| 3964 3965**Error codes** 3966 3967For details about the error codes, see [Media Error Codes](errorcode-media.md). 3968 3969| ID| Error Message | 3970| -------- | -------------------------------- | 3971| 5400102 | Operation not allowed. | 3972| 5400105 | Service died. Return by promise. | 3973 3974**Example** 3975 3976```ts 3977let maxAmplitude: number; 3978 3979avRecorder.getAudioCapturerMaxAmplitude().then((amplitude: number) => { 3980 console.info('Succeeded in getting AudioCapturerMaxAmplitude'); 3981 maxAmplitude = amplitude; 3982}).catch((err: BusinessError) => { 3983 console.error('Failed to get AudioCapturerMaxAmplitude and catch error is ' + err.message); 3984}); 3985``` 3986 3987### getAvailableEncoder<sup>11+</sup> 3988 3989getAvailableEncoder(callback: AsyncCallback\<Array\<EncoderInfo>>): void 3990 3991Obtains available encoders. This API uses an asynchronous callback to return the result. 3992 3993**System capability**: SystemCapability.Multimedia.Media.AVRecorder 3994 3995**Parameters** 3996 3997| Name | Type | Mandatory| Description | 3998| -------- | ----------------------------------------------------- | ---- | ------------------------------------ | 3999| 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.| 4000 4001**Error codes** 4002 4003For details about the error codes, see [Media Error Codes](errorcode-media.md). 4004 4005| ID| Error Message | 4006| -------- | ------------------------------------------ | 4007| 5400102 | Operation not allowed. | 4008| 5400105 | Service died. Return by callback. | 4009 4010**Example** 4011 4012```ts 4013let encoderInfo: media.EncoderInfo; 4014 4015avRecorder.getAvailableEncoder((err: BusinessError, info: media.EncoderInfo[]) => { 4016 if (err) { 4017 console.error('Failed to get AvailableEncoder and error is ' + err.message); 4018 } else { 4019 console.info('Succeeded in getting AvailableEncoder'); 4020 encoderInfo = info[0]; 4021 } 4022}); 4023``` 4024 4025### getAvailableEncoder<sup>11+</sup> 4026 4027getAvailableEncoder(): Promise\<Array\<EncoderInfo>> 4028 4029Obtains available encoders. This API uses an asynchronous callback to return the result. 4030 4031**System capability**: SystemCapability.Multimedia.Media.AVRecorder 4032 4033**Return value** 4034 4035| Type | Description | 4036| ----------------------------------------------- | ----------------------------------------------- | 4037| Promise\<Array\<[EncoderInfo](#encoderinfo11)>> | Promise used to return the information about the available encoders.| 4038 4039**Error codes** 4040 4041For details about the error codes, see [Media Error Codes](errorcode-media.md). 4042 4043| ID| Error Message | 4044| -------- | -------------------------------- | 4045| 5400102 | Operation not allowed. | 4046| 5400105 | Service died. Return by promise. | 4047 4048**Example** 4049 4050```ts 4051let encoderInfo: media.EncoderInfo; 4052 4053avRecorder.getAvailableEncoder().then((info: media.EncoderInfo[]) => { 4054 console.info('Succeeded in getting AvailableEncoder'); 4055 encoderInfo = info[0]; 4056}).catch((err: BusinessError) => { 4057 console.error('Failed to get AvailableEncoder and catch error is ' + err.message); 4058}); 4059``` 4060 4061### getAVRecorderConfig<sup>11+</sup> 4062 4063getAVRecorderConfig(callback: AsyncCallback\<AVRecorderConfig>): void 4064 4065Obtains the real-time configuration of this AVRecorder. This API uses an asynchronous callback to return the result. 4066 4067This API can be called only after [prepare()](#prepare9-2) is called. 4068 4069**System capability**: SystemCapability.Multimedia.Media.AVRecorder 4070 4071**Parameters** 4072 4073| Name | Type | Mandatory| Description | 4074| -------- | ---------------------- | ---- | --------------------------- | 4075| 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.| 4076 4077**Error codes** 4078 4079For details about the error codes, see [Media Error Codes](errorcode-media.md). 4080 4081| ID| Error Message | 4082| -------- | ------------------------------------------ | 4083| 5400102 | Operate not permit. Return by callback. | 4084| 5400103 | IO error. Return by callback. | 4085| 5400105 | Service died. Return by callback. | 4086 4087**Example** 4088 4089```ts 4090import { BusinessError } from '@kit.BasicServicesKit'; 4091 4092let avConfig: media.AVRecorderConfig; 4093 4094avRecorder.getAVRecorderConfig((err: BusinessError, config: media.AVRecorderConfig) => { 4095 if (err) { 4096 console.error('Failed to get avConfig and error is ' + err.message); 4097 } else { 4098 console.info('Succeeded in getting AVRecorderConfig'); 4099 avConfig = config; 4100 } 4101}); 4102``` 4103 4104### getAVRecorderConfig<sup>11+</sup> 4105 4106getAVRecorderConfig(): Promise\<AVRecorderConfig>; 4107 4108Obtains the real-time configuration of this AVRecorder. This API uses a promise to return the result. 4109 4110This API can be called only after [prepare()](#prepare9-3) is called. 4111 4112**System capability**: SystemCapability.Multimedia.Media.AVRecorder 4113 4114**Return value** 4115 4116| Type | Description | 4117| ---------------- | -------------------------------- | 4118| Promise\<[AVRecorderConfig](#avrecorderconfig9)> | Promise used to return the real-time configuration.| 4119 4120**Error codes** 4121 4122For details about the error codes, see [Media Error Codes](errorcode-media.md). 4123 4124| ID| Error Message | 4125| -------- | ----------------------------------------- | 4126| 5400102 | Operate not permit. Return by promise. | 4127| 5400103 | IO error. Return by promise. | 4128| 5400105 | Service died. Return by promise. | 4129 4130**Example** 4131 4132```ts 4133import { BusinessError } from '@kit.BasicServicesKit'; 4134 4135let avConfig: media.AVRecorderConfig; 4136 4137avRecorder.getAVRecorderConfig().then((config: media.AVRecorderConfig) => { 4138 console.info('Succeeded in getting AVRecorderConfig'); 4139 avConfig = config; 4140}).catch((err: BusinessError) => { 4141 console.error('Failed to get AVRecorderConfig and catch error is ' + err.message); 4142}); 4143``` 4144 4145### on('stateChange')<sup>9+</sup> 4146 4147on(type: 'stateChange', callback: OnAVRecorderStateChangeHandler): void 4148 4149Subscribes 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. 4150 4151**Atomic service API**: This API can be used in atomic services since API version 12. 4152 4153**System capability**: SystemCapability.Multimedia.Media.AVRecorder 4154 4155**Parameters** 4156 4157| Name | Type | Mandatory| Description | 4158| -------- | -------- | ---- | ------------------------------------------------------------ | 4159| type | string | Yes | Event type, which is **'stateChange'** in this case. This event can be triggered by both user operations and the system.| 4160| callback | [OnAVRecorderStateChangeHandler](#onavrecorderstatechangehandler12) | Yes | Callback invoked when the event is triggered.| 4161 4162**Error codes** 4163 4164For details about the error codes, see [Media Error Codes](errorcode-media.md). 4165 4166| ID| Error Message | 4167| -------- | --------------------------------- | 4168| 5400103 | IO error. Return by callback. | 4169| 5400105 | Service died. Return by callback. | 4170 4171**Example** 4172 4173```ts 4174avRecorder.on('stateChange', async (state: media.AVRecorderState, reason: media.StateChangeReason) => { 4175 console.info('case state has changed, new state is :' + state + ',and new reason is : ' + reason); 4176}); 4177``` 4178 4179### off('stateChange')<sup>9+</sup> 4180 4181off(type: 'stateChange', callback?: OnAVRecorderStateChangeHandler): void 4182 4183Unsubscribes from AVRecorder state changes. 4184 4185**Atomic service API**: This API can be used in atomic services since API version 12. 4186 4187**System capability**: SystemCapability.Multimedia.Media.AVRecorder 4188 4189**Parameters** 4190 4191| Name| Type | Mandatory| Description | 4192| ------ | ------ | ---- | ------------------------------------------------------------ | 4193| type | string | Yes | Event type, which is **'stateChange'** in this case. This event can be triggered by both user operations and the system.| 4194| callback | [OnAVRecorderStateChangeHandler](#onavrecorderstatechangehandler12) | No | Callback invoked when the event is triggered.<br>This parameter is supported since API version 12.| 4195 4196**Example** 4197 4198```ts 4199avRecorder.off('stateChange'); 4200``` 4201 4202### on('error')<sup>9+</sup> 4203 4204on(type: 'error', callback: ErrorCallback): void 4205 4206Subscribes 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. 4207 4208An application can subscribe to only one AVRecorder error event. When the application initiates multiple subscriptions to this event, the last subscription prevails. 4209 4210**Atomic service API**: This API can be used in atomic services since API version 12. 4211 4212**System capability**: SystemCapability.Multimedia.Media.AVRecorder 4213 4214**Parameters** 4215 4216| Name | Type | Mandatory| Description | 4217| -------- | ------------- | ---- | ------------------------------------------------------------ | 4218| type | string | Yes | Event type, which is **'error'** in this case.<br>This event is triggered when an error occurs during recording.| 4219| callback | [ErrorCallback](../apis-basic-services-kit/js-apis-base.md#errorcallback) | Yes | Callback invoked when the event is triggered. | 4220 4221**Error codes** 4222 4223For details about the error codes, see [Media Error Codes](errorcode-media.md). 4224 4225| ID| Error Message | 4226| -------- | ------------------------------------------ | 4227| 201 | Permission denied. | 4228| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 4229| 801 | Capability not supported. | 4230| 5400101 | No memory. | 4231| 5400102 | Operation not allowed. | 4232| 5400103 | I/O error. | 4233| 5400104 | Time out. | 4234| 5400105 | Service died. | 4235| 5400106 | Unsupported format. | 4236| 5400107 | Audio interrupted. | 4237 4238**Example** 4239 4240```ts 4241import { BusinessError } from '@kit.BasicServicesKit'; 4242 4243avRecorder.on('error', (err: BusinessError) => { 4244 console.info('case avRecorder.on(error) called, errMessage is ' + err.message); 4245}); 4246``` 4247 4248### off('error')<sup>9+</sup> 4249 4250off(type: 'error', callback?: ErrorCallback): void 4251 4252Unsubscribes from AVRecorder errors. After the unsubscription, your application can no longer receive AVRecorder errors. 4253 4254**Atomic service API**: This API can be used in atomic services since API version 12. 4255 4256**System capability**: SystemCapability.Multimedia.Media.AVRecorder 4257 4258**Parameters** 4259 4260| Name| Type | Mandatory| Description | 4261| ------ | ------ | ---- | ------------------------------------------------------------ | 4262| type | string | Yes | Event type, which is **'error'** in this case.<br>This event is triggered when an error occurs during recording.| 4263| 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. | 4264 4265**Example** 4266 4267```ts 4268avRecorder.off('error'); 4269``` 4270 4271### on('audioCapturerChange')<sup>11+</sup> 4272 4273on(type: 'audioCapturerChange', callback: Callback<audio.AudioCapturerChangeInfo>): void 4274 4275Subscribes to audio capturer configuration changes. Any configuration change triggers the callback that returns the entire configuration information. 4276 4277When the application initiates multiple subscriptions to this event, the last subscription prevails. 4278 4279**System capability**: SystemCapability.Multimedia.Media.AVRecorder 4280 4281**Parameters** 4282 4283| Name | Type | Mandatory| Description | 4284| -------- | -------- | ---- | ------------------------------------------------------------ | 4285| type | string | Yes |Event type, which is **'audioCapturerChange'** in this case.| 4286| 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.| 4287 4288**Error codes** 4289 4290| ID| Error Message | 4291| -------- | ------------------------------------------ | 4292| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 4293 4294**Example** 4295 4296```ts 4297import { audio } from '@kit.AudioKit' 4298 4299let capturerChangeInfo: audio.AudioCapturerChangeInfo; 4300 4301avRecorder.on('audioCapturerChange', (audioCapturerChangeInfo: audio.AudioCapturerChangeInfo) => { 4302 console.info('audioCapturerChange called'); 4303 capturerChangeInfo = audioCapturerChangeInfo; 4304}); 4305``` 4306 4307### off('audioCapturerChange')<sup>11+</sup> 4308 4309off(type: 'audioCapturerChange', callback?: Callback<audio.AudioCapturerChangeInfo>): void 4310 4311Subscribes to audio capturer configuration changes. 4312 4313**System capability**: SystemCapability.Multimedia.Media.AVRecorder 4314 4315**Parameters** 4316 4317| Name| Type | Mandatory| Description | 4318| ------ | ------ | ---- | ------------------------------------------------------------ | 4319| type | string | Yes | Event type, which is **'audioCapturerChange'** in this case.| 4320| 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.| 4321 4322**Example** 4323 4324```ts 4325avRecorder.off('audioCapturerChange'); 4326``` 4327 4328### on('photoAssetAvailable')<sup>12+</sup> 4329 4330on(type: 'photoAssetAvailable', callback: Callback\<photoAccessHelper.PhotoAsset>): void 4331 4332Subscribes 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. 4333 4334When the application initiates multiple subscriptions to this event, the last subscription prevails. 4335 4336**System capability**: SystemCapability.Multimedia.Media.AVRecorder 4337 4338**Parameters** 4339 4340| Name | Type | Mandatory| Description | 4341| -------- | -------- | ---- | ------------------------------------------------------------ | 4342| type | string | Yes |Event type, which is **'photoAssetAvailable'** in this case. The event is triggered when a photo asset is available.| 4343| 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.| 4344 4345**Error codes** 4346 4347| ID| Error Message | 4348| -------- | ------------------------------------------ | 4349| 5400103 | IO error. Return by callback. | 4350| 5400105 | Service died. Return by callback. | 4351 4352**Example** 4353 4354```ts 4355import { photoAccessHelper } from '@kit.MediaLibraryKit'; 4356import { common } from '@kit.AbilityKit' 4357let photoAsset: photoAccessHelper.PhotoAsset; 4358let context = getContext(this) as common.UIAbilityContext 4359 4360// Example: Process the photoAsset callback and save the video. 4361async function saveVideo(asset: photoAccessHelper.PhotoAsset) { 4362 console.info("saveVideo called"); 4363 try { 4364 let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context); 4365 let assetChangeRequest: photoAccessHelper.MediaAssetChangeRequest = new photoAccessHelper.MediaAssetChangeRequest(asset); 4366 assetChangeRequest.saveCameraPhoto(); 4367 await phAccessHelper.applyChanges(assetChangeRequest); 4368 console.info('apply saveVideo successfully'); 4369 } catch (err) { 4370 console.error(`apply saveVideo failed with error: ${err.code}, ${err.message}`); 4371 } 4372} 4373// Subscribe to the photoAsset event. 4374avRecorder.on('photoAssetAvailable', (asset: photoAccessHelper.PhotoAsset) => { 4375 console.info('photoAssetAvailable called'); 4376 if (asset != undefined) { 4377 photoAsset = asset; 4378 // Process the photoAsset callback. 4379 // Example: this.saveVideo (asset); 4380 } else { 4381 console.error('photoAsset is undefined'); 4382 } 4383}); 4384``` 4385 4386### off('photoAssetAvailable')<sup>12+</sup> 4387 4388off(type: 'photoAssetAvailable', callback?: Callback<photoAccessHelper.PhotoAsset>): void 4389 4390Unsubscribes from media asset callback events. 4391 4392**System capability**: SystemCapability.Multimedia.Media.AVRecorder 4393 4394**Parameters** 4395 4396| Name| Type | Mandatory| Description | 4397| ------ | ------ | ---- | ------------------------------------------------------------ | 4398| type | string | Yes | Event type, which is **'photoAssetAvailable'** in this case.| 4399 4400**Example** 4401 4402```ts 4403avRecorder.off('photoAssetAvailable'); 4404``` 4405 4406## AVRecorderState<sup>9+</sup> 4407 4408type AVRecorderState = 'idle' | 'prepared' | 'started' | 'paused' | 'stopped' | 'released' | 'error' 4409 4410Enumerates the AVRecorder states. You can obtain the state through the **state** attribute. 4411 4412**Atomic service API**: This API can be used in atomic services since API version 12. 4413 4414**System capability**: SystemCapability.Multimedia.Media.AVRecorder 4415 4416| Type | Description | 4417| -------- | ------------------------------------------------------------ | 4418| '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. | 4419| 'prepared' | The AVRecorder enters this state when the parameters are set. In this state, you can call [AVRecorder.start()](#start9) to start recording.| 4420| '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.| 4421| '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.| 4422| '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.| 4423| '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.| 4424| '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.| 4425 4426## OnAVRecorderStateChangeHandler<sup>12+</sup> 4427 4428type OnAVRecorderStateChangeHandler = (state: AVRecorderState, reason: StateChangeReason) => void 4429 4430Describes the callback invoked for the AVRecorder state change event. 4431 4432**Atomic service API**: This API can be used in atomic services since API version 12. 4433 4434**System capability**: SystemCapability.Multimedia.Media.AVPlayer 4435 4436| Name | Type | Mandatory| Description | 4437| ------ | ------ | ------ | ------------------------------------------------------------ | 4438| state | [AVRecorderState](#avrecorderstate9) | Mandatory| AVRecorder state. | 4439| reason | [StateChangeReason](#statechangereason9) | Mandatory| Reason for the state change.| 4440 4441## AVRecorderConfig<sup>9+</sup> 4442 4443Describes the audio and video recording parameters. 4444 4445The **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**. 4446 4447**System capability**: SystemCapability.Multimedia.Media.AVRecorder 4448 4449| Name | Type | Mandatory| Description | 4450| --------------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | 4451| 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.| 4452| videoSourceType | [VideoSourceType](#videosourcetype9) | No | Type of the video source to record. This parameter is mandatory for video recording. | 4453| 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.| 4454| 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.| 4455|fileGenerationMode<sup>12+</sup> | [FileGenerationMode](#filegenerationmode12) | No | Mode for creating the file, which is used together with [on('photoAssetAvailable')](#onphotoassetavailable12).| 4456| 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. | 4457| 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.| 4458| metadata<sup>12+</sup> | [AVMetadata](#avmetadata11) | No | Metadata. For details, see [AVMetadata](#avmetadata11). | 4459 4460## AVRecorderProfile<sup>9+</sup> 4461 4462Describes the audio and video recording profile. 4463 4464**System capability**: SystemCapability.Multimedia.Media.AVRecorder 4465 4466| Name | Type | Mandatory| Description | 4467| ---------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | 4468| 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.| 4469| 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. | 4470| 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. | 4471| 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.| 4472| 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.| 4473| videoBitrate | number | No | Video encoding bit rate. This parameter is mandatory for video recording. The value range is [10000 - 100000000]. | 4474| videoCodec | [CodecMimeType](#codecmimetype8) | No | Video encoding format. This parameter is mandatory for video recording. Currently, VIDEO_AVC is supported.| 4475| videoFrameWidth | number | No | Width of a video frame. This parameter is mandatory for video recording. The value range is [176 - 4096]. | 4476| videoFrameHeight | number | No | Height of a video frame. This parameter is mandatory for video recording. The value range is [144 - 4096]. | 4477| videoFrameRate | number | No | Video frame rate. This parameter is mandatory for video recording. The value range is [1 - 60]. | 4478| 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**.| 4479| 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.| 4480 4481## AudioSourceType<sup>9+</sup> 4482 4483Enumerates the audio source types for video recording. 4484 4485**System capability**: SystemCapability.Multimedia.Media.AVRecorder 4486 4487| Name | Value | Description | 4488| ------------------------- | ---- | ---------------------- | 4489| AUDIO_SOURCE_TYPE_DEFAULT | 0 | Default audio input source.| 4490| 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.| 4491| AUDIO_SOURCE_TYPE_VOICE_RECOGNITION<sup>12+</sup> | 2 | Audio source in speech recognition scenarios.| 4492| AUDIO_SOURCE_TYPE_VOICE_COMMUNICATION<sup>12+</sup> | 7 | Voice communication source.| 4493| AUDIO_SOURCE_TYPE_VOICE_MESSAGE<sup>12+</sup> | 10 | Voice message source.| 4494| AUDIO_SOURCE_TYPE_CAMCORDER<sup>12+</sup> | 13 | Audio source in camera recording scenarios.| 4495 4496## VideoSourceType<sup>9+</sup> 4497 4498Enumerates the video source types for video recording. 4499 4500**System capability**: SystemCapability.Multimedia.Media.AVRecorder 4501 4502| Name | Value | Description | 4503| ----------------------------- | ---- | ------------------------------- | 4504| VIDEO_SOURCE_TYPE_SURFACE_YUV | 0 | The input surface carries raw data.| 4505| VIDEO_SOURCE_TYPE_SURFACE_ES | 1 | The input surface carries ES data. | 4506 4507## ContainerFormatType<sup>8+</sup> 4508 4509Enumerates the container format types (CFTs). 4510 4511**System capability**: SystemCapability.Multimedia.Media.Core 4512 4513| Name | Value | Description | 4514| ----------- | ----- | --------------------- | 4515| CFT_MPEG_4 | 'mp4' | Video container format MP4.| 4516| CFT_MPEG_4A | 'm4a' | Audio container format M4A.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 4517| CFT_MP3<sup>12+</sup> | 'mp3' | Audio container format MP3.| 4518| CFT_WAV<sup>12+</sup> | 'wav' | Audio container format WAV.| 4519 4520## Location 4521 4522Describes the geographical location of the recorded video. 4523 4524**System capability**: SystemCapability.Multimedia.Media.Core 4525 4526| Name | Type | Mandatory| Description | 4527| --------- | ------ | ---- | ---------------- | 4528| latitude | number | Yes | Latitude of the geographical location.| 4529| longitude | number | Yes | Longitude of the geographical location.| 4530 4531## EncoderInfo<sup>11+</sup> 4532 4533Describes the information about an encoder. 4534 4535**System capability**: SystemCapability.Multimedia.Media.AVRecorder 4536 4537| Name | Type | Readable| Writable| Description | 4538| ---------- | -------------------------------- | ---- | ---- | ------------------------------------------------------------ | 4539| mimeType | [CodecMimeType](#codecmimetype8) | Yes | No | MIME type of the encoder. | 4540| type | string | Yes | No | Encoder type. The value **audio** means an audio encoder, and **video** means a video encoder. | 4541| bitRate | [Range](#range11) | Yes | No | Bit rate range of the encoder, with the minimum and maximum bit rates specified. | 4542| 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. | 4543| width | [Range](#range11) | Yes | No | Video frame width range, with the minimum and maximum widths specified. This parameter is available only for video encoders. | 4544| height | [Range](#range11) | Yes | No | Video frame height range, with the minimum and maximum heights specified. This parameter is available only for video encoders. | 4545| 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. | 4546| sampleRate | Array\<number> | Yes | No | Audio sampling rate, including all available audio sampling rates. This parameter is available only for audio encoders.| 4547 4548## Range<sup>11+</sup> 4549 4550Describes a range. 4551 4552**System capability**: SystemCapability.Multimedia.Media.AVRecorder 4553 4554| Name| Type | Readable| Writable| Description | 4555| ---- | ------ | ---- | ---- | ------------ | 4556| min | number | Yes | No | Minimum value.| 4557| max | number | Yes | No | Maximum value.| 4558 4559## FileGenerationMode<sup>12+</sup> 4560 4561Enumerates the modes for creating media files. 4562 4563**System capability**: SystemCapability.Multimedia.Media.AVRecorder 4564 4565| Name | Value | Description | 4566| ----------------------------- | ---- | ------------------------------- | 4567| APP_CREATE | 0 | The application creates a media file in the sandbox.| 4568| 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.| 4569 4570## AVTranscoder<sup>12+</sup> 4571 4572A transcoding management class that provides APIs to transcode videos. Before calling any API in **AVTranscoder**, you must use **createAVTranscoder()** to create an **AVTranscoder** instance. 4573 4574For details about the AVTranscoder demo, see [Using AVTranscoder for Transcoding](../../media/media/using-avtranscoder-for-transcodering.md). 4575 4576### Attributes 4577 4578**System capability**: SystemCapability.Multimedia.Media.AVTranscoder 4579 4580| Name | Type | Read-Only| Optional| Description | 4581| ------- | ------------------------------------ | ---- | ---- | ------------------ | 4582| 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.| 4583| 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.| 4584 4585### prepare<sup>12+</sup> 4586 4587prepare(config: AVTranscoderConfig): Promise\<void> 4588 4589Sets video transcoding parameters. This API uses a promise to return the result. 4590 4591**System capability**: SystemCapability.Multimedia.Media.AVTranscoder 4592 4593**Parameters** 4594 4595| Name| Type | Mandatory| Description | 4596| ------ | -------------------------------------- | ---- | -------------------------- | 4597| config | [AVTranscoderConfig](#avtranscoderconfig12) | Yes | Video transcoding parameters to set.| 4598 4599**Return value** 4600 4601| Type | Description | 4602| -------------- | ------------------------------------------ | 4603| Promise\<void> | Promise that returns no value.| 4604 4605**Error codes** 4606 4607For details about the error codes, see [Media Error Codes](errorcode-media.md). 4608 4609| ID| Error Message | 4610| -------- | -------------------------------------- | 4611| 401 | The parameter check failed. Return by promise. | 4612| 5400102 | Operation not allowed. Return by promise. | 4613| 5400105 | Service died. Return by promise. | 4614| 5400106 | Unsupported format. Returned by promise. | 4615 4616**Example** 4617 4618```ts 4619import { BusinessError } from '@kit.BasicServicesKit'; 4620 4621// Configure the parameters based on those supported by the hardware device. 4622let avTranscoderConfig: media.AVTranscoderConfig = { 4623 audioBitrate : 200000, 4624 audioCodec : media.CodecMimeType.AUDIO_AAC, 4625 fileFormat : media.ContainerFormatType.CFT_MPEG_4, 4626 videoBitrate : 3000000, 4627 videoCodec : media.CodecMimeType.VIDEO_AVC, 4628 videoFrameWidth : 1280, 4629 videoFrameHeight : 720, 4630} 4631 4632avTranscoder.prepare(avTranscoderConfig).then(() => { 4633 console.info('prepare success'); 4634}).catch((err: BusinessError) => { 4635 console.error('prepare failed and catch error is ' + err.message); 4636}); 4637``` 4638 4639### start<sup>12+</sup> 4640 4641start(): Promise\<void> 4642 4643Starts transcoding. This API uses a promise to return the result. 4644 4645This API can be called only after the [prepare()](#prepare12) API is called. 4646 4647**System capability**: SystemCapability.Multimedia.Media.AVTranscoder 4648 4649**Return value** 4650 4651| Type | Description | 4652| -------------- | ------------------------------------- | 4653| Promise\<void> | Promise that returns no value.| 4654 4655**Error codes** 4656 4657For details about the error codes, see [Media Error Codes](errorcode-media.md). 4658 4659| ID| Error Message | 4660| -------- | -------------------------------------- | 4661| 5400102 | Operation not allowed. Return by promise. | 4662| 5400103 | IO error. Return by promise. | 4663| 5400105 | Service died. Return by promise. | 4664 4665**Example** 4666 4667```ts 4668import { BusinessError } from '@kit.BasicServicesKit'; 4669 4670avTranscoder.start().then(() => { 4671 console.info('start AVTranscoder success'); 4672}).catch((err: BusinessError) => { 4673 console.error('start AVTranscoder failed and catch error is ' + err.message); 4674}); 4675``` 4676 4677### pause<sup>12+</sup> 4678 4679pause(): Promise\<void> 4680 4681Pauses transcoding. This API uses a promise to return the result. 4682 4683This API can be called only after the [start()](#start12) API is called. You can call [resume()](#resume12) to resume transcoding. 4684 4685**System capability**: SystemCapability.Multimedia.Media.AVTranscoder 4686 4687**Return value** 4688 4689| Type | Description | 4690| -------------- | ------------------------------------- | 4691| Promise\<void> | Promise that returns no value.| 4692 4693**Error codes** 4694 4695For details about the error codes, see [Media Error Codes](errorcode-media.md). 4696 4697| ID| Error Message | 4698| -------- | -------------------------------------- | 4699| 5400102 | Operation not allowed. Return by promise. | 4700| 5400103 | IO error. Return by promise. | 4701| 5400105 | Service died. Return by promise. | 4702 4703**Example** 4704 4705```ts 4706import { BusinessError } from '@kit.BasicServicesKit'; 4707 4708avTranscoder.pause().then(() => { 4709 console.info('pause AVTranscoder success'); 4710}).catch((err: BusinessError) => { 4711 console.error('pause AVTranscoder failed and catch error is ' + err.message); 4712}); 4713``` 4714 4715### resume<sup>12+</sup> 4716 4717resume(): Promise\<void> 4718 4719Resumes transcoding. This API uses a promise to return the result. 4720 4721This API can be called only after the [pause()](#pause12) API is called. 4722 4723**System capability**: SystemCapability.Multimedia.Media.AVTranscoder 4724 4725**Return value** 4726 4727| Type | Description | 4728| -------------- | ------------------------------------- | 4729| Promise\<void> | Promise that returns no value.| 4730 4731**Error codes** 4732 4733For details about the error codes, see [Media Error Codes](errorcode-media.md). 4734 4735| ID| Error Message | 4736| -------- | -------------------------------------- | 4737| 5400102 | Operation not allowed. Return by promise. | 4738| 5400103 | IO error. Return by promise. | 4739| 5400105 | Service died. Return by promise. | 4740 4741**Example** 4742 4743```ts 4744import { BusinessError } from '@kit.BasicServicesKit'; 4745 4746avTranscoder.resume().then(() => { 4747 console.info('resume AVTranscoder success'); 4748}).catch((err: BusinessError) => { 4749 console.error('resume AVTranscoder failed and catch error is ' + err.message); 4750}); 4751``` 4752 4753### cancel<sup>12+</sup> 4754 4755cancel(): Promise\<void> 4756 4757Cancels transcoding. This API uses a promise to return the result. 4758 4759This API can be called only after the [prepare()](#prepare12), [start()](#start12), [pause()](#pause12), or [resume()](#resume12) API is called. 4760 4761**System capability**: SystemCapability.Multimedia.Media.AVTranscoder 4762 4763**Return value** 4764 4765| Type | Description | 4766| -------------- | ------------------------------------- | 4767| Promise\<void> | Promise that returns no value.| 4768 4769**Error codes** 4770 4771For details about the error codes, see [Media Error Codes](errorcode-media.md). 4772 4773| ID| Error Message | 4774| -------- | -------------------------------------- | 4775| 5400102 | Operation not allowed. Return by promise. | 4776| 5400103 | IO error. Return by promise. | 4777| 5400105 | Service died. Return by promise. | 4778 4779**Example** 4780 4781```ts 4782import { BusinessError } from '@kit.BasicServicesKit'; 4783 4784avTranscoder.cancel().then(() => { 4785 console.info('cancel AVTranscoder success'); 4786}).catch((err: BusinessError) => { 4787 console.error('cancel AVTranscoder failed and catch error is ' + err.message); 4788}); 4789``` 4790 4791### release<sup>12+</sup> 4792 4793release(): Promise\<void> 4794 4795Releases the video transcoding resources. This API uses a promise to return the result. 4796 4797After the resources are released, you can no longer perform any operation on the **AVTranscoder** instance. 4798 4799**System capability**: SystemCapability.Multimedia.Media.AVTranscoder 4800 4801**Return value** 4802 4803| Type | Description | 4804| -------------- | ------------------------------------------- | 4805| Promise\<void> | Promise that returns no value.| 4806 4807**Error codes** 4808 4809For details about the error codes, see [Media Error Codes](errorcode-media.md). 4810 4811| ID| Error Message | 4812| -------- | --------------------------------- | 4813| 5400102 | Operation not allowed. Return by promise. | 4814| 5400105 | Service died. Return by promise. | 4815 4816**Example** 4817 4818```ts 4819import { BusinessError } from '@kit.BasicServicesKit'; 4820 4821avTranscoder.release().then(() => { 4822 console.info('release AVTranscoder success'); 4823}).catch((err: BusinessError) => { 4824 console.error('release AVTranscoder failed and catch error is ' + err.message); 4825}); 4826``` 4827 4828### on('progressUpdate')<sup>12+</sup> 4829 4830on(type: 'progressUpdate', callback: Callback\<number>): void 4831 4832Subscribes 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. 4833 4834**System capability**: SystemCapability.Multimedia.Media.AVTranscoder 4835 4836**Parameters** 4837 4838| Name | Type | Mandatory| Description | 4839| -------- | -------- | ---- | ------------------------------------------------------------ | 4840| type | string | Yes | Event type, which is **'progressUpdate'** in this case. This event is triggered by the system during transcoding.| 4841| 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.| 4842 4843**Example** 4844 4845```ts 4846avTranscoder.on('progressUpdate', (progress: number) => { 4847 console.info('avTranscoder progressUpdate = ' + progress); 4848}); 4849``` 4850 4851### off('progressUpdate')<sup>12+</sup> 4852 4853off(type:'progressUpdate', callback?: Callback\<number>): void 4854 4855Unsubscribes from transcoding progress updates. 4856 4857**System capability**: SystemCapability.Multimedia.Media.AVTranscoder 4858 4859**Parameters** 4860 4861| Name| Type | Mandatory| Description | 4862| ------ | ------ | ---- | ------------------------------------------------------------ | 4863| type | string | Yes | Event type, which is **'progressUpdate'** in this case. This event can be triggered by both user operations and the system.| 4864| 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.| 4865 4866**Example** 4867 4868```ts 4869avTranscoder.off('progressUpdate'); 4870``` 4871 4872### on('error')<sup>12+</sup> 4873 4874on(type: 'error', callback: ErrorCallback): void 4875 4876Subscribes to AVTranscoder errors. If this event is reported, call [release()](#release12) to exit the transcoding. 4877 4878An application can subscribe to only one AVTranscoder error event. When the application initiates multiple subscriptions to this event, the last subscription prevails. 4879 4880**System capability**: SystemCapability.Multimedia.Media.AVTranscoder 4881 4882**Parameters** 4883 4884| Name | Type | Mandatory| Description | 4885| -------- | ------------- | ---- | ------------------------------------------------------------ | 4886| type | string | Yes | Event type, which is **'error'** in this case.<br>This event is triggered when an error occurs during recording.| 4887| callback | [ErrorCallback](../apis-basic-services-kit/js-apis-base.md#errorcallback) | Yes | Callback invoked when the event is triggered. | 4888 4889**Error codes** 4890 4891For details about the error codes, see [Media Error Codes](errorcode-media.md). 4892 4893| ID| Error Message | 4894| -------- | ------------------------------------------ | 4895| 401 | The parameter check failed. | 4896| 801 | Capability not supported. | 4897| 5400101 | No memory. | 4898| 5400102 | Operation not allowed. | 4899| 5400103 | I/O error. | 4900| 5400104 | Time out. | 4901| 5400105 | Service died. | 4902| 5400106 | Unsupported format. | 4903 4904**Example** 4905 4906```ts 4907import { BusinessError } from '@kit.BasicServicesKit'; 4908 4909avTranscoder.on('error', (err: BusinessError) => { 4910 console.info('case avTranscoder.on(error) called, errMessage is ' + err.message); 4911}); 4912``` 4913 4914### off('error')<sup>12+</sup> 4915 4916off(type:'error', callback?: ErrorCallback): void 4917 4918Unsubscribes from AVTranscoder errors. After the unsubscription, your application can no longer receive AVTranscoder errors. 4919 4920**System capability**: SystemCapability.Multimedia.Media.AVTranscoder 4921 4922**Parameters** 4923 4924| Name| Type | Mandatory| Description | 4925| ------ | ------ | ---- | ------------------------------------------------------------ | 4926| type | string | Yes | Event type, which is **'error'** in this case.<br>This event is triggered when an error occurs during transcoding.| 4927| callback | [ErrorCallback](../apis-basic-services-kit/js-apis-base.md#errorcallback) | No | Callback that has been registered to listen for AVTranscoder errors.| 4928 4929**Example** 4930 4931```ts 4932avTranscoder.off('error'); 4933``` 4934 4935### on('complete')<sup>12+</sup> 4936 4937on(type: 'complete', callback: Callback\<void>): void 4938 4939Subscribes 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. 4940 4941When this event is reported, the current transcoding operation is complete. You can call [release()](#release12) to exit the transcoding. 4942 4943**System capability**: SystemCapability.Multimedia.Media.AVTranscoder 4944 4945**Parameters** 4946 4947| Name | Type | Mandatory| Description | 4948| -------- | -------- | ---- | ------------------------------------------------------------ | 4949| type | string | Yes | Event type, which is **'complete'** in this case. This event is triggered by the system during transcoding.| 4950| callback | [Callback](../apis-basic-services-kit/js-apis-base.md#callback) | Yes | Callback that has been registered to listen for transcoding completion events.| 4951 4952**Example** 4953 4954```ts 4955avTranscoder.on('complete', () => { 4956 console.info('avTranscoder complete'); 4957}); 4958``` 4959 4960### off('complete')<sup>12+</sup> 4961 4962off(type:'complete', callback?: Callback\<void>): void 4963 4964Unsubscribes from the event indicating that transcoding is complete. 4965 4966**System capability**: SystemCapability.Multimedia.Media.AVTranscoder 4967 4968**Parameters** 4969 4970| Name| Type | Mandatory| Description | 4971| ------ | ------ | ---- | ------------------------------------------------------------ | 4972| type | string | Yes | Event type, which is **'complete'** in this case. This event can be triggered by both user operations and the system.| 4973| callback | [Callback](../apis-basic-services-kit/js-apis-base.md#callback) | No | Callback invoked when the event is triggered.| 4974 4975**Example** 4976 4977```ts 4978avTranscoder.off('complete'); 4979``` 4980 4981## AVTranscoderConfig<sup>12+</sup> 4982 4983Describes the video transcoding parameters. 4984 4985**System capability**: SystemCapability.Multimedia.Media.AVTranscoder 4986 4987| Name | Type | Read-Only| Optional| Description | 4988| --------------- | ---------------------------------------- |---- | ---- | ------------------------------------------------------------ | 4989| audioBitrate | number | No| Yes| Bit rate of the output audio, in bit/s. The default value is 48 kbit/s.| 4990| audioCodec | [CodecMimeType](#codecmimetype8) | No| Yes | Encoding format of the output audio. Currently, only AAC is supported. | 4991| fileFormat | [ContainerFormatType](#containerformattype8) | No| No | Container format of the output video file. Currently, only MP4 is supported.| 4992| 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.| 4993| videoCodec | [CodecMimeType](#codecmimetype8) | No| Yes | Encoding format of the output video. Currently, only AVC and HEVC are supported.| 4994| 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.| 4995| 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.| 4996 4997 4998 4999## AVMetadataExtractor<sup>11+</sup> 5000 5001Provides APIs to obtain metadata from media resources. Before calling any API of **AVMetadataExtractor**, you must use [createAVMetadataExtractor()](#mediacreateavmetadataextractor11) to create an **AVMetadataExtractor** instance. 5002 5003For details about the demo for obtaining audio or video metadata, see [Obtaining Audio/Video Metadata](../../media/media/avmetadataextractor.md). 5004 5005### Attributes 5006 5007**System capability**: SystemCapability.Multimedia.Media.AVMetadataExtractor 5008 5009| Name | Type | Readable| Writable| Description | 5010| --------------------------------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | 5011| 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.| 5012| 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.| 5013 5014### fetchMetadata<sup>11+</sup> 5015 5016fetchMetadata(callback: AsyncCallback\<AVMetadata>): void 5017 5018Obtains media metadata. This API uses an asynchronous callback to return the result. 5019 5020**System capability**: SystemCapability.Multimedia.Media.AVMetadataExtractor 5021 5022**Parameters** 5023 5024| Name | Type | Mandatory| Description | 5025| -------- | -------------------------------------------- | ---- | ----------------------------------- | 5026| callback | AsyncCallback\<[AVMetadata](#avmetadata11)> | Yes | Callback used to return the result, which is an **AVMetadata** instance.| 5027 5028**Error codes** 5029 5030For details about the error codes, see [Media Error Codes](errorcode-media.md). 5031 5032| ID| Error Message | 5033| -------- | ------------------------------------------ | 5034| 5400102 | Operation not allowed. Returned by callback. | 5035| 5400106 | Unsupported format. Returned by callback. | 5036 5037**Example** 5038 5039```ts 5040import { BusinessError } from '@kit.BasicServicesKit'; 5041 5042avMetadataExtractor.fetchMetadata((error: BusinessError, metadata: media.AVMetadata) => { 5043 if (error) { 5044 console.error(`Failed to fetch Metadata, err = ${JSON.stringify(error)}`); 5045 return; 5046 } 5047 console.info(`Succeeded in fetching Metadata, genre: ${metadata.genre}`); 5048}); 5049``` 5050 5051### fetchMetadata<sup>11+</sup> 5052 5053fetchMetadata(): Promise\<AVMetadata> 5054 5055Obtains media metadata. This API uses a promise to return the result. 5056 5057**System capability**: SystemCapability.Multimedia.Media.AVMetadataExtractor 5058 5059**Return value** 5060 5061| Type | Description | 5062| -------------- | ---------------------------------------- | 5063| Promise\<[AVMetadata](#avmetadata11)> | Promise used to return the result, which is an **AVMetadata** instance.| 5064 5065**Error codes** 5066 5067For details about the error codes, see [Media Error Codes](errorcode-media.md). 5068 5069| ID| Error Message | 5070| -------- | ----------------------------------------- | 5071| 5400102 | Operation not allowed. Returned by promise. | 5072| 5400106 | Unsupported format. Returned by promise. | 5073 5074**Example** 5075 5076```ts 5077import { BusinessError } from '@kit.BasicServicesKit'; 5078 5079avMetadataExtractor.fetchMetadata().then((metadata: media.AVMetadata) => { 5080 console.info(`Succeeded in fetching Metadata, genre: ${metadata.genre}`) 5081}).catch((error: BusinessError) => { 5082 console.error(`Failed to fetch Metadata, error message:${error.message}`); 5083}); 5084``` 5085 5086### fetchAlbumCover<sup>11+</sup> 5087 5088fetchAlbumCover(callback: AsyncCallback\<image.PixelMap>): void 5089 5090Obtains the cover of the audio album. This API uses an asynchronous callback to return the result. 5091 5092**System capability**: SystemCapability.Multimedia.Media.AVMetadataExtractor 5093 5094**Parameters** 5095 5096| Name | Type | Mandatory| Description | 5097| -------- | -------------------------------------------- | ---- | ----------------------------------- | 5098| callback | AsyncCallback\<[image.PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)> | Yes | Callback used to return the album cover.| 5099 5100**Error codes** 5101 5102For details about the error codes, see [Media Error Codes](errorcode-media.md). 5103 5104| ID| Error Message | 5105| -------- | ------------------------------------------ | 5106| 5400102 | Operation not allowed. Return by callback. | 5107| 5400106 | Unsupported format. Returned by callback. | 5108 5109**Example** 5110 5111```ts 5112import { BusinessError } from '@kit.BasicServicesKit'; 5113import { image } from '@kit.ImageKit'; 5114 5115let pixel_map : image.PixelMap | undefined = undefined; 5116 5117avMetadataExtractor.fetchAlbumCover((error: BusinessError, pixelMap: image.PixelMap) => { 5118 if (error) { 5119 console.error(`Failed to fetch AlbumCover, error = ${JSON.stringify(error)}`); 5120 return; 5121 } 5122 pixel_map = pixelMap; 5123}); 5124``` 5125 5126### fetchAlbumCover<sup>11+</sup> 5127 5128fetchAlbumCover(): Promise\<image.PixelMap> 5129 5130Obtains the cover of the audio album. This API uses a promise to return the result. 5131 5132**System capability**: SystemCapability.Multimedia.Media.AVMetadataExtractor 5133 5134**Return value** 5135 5136| Type | Description | 5137| -------------- | ---------------------------------------- | 5138| Promise\<[image.PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)> | Promise used to return the album cover.| 5139 5140**Error codes** 5141 5142For details about the error codes, see [Media Error Codes](errorcode-media.md). 5143 5144| ID| Error Message | 5145| -------- | ----------------------------------------- | 5146| 5400102 | Operation not allowed. Returned by promise. | 5147| 5400106 | Unsupported format. Returned by promise. | 5148 5149**Example** 5150 5151```ts 5152import { BusinessError } from '@kit.BasicServicesKit'; 5153import { image } from '@kit.ImageKit'; 5154 5155let pixel_map : image.PixelMap | undefined = undefined; 5156 5157avMetadataExtractor.fetchAlbumCover().then((pixelMap: image.PixelMap) => { 5158 pixel_map = pixelMap; 5159}).catch((error: BusinessError) => { 5160 console.error(`Failed to fetch AlbumCover, error message:${error.message}`); 5161}); 5162``` 5163 5164### release<sup>11+</sup> 5165 5166release(callback: AsyncCallback\<void>): void 5167 5168Releases this **AVMetadataExtractor** instance. This API uses an asynchronous callback to return the result. 5169 5170**System capability**: SystemCapability.Multimedia.Media.AVMetadataExtractor 5171 5172**Parameters** 5173 5174| Name | Type | Mandatory| Description | 5175| -------- | -------------------------------------------- | ---- | ----------------------------------- | 5176| callback | AsyncCallback\<void> | Yes |Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 5177 5178**Error codes** 5179 5180For details about the error codes, see [Media Error Codes](errorcode-media.md). 5181 5182| ID| Error Message | 5183| -------- | ------------------------------------------ | 5184| 5400102 | Operation not allowed. Returned by callback. | 5185 5186**Example** 5187 5188```ts 5189import { BusinessError } from '@kit.BasicServicesKit'; 5190 5191avMetadataExtractor.release((error: BusinessError) => { 5192 if (error) { 5193 console.error(`Failed to release, err = ${JSON.stringify(error)}`); 5194 return; 5195 } 5196 console.info(`Succeeded in releasing.`); 5197}); 5198``` 5199 5200### release<sup>11+</sup> 5201 5202release(): Promise\<void> 5203 5204Releases this **AVMetadataExtractor** instance. This API uses a promise to return the result. 5205 5206**System capability**: SystemCapability.Multimedia.Media.AVMetadataExtractor 5207 5208**Return value** 5209 5210| Type | Description | 5211| -------------- | ---------------------------------------- | 5212| Promise\<void> | Promise that returns no value.| 5213 5214**Error codes** 5215 5216For details about the error codes, see [Media Error Codes](errorcode-media.md). 5217 5218| ID| Error Message | 5219| -------- | ----------------------------------------- | 5220| 5400102 | Operation not allowed. Returned by promise. | 5221 5222**Example** 5223 5224```ts 5225import { BusinessError } from '@kit.BasicServicesKit'; 5226 5227avMetadataExtractor.release().then(() => { 5228 console.info(`Succeeded in releasing.`); 5229}).catch((error: BusinessError) => { 5230 console.error(`Failed to release, error message:${error.message}`); 5231}); 5232``` 5233 5234## AVMetadata<sup>11+</sup> 5235 5236Defines 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). 5237 5238**System capability**: SystemCapability.Multimedia.Media.AVMetadataExtractor 5239 5240| Name | Type | Mandatory| Description | 5241| ------ | ------ | ---- | ------------------------------------------------------------ | 5242| album | string | No | Title of the album. This parameter is read-only in the current version. | 5243| albumArtist | string | No | Artist of the album. This parameter is read-only in the current version.| 5244| artist | string | No | Artist of the media asset. This parameter is read-only in the current version.| 5245| author | string | No | Author of the media asset. This parameter is read-only in the current version.| 5246| dateTime | string | No | Time when the media asset is created. This parameter is read-only in the current version.| 5247| 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.| 5248| composer | string | No | Composer of the media asset. This parameter is read-only in the current version.| 5249| duration | string | No | Duration of the media asset. This parameter is read-only in the current version.| 5250| genre | string | No | Type or genre of the media asset.| 5251| hasAudio | string | No | Whether the media asset contains audio. This parameter is read-only in the current version.| 5252| hasVideo | string | No | Whether the media asset contains a video. This parameter is read-only in the current version.| 5253| mimeType | string | No | MIME type of the media asset. This parameter is read-only in the current version.| 5254| trackCount | string | No | Number of tracks of the media asset. This parameter is read-only in the current version.| 5255| sampleRate | string | No | Audio sampling rate, in Hz. This parameter is read-only in the current version.| 5256| 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.| 5257| videoHeight | string | No | Video height, in px. This parameter is read-only in the current version.| 5258| videoWidth | string | No | Video width, in px. This parameter is read-only in the current version.| 5259| videoOrientation | string | No | Video rotation direction, in degrees.| 5260| hdrType<sup>12+</sup> | [HdrType](#hdrtype12) | No | HDR type of the media asset. This parameter is read-only in the current version.| 5261| location<sup>12+</sup> | [Location](#location) | No| Geographical location of the media asset.| 5262| customInfo<sup>12+</sup> | Record<string, string> | No| Custom key-value mappings obtained from **moov.meta.list**.| 5263 5264## HdrType<sup>12+</sup> 5265 5266Enumerates the HDR types. 5267 5268**System capability**: SystemCapability.Multimedia.Media.Core 5269 5270| Name | Value | Description | 5271| ------------------------- | ---- | ---------------------- | 5272| AV_HDR_TYPE_NONE | 0 | No HDR.| 5273| AV_HDR_TYPE_VIVID | 1 | HDR VIVID.| 5274 5275## media.createAudioPlayer<sup>(deprecated)</sup> 5276 5277createAudioPlayer(): AudioPlayer 5278 5279Creates an **AudioPlayer** instance in synchronous mode. 5280 5281> **NOTE** 5282> 5283> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [createAVPlayer](#mediacreateavplayer9) instead. 5284 5285**System capability**: SystemCapability.Multimedia.Media.AudioPlayer 5286 5287**Return value** 5288 5289| Type | Description | 5290| --------------------------- | ------------------------------------------------------------ | 5291| [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.| 5292 5293**Example** 5294 5295```ts 5296let audioPlayer: media.AudioPlayer = media.createAudioPlayer(); 5297``` 5298 5299## media.createVideoPlayer<sup>(deprecated)</sup> 5300 5301createVideoPlayer(callback: AsyncCallback\<VideoPlayer>): void 5302 5303Creates a **VideoPlayer** instance. This API uses an asynchronous callback to return the result. 5304 5305> **NOTE** 5306> 5307> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [createAVPlayer](#mediacreateavplayer9) instead. 5308 5309**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 5310 5311**Parameters** 5312 5313| Name | Type | Mandatory| Description | 5314| -------- | ------------------------------------------ | ---- | ------------------------------------------------------------ | 5315| 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.| 5316 5317**Example** 5318 5319```ts 5320import { BusinessError } from '@kit.BasicServicesKit'; 5321 5322let videoPlayer: media.VideoPlayer; 5323media.createVideoPlayer((error: BusinessError, video: media.VideoPlayer) => { 5324 if (video != null) { 5325 videoPlayer = video; 5326 console.info('Succeeded in creating VideoPlayer'); 5327 } else { 5328 console.error(`Failed to create VideoPlayer, error:${error}`); 5329 } 5330}); 5331``` 5332 5333## media.createVideoPlayer<sup>(deprecated)</sup> 5334 5335createVideoPlayer(): Promise\<VideoPlayer> 5336 5337Creates a **VideoPlayer** instance. This API uses a promise to return the result. 5338 5339> **NOTE** 5340> 5341> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [createAVPlayer](#mediacreateavplayer9-1) instead. 5342 5343**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 5344 5345**Return value** 5346 5347| Type | Description | 5348| ------------------------------------ | ------------------------------------------------------------ | 5349| 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.| 5350 5351**Example** 5352 5353```ts 5354import { BusinessError } from '@kit.BasicServicesKit'; 5355 5356let videoPlayer: media.VideoPlayer; 5357media.createVideoPlayer().then((video: media.VideoPlayer) => { 5358 if (video != null) { 5359 videoPlayer = video; 5360 console.info('Succeeded in creating VideoPlayer'); 5361 } else { 5362 console.error('Failed to create VideoPlayer'); 5363 } 5364}).catch((error: BusinessError) => { 5365 console.error(`Failed to create VideoPlayer, error:${error}`); 5366}); 5367``` 5368 5369## media.createAudioRecorder<sup>(deprecated)</sup> 5370 5371createAudioRecorder(): AudioRecorder 5372 5373Creates an **AudioRecorder** instance to control audio recording. 5374Only one **AudioRecorder** instance can be created per device. 5375 5376> **NOTE** 5377> 5378> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [createAVRecorder](#mediacreateavrecorder9) instead. 5379 5380**System capability**: SystemCapability.Multimedia.Media.AudioRecorder 5381 5382**Return value** 5383 5384| Type | Description | 5385| ------------------------------- | ------------------------------------------------------------ | 5386| [AudioRecorder](#audiorecorderdeprecated) | If the operation is successful, an **AudioRecorder** instance is returned; otherwise, **null** is returned. The instance can be used to record audio.| 5387 5388**Example** 5389 5390```ts 5391let audioRecorder: media.AudioRecorder = media.createAudioRecorder(); 5392``` 5393 5394## MediaErrorCode<sup>(deprecated)</sup> 5395 5396Enumerates the media error codes. 5397 5398> **NOTE** 5399> 5400> This enum is supported since API version 8 and deprecated since API version 11. You are advised to use [Media Error Codes](#averrorcode9) instead. 5401 5402**System capability**: SystemCapability.Multimedia.Media.Core 5403 5404| Name | Value | Description | 5405| -------------------------- | ---- | -------------------------------------- | 5406| MSERR_OK | 0 | The operation is successful. | 5407| MSERR_NO_MEMORY | 1 | Failed to allocate memory. The system may have no available memory.| 5408| MSERR_OPERATION_NOT_PERMIT | 2 | No permission to perform the operation. | 5409| MSERR_INVALID_VAL | 3 | Invalid input parameter. | 5410| MSERR_IO | 4 | An I/O error occurs. | 5411| MSERR_TIMEOUT | 5 | The operation times out. | 5412| MSERR_UNKNOWN | 6 | An unknown error occurs. | 5413| MSERR_SERVICE_DIED | 7 | Invalid server. | 5414| MSERR_INVALID_STATE | 8 | The operation is not allowed in the current state. | 5415| MSERR_UNSUPPORTED | 9 | The operation is not supported in the current version. | 5416 5417## AudioPlayer<sup>(deprecated)</sup> 5418 5419> **NOTE** 5420> 5421> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayer](#avplayer9) instead. 5422 5423Provides APIs to manage and play audio. Before calling any API in **AudioPlayer**, you must use [createAudioPlayer()](#mediacreateaudioplayerdeprecated) to create an **AudioPlayer** instance. 5424 5425### Attributes<sup>(deprecated)</sup> 5426 5427**System capability**: SystemCapability.Multimedia.Media.AudioPlayer 5428 5429| Name | Type | Read-Only| Optional| Description | 5430| ------------------------------- | ------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | 5431| 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| 5432| 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>| 5433| loop | boolean | No | No | Whether to loop audio playback. The value **true** means to loop audio playback, and **false** means the opposite. | 5434| audioInterruptMode<sup>9+</sup> | [audio.InterruptMode](../apis-audio-kit/js-apis-audio.md#interruptmode9) | Yes | Yes | Audio interruption mode. | 5435| currentTime | number | Yes | No | Current audio playback position, in ms. | 5436| duration | number | Yes | No | Audio duration, in ms. | 5437| 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()**.| 5438 5439### play<sup>(deprecated)</sup> 5440 5441play(): void 5442 5443Starts to play an audio asset. This API can be called only after the **'dataLoad'** event is triggered. 5444 5445> **NOTE** 5446> 5447> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayer.play](#play9) instead. 5448 5449**System capability**: SystemCapability.Multimedia.Media.AudioPlayer 5450 5451**Example** 5452 5453```ts 5454audioPlayer.on('play', () => { // Set the 'play' event callback. 5455 console.info('audio play called'); 5456}); 5457audioPlayer.play(); 5458``` 5459 5460### pause<sup>(deprecated)</sup> 5461 5462pause(): void 5463 5464Pauses audio playback. 5465 5466> **NOTE** 5467> 5468> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayer.pause](#pause9) instead. 5469 5470**System capability**: SystemCapability.Multimedia.Media.AudioPlayer 5471 5472**Example** 5473 5474```ts 5475audioPlayer.on('pause', () => { // Set the 'pause' event callback. 5476 console.info('audio pause called'); 5477}); 5478audioPlayer.pause(); 5479``` 5480 5481### stop<sup>(deprecated)</sup> 5482 5483stop(): void 5484 5485Stops audio playback. 5486 5487> **NOTE** 5488> 5489> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayer.stop](#stop9) instead. 5490 5491**System capability**: SystemCapability.Multimedia.Media.AudioPlayer 5492 5493**Example** 5494 5495```ts 5496audioPlayer.on('stop', () => { // Set the 'stop' event callback. 5497 console.info('audio stop called'); 5498}); 5499audioPlayer.stop(); 5500``` 5501 5502### reset<sup>(deprecated)</sup> 5503 5504reset(): void 5505 5506Resets the audio asset to be played. 5507 5508> **NOTE** 5509> 5510> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [AVPlayer.reset](#reset9) instead. 5511 5512**System capability**: SystemCapability.Multimedia.Media.AudioPlayer 5513 5514**Example** 5515 5516```ts 5517audioPlayer.on('reset', () => { // Set the 'reset' event callback. 5518 console.info('audio reset called'); 5519}); 5520audioPlayer.reset(); 5521``` 5522 5523### seek<sup>(deprecated)</sup> 5524 5525seek(timeMs: number): void 5526 5527Seeks to the specified playback position. 5528 5529> **NOTE** 5530> 5531> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayer.seek](#seek9) instead. 5532 5533**System capability**: SystemCapability.Multimedia.Media.AudioPlayer 5534 5535**Parameters** 5536 5537| Name| Type | Mandatory| Description | 5538| ------ | ------ | ---- | ----------------------------------------------------------- | 5539| timeMs | number | Yes | Position to seek to, in ms. The value range is [0, duration].| 5540 5541**Example** 5542 5543```ts 5544audioPlayer.on('timeUpdate', (seekDoneTime: number) => { // Set the 'timeUpdate' event callback. 5545 if (seekDoneTime == null) { 5546 console.error('Failed to seek'); 5547 return; 5548 } 5549 console.info('Succeeded in seek. seekDoneTime: ' + seekDoneTime); 5550}); 5551audioPlayer.seek(30000); // Seek to 30000 ms. 5552``` 5553 5554### setVolume<sup>(deprecated)</sup> 5555 5556setVolume(vol: number): void 5557 5558Sets the volume. 5559 5560> **NOTE** 5561> 5562> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayer.setVolume](#setvolume9) instead. 5563 5564**System capability**: SystemCapability.Multimedia.Media.AudioPlayer 5565 5566**Parameters** 5567 5568| Name| Type | Mandatory| Description | 5569| ------ | ------ | ---- | ------------------------------------------------------------ | 5570| vol | number | Yes | Relative volume. The value ranges from 0.00 to 1.00. The value **1.00** indicates the maximum volume (100%).| 5571 5572**Example** 5573 5574```ts 5575audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback. 5576 console.info('audio volumeChange called'); 5577}); 5578audioPlayer.setVolume(1); // Set the volume to 100%. 5579``` 5580 5581### release<sup>(deprecated)</sup> 5582 5583release(): void 5584 5585Releases the audio playback resources. 5586 5587> **NOTE** 5588> 5589> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayer.release](#release9) instead. 5590 5591**System capability**: SystemCapability.Multimedia.Media.AudioPlayer 5592 5593**Example** 5594 5595```ts 5596audioPlayer.release(); 5597audioPlayer = undefined; 5598``` 5599 5600### getTrackDescription<sup>(deprecated)</sup> 5601 5602getTrackDescription(callback: AsyncCallback\<Array\<MediaDescription>>): void 5603 5604Obtains 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. 5605 5606> **NOTE** 5607> 5608> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.getTrackDescription](#gettrackdescription9) instead. 5609 5610**System capability**: SystemCapability.Multimedia.Media.AudioPlayer 5611 5612**Parameters** 5613 5614| Name | Type | Mandatory| Description | 5615| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------ | 5616| 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.| 5617 5618**Example** 5619 5620```ts 5621import { BusinessError } from '@kit.BasicServicesKit'; 5622 5623audioPlayer.getTrackDescription((error: BusinessError, arrList: Array<media.MediaDescription>) => { 5624 if (arrList != null) { 5625 console.info('Succeeded in getting TrackDescription'); 5626 } else { 5627 console.error(`Failed to get TrackDescription, error:${error}`); 5628 } 5629}); 5630``` 5631 5632### getTrackDescription<sup>(deprecated)</sup> 5633 5634getTrackDescription(): Promise\<Array\<MediaDescription>> 5635 5636Obtains the audio track information. It can be called only after the **'dataLoad'** event is triggered. This API uses a promise to return the result. 5637 5638> **NOTE** 5639> 5640> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.getTrackDescription](#gettrackdescription9-1) instead. 5641 5642**System capability**: SystemCapability.Multimedia.Media.AudioPlayer 5643 5644**Return value** 5645 5646| Type | Description | 5647| ------------------------------------------------------ | ----------------------------------------------- | 5648| Promise<Array<[MediaDescription](#mediadescription8)>> | Promise used to return a **MediaDescription** array, which records the audio track information.| 5649 5650**Example** 5651 5652```ts 5653import { BusinessError } from '@kit.BasicServicesKit'; 5654 5655audioPlayer.getTrackDescription().then((arrList: Array<media.MediaDescription>) => { 5656 console.info('Succeeded in getting TrackDescription'); 5657}).catch((error: BusinessError) => { 5658 console.error(`Failed to get TrackDescription, error:${error}`); 5659}); 5660``` 5661 5662### on('bufferingUpdate')<sup>(deprecated)</sup> 5663 5664on(type: 'bufferingUpdate', callback: (infoType: BufferingInfoType, value: number) => void): void 5665 5666Subscribes to the audio buffering update event. This API works only under online playback. 5667 5668> **NOTE** 5669> 5670> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.on('bufferingUpdate')](#onbufferingupdate9) instead. 5671 5672**System capability**: SystemCapability.Multimedia.Media.AudioPlayer 5673 5674**Parameters** 5675 5676| Name | Type | Mandatory| Description | 5677| -------- | -------- | ---- | ------------------------------------------------------------ | 5678| type | string | Yes | Event type, which is **'bufferingUpdate'** in this case. | 5679| callback | function | Yes | Callback invoked when the event is triggered.<br>The value of [BufferingInfoType](#bufferinginfotype8) is fixed at **0**.| 5680 5681**Example** 5682 5683```ts 5684audioPlayer.on('bufferingUpdate', (infoType: media.BufferingInfoType, value: number) => { 5685 console.info('audio bufferingInfo type: ' + infoType); 5686 console.info('audio bufferingInfo value: ' + value); 5687}); 5688``` 5689 5690### on('play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange')<sup>(deprecated)</sup> 5691 5692on(type: 'play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange', callback: () => void): void 5693 5694Subscribes to the audio playback events. 5695 5696> **NOTE** 5697> 5698> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayer.on('stateChange')](#onstatechange9) instead. 5699 5700**System capability**: SystemCapability.Multimedia.Media.AudioPlayer 5701 5702**Parameters** 5703 5704| Name | Type | Mandatory| Description | 5705| -------- | ---------- | ---- | ------------------------------------------------------------ | 5706| 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.| 5707| callback | () => void | Yes | Callback invoked when the event is triggered. | 5708 5709**Example** 5710 5711```ts 5712import { fileIo as fs } from '@kit.CoreFileKit'; 5713import { BusinessError } from '@kit.BasicServicesKit'; 5714 5715let audioPlayer: media.AudioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. 5716audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. 5717 console.info('audio set source called'); 5718 audioPlayer.play(); // Start the playback and trigger the 'play' event callback. 5719}); 5720audioPlayer.on('play', () => { // Set the 'play' event callback. 5721 console.info('audio play called'); 5722 audioPlayer.seek(30000); // Call the seek() API and trigger the 'timeUpdate' event callback. 5723}); 5724audioPlayer.on('pause', () => { // Set the 'pause' event callback. 5725 console.info('audio pause called'); 5726 audioPlayer.stop(); // Stop the playback and trigger the 'stop' event callback. 5727}); 5728audioPlayer.on('reset', () => { // Set the 'reset' event callback. 5729 console.info('audio reset called'); 5730 audioPlayer.release(); // Release the AudioPlayer instance. 5731 audioPlayer = undefined; 5732}); 5733audioPlayer.on('timeUpdate', (seekDoneTime: number) => { // Set the 'timeUpdate' event callback. 5734 if (seekDoneTime == null) { 5735 console.error('Failed to seek'); 5736 return; 5737 } 5738 console.info('Succeeded in seek, and seek time is ' + seekDoneTime); 5739 audioPlayer.setVolume(0.5); // Set the volume to 50% and trigger the 'volumeChange' event callback. 5740}); 5741audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback. 5742 console.info('audio volumeChange called'); 5743 audioPlayer.pause(); // Pause the playback and trigger the 'pause' event callback. 5744}); 5745audioPlayer.on('finish', () => { // Set the 'finish' event callback. 5746 console.info('audio play finish'); 5747 audioPlayer.stop(); // Stop the playback and trigger the 'stop' event callback. 5748}); 5749audioPlayer.on('error', (error: BusinessError) => { // Set the 'error' event callback. 5750 console.error(`audio error called, error: ${error}`); 5751}); 5752 5753// Set the FD (local playback) of the audio file selected by the user. 5754let fdPath = 'fd://'; 5755// 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. 5756let path = '/data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3'; 5757fs.open(path).then((file) => { 5758 fdPath = fdPath + '' + file.fd; 5759 console.info('Succeeded in opening fd, fd is' + fdPath); 5760 audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback. 5761}, (err: BusinessError) => { 5762 console.error('Failed to open fd, err is' + err); 5763}).catch((err: BusinessError) => { 5764 console.error('Failed to open fd, err is' + err); 5765}); 5766``` 5767 5768### on('timeUpdate')<sup>(deprecated)</sup> 5769 5770on(type: 'timeUpdate', callback: Callback\<number>): void 5771 5772Subscribes to the **'timeUpdate'** event. This event is reported every second when the audio playback is in progress. 5773 5774> **NOTE** 5775> 5776> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayer.on('timeUpdate')](#ontimeupdate9) instead. 5777 5778**System capability**: SystemCapability.Multimedia.Media.AudioPlayer 5779 5780**Parameters** 5781 5782| Name | Type | Mandatory| Description | 5783| -------- | ----------------- | ---- | ------------------------------------------------------------ | 5784| 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.| 5785| callback | Callback\<number> | Yes | Callback invoked when the event is triggered. The input parameter is the updated timestamp. | 5786 5787**Example** 5788 5789```ts 5790audioPlayer.on('timeUpdate', (newTime: number) => { // Set the 'timeUpdate' event callback. 5791 if (newTime == null) { 5792 console.error('Failed to do timeUpadate'); 5793 return; 5794 } 5795 console.info('Succeeded in doing timeUpadate. seekDoneTime: ' + newTime); 5796}); 5797audioPlayer.play(); // The 'timeUpdate' event is triggered when the playback starts. 5798``` 5799 5800### on('audioInterrupt')<sup>(deprecated)</sup> 5801 5802on(type: 'audioInterrupt', callback: (info: audio.InterruptEvent) => void): void 5803 5804Subscribes to the audio interruption event. For details, see [audio.InterruptEvent](../apis-audio-kit/js-apis-audio.md#interruptevent9). 5805 5806> **NOTE** 5807> 5808> This API is supported in API version 9 and deprecated since API version 9. You are advised to use [AVPlayer.on('audioInterrupt')](#onaudiointerrupt9) instead. 5809 5810**System capability**: SystemCapability.Multimedia.Media.AudioPlayer 5811 5812**Parameters** 5813 5814| Name | Type | Mandatory| Description | 5815| -------- | ------------------------------------------------------------ | ---- | -------------------------------------------------------- | 5816| type | string | Yes | Event type, which is **'audioInterrupt'** in this case.| 5817| callback | function | Yes | Callback invoked when the event is triggered. | 5818 5819**Example** 5820 5821```ts 5822import { audio } from '@kit.AudioKit'; 5823 5824audioPlayer.on('audioInterrupt', (info: audio.InterruptEvent) => { 5825 console.info('audioInterrupt called,and InterruptEvent info is:' + info) 5826}) 5827``` 5828 5829### on('error')<sup>(deprecated)</sup> 5830 5831on(type: 'error', callback: ErrorCallback): void 5832 5833Subscribes to audio playback error events. After an error event is reported, you must handle the event and exit the playback. 5834 5835> **NOTE** 5836> 5837> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayer.on('error')](#onerror9) instead. 5838 5839**System capability**: SystemCapability.Multimedia.Media.AudioPlayer 5840 5841**Parameters** 5842 5843| Name | Type | Mandatory| Description | 5844| -------- | ------------- | ---- | ------------------------------------------------------------ | 5845| type | string | Yes | Event type, which is **'error'** in this case.<br>This event is triggered when an error occurs during audio playback.| 5846| callback | [ErrorCallback](../apis-basic-services-kit/js-apis-base.md#errorcallback) | Yes | Callback invoked when the event is triggered. | 5847 5848**Example** 5849 5850```ts 5851import { BusinessError } from '@kit.BasicServicesKit'; 5852 5853audioPlayer.on('error', (error: BusinessError) => { // Set the 'error' event callback. 5854 console.error(`audio error called, error: ${error}`); 5855}); 5856audioPlayer.setVolume(3); // Set volume to an invalid value to trigger the 'error' event. 5857``` 5858 5859## AudioState<sup>(deprecated)</sup> 5860 5861type AudioState = 'idle' | 'playing' | 'paused' | 'stopped' | 'error' 5862 5863Enumerates the audio playback states. You can obtain the state through the **state** attribute. 5864 5865> **NOTE** 5866> 5867> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayerState](#avplayerstate9) instead. 5868 5869**System capability**: SystemCapability.Multimedia.Media.AudioPlayer 5870 5871| Type | Description | 5872| ------- | ---------------------------------------------- | 5873| 'idle' | No audio playback is in progress. The audio player is in this state after the **'dataload'** or **'reset'** event is triggered.| 5874| 'playing' | Audio playback is in progress. The audio player is in this state after the **'play'** event is triggered. | 5875| 'paused' | Audio playback is paused. The audio player is in this state after the **'pause'** event is triggered. | 5876| 'stopped' | Audio playback is stopped. The audio player is in this state after the **'stop'** event is triggered. | 5877| 'error' | Audio playback is in the error state. | 5878 5879## VideoPlayer<sup>(deprecated)</sup> 5880 5881> **NOTE** 5882> 5883> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer](#avplayer9) instead. 5884 5885Provides APIs to manage and play video. Before calling any API of **VideoPlayer**, you must use [createVideoPlayer()](#mediacreatevideoplayerdeprecated) to create a **VideoPlayer** instance. 5886 5887### Attributes 5888 5889**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 5890 5891| Name | Type | Read-Only| Optional| Description | 5892| ------------------------------- | ------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | 5893| 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.| 5894| 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>| 5895| 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. | 5896| videoScaleType<sup>9+</sup> | [VideoScaleType](#videoscaletype9) | No | Yes | Video scale type. The default value is **VIDEO_SCALE_TYPE_FIT**. | 5897| audioInterruptMode<sup>9+</sup> | [audio.InterruptMode](../apis-audio-kit/js-apis-audio.md#interruptmode9) | No | Yes | Audio interruption mode. | 5898| currentTime<sup>8+</sup> | number | Yes | No | Current video playback position, in ms. | 5899| duration<sup>8+</sup> | number | Yes | No | Video duration, in ms. The value **-1** indicates the live mode. | 5900| state<sup>8+</sup> | [VideoPlayState](#videoplaystatedeprecated) | Yes | No | Video playback state. | 5901| width<sup>8+</sup> | number | Yes | No | Video width, in px. | 5902| height<sup>8+</sup> | number | Yes | No | Video height, in px. | 5903 5904### setDisplaySurface<sup>(deprecated)</sup> 5905 5906setDisplaySurface(surfaceId: string, callback: AsyncCallback\<void>): void 5907 5908Sets a surface ID. This API uses an asynchronous callback to return the result. 5909 5910*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. 5911 5912> **NOTE** 5913> 5914> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.surfaceId](#attributes) instead. 5915 5916**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 5917 5918**Parameters** 5919 5920| Name | Type | Mandatory| Description | 5921| --------- | -------------------- | ---- | ------------------------- | 5922| surfaceId | string | Yes | Surface ID to set. | 5923| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the setting is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 5924 5925**Example** 5926 5927```ts 5928import { BusinessError } from '@kit.BasicServicesKit'; 5929 5930let surfaceId: string = ''; 5931videoPlayer.setDisplaySurface(surfaceId, (err: BusinessError) => { 5932 if (err) { 5933 console.error('Failed to set DisplaySurface!'); 5934 } else { 5935 console.info('Succeeded in setting DisplaySurface!'); 5936 } 5937}); 5938``` 5939 5940### setDisplaySurface<sup>(deprecated)</sup> 5941 5942setDisplaySurface(surfaceId: string): Promise\<void> 5943 5944Sets a surface ID. This API uses a promise to return the result. 5945 5946*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. 5947 5948> **NOTE** 5949> 5950> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.surfaceId](#attributes) instead. 5951 5952**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 5953 5954**Parameters** 5955 5956| Name | Type | Mandatory| Description | 5957| --------- | ------ | ---- | --------- | 5958| surfaceId | string | Yes | Surface ID to set.| 5959 5960**Return value** 5961 5962| Type | Description | 5963| -------------- | ------------------------------ | 5964| Promise\<void> | Promise that returns no value.| 5965 5966**Example** 5967 5968```ts 5969import { BusinessError } from '@kit.BasicServicesKit'; 5970 5971let surfaceId: string = ''; 5972videoPlayer.setDisplaySurface(surfaceId).then(() => { 5973 console.info('Succeeded in setting DisplaySurface'); 5974}).catch((error: BusinessError) => { 5975 console.error(`video catchCallback, error:${error}`); 5976}); 5977``` 5978 5979### prepare<sup>(deprecated)</sup> 5980 5981prepare(callback: AsyncCallback\<void>): void 5982 5983Prepares for video playback. This API uses an asynchronous callback to return the result. 5984 5985> **NOTE** 5986> 5987> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.prepare](#prepare9) instead. 5988 5989**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 5990 5991**Parameters** 5992 5993| Name | Type | Mandatory| Description | 5994| -------- | -------------------- | ---- | ------------------------ | 5995| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 5996 5997**Example** 5998 5999```ts 6000import { BusinessError } from '@kit.BasicServicesKit'; 6001 6002videoPlayer.prepare((err: BusinessError) => { 6003 if (err) { 6004 console.error('Failed to prepare!'); 6005 } else { 6006 console.info('Succeeded in preparing!'); 6007 } 6008}); 6009``` 6010 6011### prepare<sup>(deprecated)</sup> 6012 6013prepare(): Promise\<void> 6014 6015Prepares for video playback. This API uses a promise to return the result. 6016 6017> **NOTE** 6018> 6019> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.prepare](#prepare9-1) instead. 6020 6021**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6022 6023**Return value** 6024 6025| Type | Description | 6026| -------------- | ----------------------------- | 6027| Promise\<void> | Promise that returns no value.| 6028 6029**Example** 6030 6031```ts 6032import { BusinessError } from '@kit.BasicServicesKit'; 6033 6034videoPlayer.prepare().then(() => { 6035 console.info('Succeeded in preparing'); 6036}).catch((error: BusinessError) => { 6037 console.error(`video catchCallback, error:${error}`); 6038}); 6039``` 6040 6041### play<sup>(deprecated)</sup> 6042 6043play(callback: AsyncCallback\<void>): void 6044 6045Starts video playback. This API uses an asynchronous callback to return the result. 6046 6047> **NOTE** 6048> 6049> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.play](#play9) instead. 6050 6051**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6052 6053**Parameters** 6054 6055| Name | Type | Mandatory| Description | 6056| -------- | -------------------- | ---- | ------------------------ | 6057| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 6058 6059**Example** 6060 6061```ts 6062import { BusinessError } from '@kit.BasicServicesKit'; 6063 6064videoPlayer.play((err: BusinessError) => { 6065 if (err) { 6066 console.error('Failed to play!'); 6067 } else { 6068 console.info('Succeeded in playing!'); 6069 } 6070}); 6071``` 6072 6073### play<sup>(deprecated)</sup> 6074 6075play(): Promise\<void> 6076 6077Starts video playback. This API uses a promise to return the result. 6078 6079> **NOTE** 6080> 6081> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.play](#play9-1) instead. 6082 6083**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6084 6085**Return value** 6086 6087| Type | Description | 6088| -------------- | ----------------------------- | 6089| Promise\<void> | Promise that returns no value.| 6090 6091**Example** 6092 6093```ts 6094import { BusinessError } from '@kit.BasicServicesKit'; 6095 6096videoPlayer.play().then(() => { 6097 console.info('Succeeded in playing'); 6098}).catch((error: BusinessError) => { 6099 console.error(`video catchCallback, error:${error}`); 6100}); 6101``` 6102 6103### pause<sup>(deprecated)</sup> 6104 6105pause(callback: AsyncCallback\<void>): void 6106 6107Pauses video playback. This API uses an asynchronous callback to return the result. 6108 6109> **NOTE** 6110> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.pause](#pause9) instead. 6111 6112**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6113 6114**Parameters** 6115 6116| Name | Type | Mandatory| Description | 6117| -------- | -------------------- | ---- | ------------------------ | 6118| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 6119 6120**Example** 6121 6122```ts 6123import { BusinessError } from '@kit.BasicServicesKit'; 6124 6125videoPlayer.pause((err: BusinessError) => { 6126 if (err) { 6127 console.error('Failed to pause!'); 6128 } else { 6129 console.info('Succeeded in pausing!'); 6130 } 6131}); 6132``` 6133 6134### pause<sup>(deprecated)</sup> 6135 6136pause(): Promise\<void> 6137 6138Pauses video playback. This API uses a promise to return the result. 6139 6140> **NOTE** 6141> 6142> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.pause](#pause9-1) instead. 6143 6144**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6145 6146**Return value** 6147 6148| Type | Description | 6149| -------------- | ----------------------------- | 6150| Promise\<void> | Promise that returns no value.| 6151 6152**Example** 6153 6154```ts 6155import { BusinessError } from '@kit.BasicServicesKit'; 6156 6157videoPlayer.pause().then(() => { 6158 console.info('Succeeded in pausing'); 6159}).catch((error: BusinessError) => { 6160 console.error(`video catchCallback, error:${error}`); 6161}); 6162``` 6163 6164### stop<sup>(deprecated)</sup> 6165 6166stop(callback: AsyncCallback\<void>): void 6167 6168Stops video playback. This API uses an asynchronous callback to return the result. 6169 6170> **NOTE** 6171> 6172> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.stop](#stop9) instead. 6173 6174**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6175 6176**Parameters** 6177 6178| Name | Type | Mandatory| Description | 6179| -------- | -------------------- | ---- | ------------------------ | 6180| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 6181 6182**Example** 6183 6184```ts 6185import { BusinessError } from '@kit.BasicServicesKit'; 6186 6187videoPlayer.stop((err: BusinessError) => { 6188 if (err) { 6189 console.error('Failed to stop!'); 6190 } else { 6191 console.info('Succeeded in stopping!'); 6192 } 6193}); 6194``` 6195 6196### stop<sup>(deprecated)</sup> 6197 6198stop(): Promise\<void> 6199 6200Stops video playback. This API uses a promise to return the result. 6201 6202> **NOTE** 6203> 6204> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.stop](#stop9-1) instead. 6205 6206**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6207 6208**Return value** 6209 6210| Type | Description | 6211| -------------- | ----------------------------- | 6212| Promise\<void> | Promise that returns no value.| 6213 6214**Example** 6215 6216```ts 6217import { BusinessError } from '@kit.BasicServicesKit'; 6218 6219videoPlayer.stop().then(() => { 6220 console.info('Succeeded in stopping'); 6221}).catch((error: BusinessError) => { 6222 console.error(`video catchCallback, error:${error}`); 6223}); 6224``` 6225 6226### reset<sup>(deprecated)</sup> 6227 6228reset(callback: AsyncCallback\<void>): void 6229 6230Resets video playback. This API uses an asynchronous callback to return the result. 6231 6232> **NOTE** 6233> 6234> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.reset](#reset9) instead. 6235 6236**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6237 6238**Parameters** 6239 6240| Name | Type | Mandatory| Description | 6241| -------- | -------------------- | ---- | ------------------------ | 6242| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 6243 6244**Example** 6245 6246```ts 6247import { BusinessError } from '@kit.BasicServicesKit'; 6248 6249videoPlayer.reset((err: BusinessError) => { 6250 if (err) { 6251 console.error('Failed to reset!'); 6252 } else { 6253 console.info('Succeeded in resetting!'); 6254 } 6255}); 6256``` 6257 6258### reset<sup>(deprecated)</sup> 6259 6260reset(): Promise\<void> 6261 6262Resets video playback. This API uses a promise to return the result. 6263 6264> **NOTE** 6265> 6266> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.reset](#reset9-1) instead. 6267 6268**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6269 6270**Return value** 6271 6272| Type | Description | 6273| -------------- | ----------------------------- | 6274| Promise\<void> | Promise that returns no value.| 6275 6276**Example** 6277 6278```ts 6279import { BusinessError } from '@kit.BasicServicesKit'; 6280 6281videoPlayer.reset().then(() => { 6282 console.info('Succeeded in resetting'); 6283}).catch((error: BusinessError) => { 6284 console.error(`video catchCallback, error:${error}`); 6285}); 6286``` 6287 6288### seek<sup>(deprecated)</sup> 6289 6290seek(timeMs: number, callback: AsyncCallback\<number>): void 6291 6292Seeks 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. 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| 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. | 6306 6307**Example** 6308 6309```ts 6310import { BusinessError } from '@kit.BasicServicesKit'; 6311 6312let videoPlayer: media.VideoPlayer; 6313media.createVideoPlayer((error: BusinessError, video: media.VideoPlayer) => { 6314 if (video != null) { 6315 videoPlayer = video; 6316 console.info('Succeeded in creating VideoPlayer'); 6317 } else { 6318 console.error(`Failed to create VideoPlayer, error:${error}`); 6319 } 6320}); 6321 6322let seekTime: number = 5000; 6323videoPlayer.seek(seekTime, (err: BusinessError, result: number) => { 6324 if (err) { 6325 console.error('Failed to do seek!'); 6326 } else { 6327 console.info('Succeeded in doing seek!'); 6328 } 6329}); 6330``` 6331 6332### seek<sup>(deprecated)</sup> 6333 6334seek(timeMs: number, mode:SeekMode, callback: AsyncCallback\<number>): void 6335 6336Seeks to the specified playback position. This API uses an asynchronous callback to return the result. 6337 6338> **NOTE** 6339> 6340> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.seek](#seek9) instead. 6341 6342**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6343 6344**Parameters** 6345 6346| Name | Type | Mandatory| Description | 6347| -------- | ---------------------- | ---- | ------------------------------------------------------------ | 6348| timeMs | number | Yes | Position to seek to, in ms. The value range is [0, duration].| 6349| mode | [SeekMode](#seekmode8) | Yes | Seek mode. | 6350| 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. | 6351 6352**Example** 6353 6354```ts 6355import { BusinessError } from '@kit.BasicServicesKit'; 6356 6357let videoPlayer: media.VideoPlayer | null = null; 6358media.createVideoPlayer((error: BusinessError, video: media.VideoPlayer) => { 6359 if (video != null) { 6360 videoPlayer = video; 6361 console.info('Succeeded in creating VideoPlayer'); 6362 } else { 6363 console.error(`Failed to create VideoPlayer, error:${error}`); 6364 } 6365}); 6366let seekTime: number = 5000; 6367if (videoPlayer) { 6368 (videoPlayer as media.VideoPlayer).seek(seekTime, media.SeekMode.SEEK_NEXT_SYNC, (err: BusinessError, result: number) => { 6369 if (err) { 6370 console.error('Failed to do seek!'); 6371 } else { 6372 console.info('Succeeded in doing seek!'); 6373 } 6374 }); 6375} 6376``` 6377 6378### seek<sup>(deprecated)</sup> 6379 6380seek(timeMs: number, mode?:SeekMode): Promise\<number> 6381 6382Seeks 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. 6383 6384> **NOTE** 6385> 6386> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.seek](#seek9) instead. 6387 6388**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6389 6390**Parameters** 6391 6392| Name| Type | Mandatory| Description | 6393| ------ | ---------------------- | ---- | ------------------------------------------------------------ | 6394| timeMs | number | Yes | Position to seek to, in ms. The value range is [0, duration].| 6395| mode | [SeekMode](#seekmode8) | No | Seek mode based on the video I frame. The default value is **SEEK_PREV_SYNC**. | 6396 6397**Return value** 6398 6399| Type | Description | 6400| ---------------- | ------------------------------------------- | 6401| Promise\<number>| Promise used to return the playback position, in ms.| 6402 6403**Example** 6404 6405```ts 6406import { BusinessError } from '@kit.BasicServicesKit'; 6407 6408let videoPlayer: media.VideoPlayer | null = null; 6409media.createVideoPlayer((error: BusinessError, video: media.VideoPlayer) => { 6410 if (video != null) { 6411 videoPlayer = video; 6412 console.info('Succeeded in creating VideoPlayer'); 6413 } else { 6414 console.error(`Failed to create VideoPlayer, error:${error}`); 6415 } 6416}); 6417let seekTime: number = 5000; 6418if (videoPlayer) { 6419 (videoPlayer as media.VideoPlayer).seek(seekTime).then((seekDoneTime: number) => { // seekDoneTime indicates the position after the seek operation is complete. 6420 console.info('Succeeded in doing seek'); 6421 }).catch((error: BusinessError) => { 6422 console.error(`video catchCallback, error:${error}`); 6423 }); 6424 6425 (videoPlayer as media.VideoPlayer).seek(seekTime, media.SeekMode.SEEK_NEXT_SYNC).then((seekDoneTime: number) => { 6426 console.info('Succeeded in doing seek'); 6427 }).catch((error: BusinessError) => { 6428 console.error(`video catchCallback, error:${error}`); 6429 }); 6430} 6431``` 6432 6433### setVolume<sup>(deprecated)</sup> 6434 6435setVolume(vol: number, callback: AsyncCallback\<void>): void 6436 6437Sets the volume. This API uses an asynchronous callback to return the result. 6438 6439> **NOTE** 6440> 6441> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.setVolume](#setvolume9) instead. 6442 6443**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6444 6445**Parameters** 6446 6447| Name | Type | Mandatory| Description | 6448| -------- | -------------------- | ---- | ------------------------------------------------------------ | 6449| vol | number | Yes | Relative volume. The value ranges from 0.00 to 1.00. The value **1.00** indicates the maximum volume (100%).| 6450| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the setting is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 6451 6452**Example** 6453 6454```ts 6455import { BusinessError } from '@kit.BasicServicesKit'; 6456 6457let vol: number = 0.5; 6458videoPlayer.setVolume(vol, (err: BusinessError) => { 6459 if (err) { 6460 console.error('Failed to set Volume!'); 6461 } else { 6462 console.info('Succeeded in setting Volume!'); 6463 } 6464}); 6465``` 6466 6467### setVolume<sup>(deprecated)</sup> 6468 6469setVolume(vol: number): Promise\<void> 6470 6471Sets the volume. This API uses a promise to return the result. 6472 6473> **NOTE** 6474> 6475> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.setVolume](#setvolume9) instead. 6476 6477**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6478 6479**Parameters** 6480 6481| Name| Type | Mandatory| Description | 6482| ------ | ------ | ---- | ------------------------------------------------------------ | 6483| vol | number | Yes | Relative volume. The value ranges from 0.00 to 1.00. The value **1.00** indicates the maximum volume (100%).| 6484 6485**Return value** 6486 6487| Type | Description | 6488| -------------- | ------------------------- | 6489| Promise\<void> | Promise that returns no value.| 6490 6491**Example** 6492 6493```ts 6494import { BusinessError } from '@kit.BasicServicesKit'; 6495 6496let vol: number = 0.5; 6497videoPlayer.setVolume(vol).then(() => { 6498 console.info('Succeeded in setting Volume'); 6499}).catch((error: BusinessError) => { 6500 console.error(`video catchCallback, error:${error}`); 6501}); 6502``` 6503 6504### release<sup>(deprecated)</sup> 6505 6506release(callback: AsyncCallback\<void>): void 6507 6508Releases the video playback resources. This API uses an asynchronous callback to return the result. 6509 6510> **NOTE** 6511> 6512> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.release](#release9) instead. 6513 6514**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6515 6516**Parameters** 6517 6518| Name | Type | Mandatory| Description | 6519| -------- | -------------------- | ---- | ------------------------ | 6520| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 6521 6522**Example** 6523 6524```ts 6525import { BusinessError } from '@kit.BasicServicesKit'; 6526 6527videoPlayer.release((err: BusinessError) => { 6528 if (err) { 6529 console.error('Failed to release!'); 6530 } else { 6531 console.info('Succeeded in releasing!'); 6532 } 6533}); 6534``` 6535 6536### release<sup>(deprecated)</sup> 6537 6538release(): Promise\<void> 6539 6540Releases the video playback resources. This API uses a promise to return the result. 6541 6542> **NOTE** 6543> 6544> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.release](#release9-1) instead. 6545 6546**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6547 6548**Return value** 6549 6550| Type | Description | 6551| -------------- | ----------------------------- | 6552| Promise\<void> | Promise that returns no value.| 6553 6554**Example** 6555 6556```ts 6557import { BusinessError } from '@kit.BasicServicesKit'; 6558 6559videoPlayer.release().then(() => { 6560 console.info('Succeeded in releasing'); 6561}).catch((error: BusinessError) => { 6562 console.error(`video catchCallback, error:${error}`); 6563}); 6564``` 6565 6566### getTrackDescription<sup>(deprecated)</sup> 6567 6568getTrackDescription(callback: AsyncCallback\<Array\<MediaDescription>>): void 6569 6570Obtains the video track information. This API uses an asynchronous callback to return the result. 6571 6572> **NOTE** 6573> 6574> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.getTrackDescription](#gettrackdescription9) instead. 6575 6576**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6577 6578**Parameters** 6579 6580| Name | Type | Mandatory| Description | 6581| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------ | 6582| 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.| 6583 6584**Example** 6585 6586```ts 6587import { BusinessError } from '@kit.BasicServicesKit'; 6588 6589videoPlayer.getTrackDescription((error: BusinessError, arrList: Array<media.MediaDescription>) => { 6590 if ((arrList) != null) { 6591 console.info('Succeeded in getting TrackDescription'); 6592 } else { 6593 console.error(`Failed to get TrackDescription, error:${error}`); 6594 } 6595}); 6596``` 6597 6598### getTrackDescription<sup>(deprecated)</sup> 6599 6600getTrackDescription(): Promise\<Array\<MediaDescription>> 6601 6602Obtains the video track information. This API uses a promise to return the result. 6603 6604> **NOTE** 6605> 6606> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.getTrackDescription](#gettrackdescription9-1) instead. 6607 6608**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6609 6610**Return value** 6611 6612| Type | Description | 6613| ------------------------------------------------------ | ----------------------------------------------- | 6614| Promise<Array<[MediaDescription](#mediadescription8)>> | Promise used to return the MediaDescription array that holds the video track information.| 6615 6616**Example** 6617 6618```ts 6619import { BusinessError } from '@kit.BasicServicesKit'; 6620 6621videoPlayer.getTrackDescription().then((arrList: Array<media.MediaDescription>) => { 6622 if (arrList != null) { 6623 console.info('Succeeded in getting TrackDescription'); 6624 } else { 6625 console.error('Failed to get TrackDescription'); 6626 } 6627}).catch((error: BusinessError) => { 6628 console.error(`video catchCallback, error:${error}`); 6629}); 6630``` 6631 6632### setSpeed<sup>(deprecated)</sup> 6633 6634setSpeed(speed: number, callback: AsyncCallback\<number>): void 6635 6636Sets the playback speed. This API uses an asynchronous callback to return the result. 6637 6638> **NOTE** 6639> 6640> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.setSpeed](#setspeed9) instead. 6641 6642**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6643 6644**Parameters** 6645 6646| Name | Type | Mandatory| Description | 6647| -------- | ---------------------- | ---- | ---------------------------------------------------------- | 6648| speed | number | Yes | Video playback speed. For details, see [PlaybackSpeed](#playbackspeed8).| 6649| 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. | 6650 6651**Example** 6652 6653```ts 6654import { BusinessError } from '@kit.BasicServicesKit'; 6655 6656let videoPlayer: media.VideoPlayer | null = null; 6657media.createVideoPlayer((error: BusinessError, video: media.VideoPlayer) => { 6658 if (video != null) { 6659 videoPlayer = video; 6660 console.info('Succeeded in creating VideoPlayer'); 6661 } else { 6662 console.error(`Failed to create VideoPlayer, error:${error}`); 6663 } 6664}); 6665let speed = media.PlaybackSpeed.SPEED_FORWARD_2_00_X; 6666if (videoPlayer) { 6667 (videoPlayer as media.VideoPlayer).setSpeed(speed, (err: BusinessError, result: number) => { 6668 if (err) { 6669 console.error('Failed to set Speed!'); 6670 } else { 6671 console.info('Succeeded in setting Speed!'); 6672 } 6673 }); 6674} 6675``` 6676 6677### setSpeed<sup>(deprecated)</sup> 6678 6679setSpeed(speed: number): Promise\<number> 6680 6681Sets the playback speed. This API uses a promise to return the result. 6682 6683> **NOTE** 6684> 6685> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.setSpeed](#setspeed9) instead. 6686 6687**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6688 6689**Parameters** 6690 6691| Name| Type | Mandatory| Description | 6692| ------ | ------ | ---- | ---------------------------------------------------------- | 6693| speed | number | Yes | Video playback speed. For details, see [PlaybackSpeed](#playbackspeed8).| 6694 6695**Return value** 6696 6697| Type | Description | 6698| ---------------- | ------------------------------------------------------------ | 6699| Promise\<number>| Promise used to return the playback speed. For details, see [PlaybackSpeed](#playbackspeed8).| 6700 6701**Example** 6702 6703```ts 6704import { BusinessError } from '@kit.BasicServicesKit'; 6705 6706let videoPlayer: media.VideoPlayer | null = null; 6707media.createVideoPlayer((error: BusinessError, video: media.VideoPlayer) => { 6708 if (video != null) { 6709 videoPlayer = video; 6710 console.info('Succeeded in creating VideoPlayer'); 6711 } else { 6712 console.error(`Failed to create VideoPlayer, error:${error}`); 6713 } 6714}); 6715let speed = media.PlaybackSpeed.SPEED_FORWARD_2_00_X; 6716if (videoPlayer) { 6717 (videoPlayer as media.VideoPlayer).setSpeed(speed).then((result: number) => { 6718 console.info('Succeeded in setting Speed'); 6719 }).catch((error: BusinessError) => { 6720 console.error(`Failed to set Speed, error:${error}`);//todo:: error 6721 }); 6722} 6723``` 6724 6725### on('playbackCompleted')<sup>(deprecated)</sup> 6726 6727on(type: 'playbackCompleted', callback: Callback\<void>): void 6728 6729Subscribes to the video playback completion event. 6730 6731> **NOTE** 6732> 6733> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.on('stateChange')](#onstatechange9) instead. 6734 6735**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6736 6737**Parameters** 6738 6739| Name | Type | Mandatory| Description | 6740| -------- | -------- | ---- | ----------------------------------------------------------- | 6741| type | string | Yes | Event type, which is **'playbackCompleted'** in this case.| 6742| callback | Callback\<void> | Yes | Callback invoked when the event is triggered. | 6743 6744**Example** 6745 6746```ts 6747videoPlayer.on('playbackCompleted', () => { 6748 console.info('playbackCompleted called!'); 6749}); 6750``` 6751 6752### on('bufferingUpdate')<sup>(deprecated)</sup> 6753 6754on(type: 'bufferingUpdate', callback: (infoType: BufferingInfoType, value: number) => void): void 6755 6756Subscribes to the video buffering update event. This API works only under online playback. 6757 6758> **NOTE** 6759> 6760> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.on('bufferingUpdate')](#onbufferingupdate9) instead. 6761 6762**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6763 6764**Parameters** 6765 6766| Name | Type | Mandatory| Description | 6767| -------- | -------- | ---- | ------------------------------------------------------------ | 6768| type | string | Yes | Event type, which is **'bufferingUpdate'** in this case. | 6769| callback | function | Yes | Callback invoked when the event is triggered.<br>The value of [BufferingInfoType](#bufferinginfotype8) is fixed at **0**.| 6770 6771**Example** 6772 6773```ts 6774videoPlayer.on('bufferingUpdate', (infoType: media.BufferingInfoType, value: number) => { 6775 console.info('video bufferingInfo type: ' + infoType); 6776 console.info('video bufferingInfo value: ' + value); 6777}); 6778``` 6779 6780### on('startRenderFrame')<sup>(deprecated)</sup> 6781 6782on(type: 'startRenderFrame', callback: Callback\<void>): void 6783 6784Subscribes to the frame rendering start event. 6785 6786> **NOTE** 6787> 6788> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.on('startRenderFrame')](#onstartrenderframe9) instead. 6789 6790**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6791 6792**Parameters** 6793 6794| Name | Type | Mandatory| Description | 6795| -------- | --------------- | ---- | ------------------------------------------------------------ | 6796| type | string | Yes | Event type, which is **'startRenderFrame'** in this case.| 6797| callback | Callback\<void> | Yes | Callback invoked when the event is triggered. | 6798 6799**Example** 6800 6801```ts 6802videoPlayer.on('startRenderFrame', () => { 6803 console.info('startRenderFrame called!'); 6804}); 6805``` 6806 6807### on('videoSizeChanged')<sup>(deprecated)</sup> 6808 6809on(type: 'videoSizeChanged', callback: (width: number, height: number) => void): void 6810 6811Subscribes to the video width and height change event. 6812 6813> **NOTE** 6814> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.on('videoSizeChange')](#onvideosizechange9) instead. 6815 6816**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6817 6818**Parameters** 6819 6820| Name | Type | Mandatory| Description | 6821| -------- | -------- | ---- | ------------------------------------------------------------ | 6822| type | string | Yes | Event type, which is **'videoSizeChanged'** in this case.| 6823| callback | function | Yes | Callback invoked when the event is triggered. **width** indicates the video width, and **height** indicates the video height. | 6824 6825**Example** 6826 6827```ts 6828videoPlayer.on('videoSizeChanged', (width: number, height: number) => { 6829 console.info('video width is: ' + width); 6830 console.info('video height is: ' + height); 6831}); 6832``` 6833### on('audioInterrupt')<sup>(deprecated)</sup> 6834 6835on(type: 'audioInterrupt', callback: (info: audio.InterruptEvent) => void): void 6836 6837Subscribes to the audio interruption event. For details, see [audio.InterruptEvent](../apis-audio-kit/js-apis-audio.md#interruptevent9). 6838 6839> **NOTE** 6840> 6841> This API is supported in API version 9 and deprecated since API version 9. You are advised to use [AVPlayer.on('audioInterrupt')](#onaudiointerrupt9) instead. 6842 6843**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6844 6845**Parameters** 6846 6847| Name | Type | Mandatory| Description | 6848| -------- | ------------------------------------------------------------ | ---- | -------------------------------------------------------- | 6849| type | string | Yes | Event type, which is **'audioInterrupt'** in this case.| 6850| callback | function | Yes | Callback invoked when the event is triggered. | 6851 6852**Example** 6853 6854```ts 6855import { audio } from '@kit.AudioKit'; 6856 6857videoPlayer.on('audioInterrupt', (info: audio.InterruptEvent) => { 6858 console.info('audioInterrupt called,and InterruptEvent info is:' + info) 6859}) 6860``` 6861 6862### on('error')<sup>(deprecated)</sup> 6863 6864on(type: 'error', callback: ErrorCallback): void 6865 6866Subscribes to video playback error events. After an error event is reported, you must handle the event and exit the playback. 6867 6868> **NOTE** 6869> 6870> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.on('error')](#onerror9) instead. 6871 6872**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6873 6874**Parameters** 6875 6876| Name | Type | Mandatory| Description | 6877| -------- | ------------- | ---- | ------------------------------------------------------------ | 6878| type | string | Yes | Event type, which is **'error'** in this case.<br>This event is triggered when an error occurs during video playback.| 6879| callback | [ErrorCallback](../apis-basic-services-kit/js-apis-base.md#errorcallback) | Yes | Callback invoked when the event is triggered. | 6880 6881**Example** 6882 6883```ts 6884import { BusinessError } from '@kit.BasicServicesKit'; 6885 6886videoPlayer.on('error', (error: BusinessError) => { // Set the 'error' event callback. 6887 console.error(`video error called, error: ${error}`); 6888}); 6889videoPlayer.url = 'fd://error'; // Set an incorrect URL to trigger the 'error' event. 6890``` 6891 6892## VideoPlayState<sup>(deprecated)</sup> 6893 6894type VideoPlayState = 'idle' | 'prepared' | 'playing' | 'paused' | 'stopped' | 'error' 6895 6896Enumerates the video playback states. You can obtain the state through the **state** attribute. 6897 6898> **NOTE** 6899> 6900> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayerState](#avplayerstate9) instead. 6901 6902**System capability**: SystemCapability.Multimedia.Media.VideoPlayer 6903 6904| Type | Description | 6905| -------- | -------------- | 6906| 'idle' | The video player is idle.| 6907| 'prepared' | Video playback is being prepared.| 6908| 'playing' | Video playback is in progress.| 6909| 'paused' | Video playback is paused.| 6910| 'stopped' | Video playback is stopped.| 6911| 'error' | Video playback is in the error state. | 6912 6913## AudioRecorder<sup>(deprecated)</sup> 6914 6915> **NOTE** 6916> 6917> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVRecorder](#avrecorder9) instead. 6918 6919Implements audio recording. Before calling any API of **AudioRecorder**, you must use [createAudioRecorder()](#mediacreateaudiorecorderdeprecated) to create an **AudioRecorder** instance. 6920 6921### prepare<sup>(deprecated)</sup> 6922 6923prepare(config: AudioRecorderConfig): void 6924 6925Prepares for recording. 6926 6927> **NOTE** 6928> 6929> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVRecorder.prepare](#prepare9-2) instead. 6930 6931**Required permissions:** ohos.permission.MICROPHONE 6932 6933**System capability**: SystemCapability.Multimedia.Media.AudioRecorder 6934 6935**Parameters** 6936 6937| Name| Type | Mandatory| Description | 6938| ------ | ------------------------------------------- | ---- | ------------------------------------------------------------ | 6939| config | [AudioRecorderConfig](#audiorecorderconfigdeprecated) | Yes | Audio recording parameters, including the audio output URI, encoding format, sampling rate, number of audio channels, and output format.| 6940 6941**Error codes** 6942 6943For details about the error codes, see [Media Error Codes](errorcode-media.md). 6944 6945| ID| Error Message | 6946| -------- | --------------------- | 6947| 201 | permission denied | 6948 6949**Example** 6950 6951```ts 6952let audioRecorderConfig: media.AudioRecorderConfig = { 6953 audioEncoder : media.AudioEncoder.AAC_LC, 6954 audioEncodeBitRate : 22050, 6955 audioSampleRate : 22050, 6956 numberOfChannels : 2, 6957 format : media.AudioOutputFormat.AAC_ADTS, 6958 uri : 'fd://1', // The file must be created by the caller and granted with proper permissions. 6959 location : { latitude : 30, longitude : 130}, 6960} 6961audioRecorder.on('prepare', () => { // Set the 'prepare' event callback. 6962 console.info('prepare called'); 6963}); 6964audioRecorder.prepare(audioRecorderConfig); 6965``` 6966 6967### start<sup>(deprecated)</sup> 6968 6969start(): void 6970 6971Starts audio recording. This API can be called only after the **'prepare'** event is triggered. 6972 6973> **NOTE** 6974> 6975> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVRecorder.start](#start9) instead. 6976 6977**System capability**: SystemCapability.Multimedia.Media.AudioRecorder 6978 6979**Example** 6980 6981```ts 6982audioRecorder.on('start', () => { // Set the 'start' event callback. 6983 console.info('audio recorder start called'); 6984}); 6985audioRecorder.start(); 6986``` 6987 6988### pause<sup>(deprecated)</sup> 6989 6990pause():void 6991 6992Pauses audio recording. This API can be called only after the **'start'** event is triggered. 6993 6994> **NOTE** 6995> 6996> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVRecorder.pause](#pause9-2) instead. 6997 6998**System capability**: SystemCapability.Multimedia.Media.AudioRecorder 6999 7000**Example** 7001 7002```ts 7003audioRecorder.on('pause', () => { // Set the 'pause' event callback. 7004 console.info('audio recorder pause called'); 7005}); 7006audioRecorder.pause(); 7007``` 7008 7009### resume<sup>(deprecated)</sup> 7010 7011resume():void 7012 7013Resumes audio recording. This API can be called only after the **'pause'** event is triggered. 7014 7015> **NOTE** 7016> 7017> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVRecorder.resume](#resume9) instead. 7018 7019**System capability**: SystemCapability.Multimedia.Media.AudioRecorder 7020 7021**Example** 7022 7023```ts 7024audioRecorder.on('resume', () => { // Set the 'resume' event callback. 7025 console.info('audio recorder resume called'); 7026}); 7027audioRecorder.resume(); 7028``` 7029 7030### stop<sup>(deprecated)</sup> 7031 7032stop(): void 7033 7034Stops audio recording. 7035 7036> **NOTE** 7037> 7038> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVRecorder.stop](#stop9-2) instead. 7039 7040**System capability**: SystemCapability.Multimedia.Media.AudioRecorder 7041 7042**Example** 7043 7044```ts 7045audioRecorder.on('stop', () => { // Set the 'stop' event callback. 7046 console.info('audio recorder stop called'); 7047}); 7048audioRecorder.stop(); 7049``` 7050 7051### release<sup>(deprecated)</sup> 7052 7053release(): void 7054 7055Releases the audio recording resources. 7056 7057> **NOTE** 7058> 7059> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVRecorder.release](#release9-2) instead. 7060 7061**System capability**: SystemCapability.Multimedia.Media.AudioRecorder 7062 7063**Example** 7064 7065```ts 7066audioRecorder.on('release', () => { // Set the 'release' event callback. 7067 console.info('audio recorder release called'); 7068}); 7069audioRecorder.release(); 7070audioRecorder = undefined; 7071``` 7072 7073### reset<sup>(deprecated)</sup> 7074 7075reset(): void 7076 7077Resets audio recording. 7078 7079Before 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. 7080 7081> **NOTE** 7082> 7083> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVRecorder.reset](#reset9-2) instead. 7084 7085**System capability**: SystemCapability.Multimedia.Media.AudioRecorder 7086 7087**Example** 7088 7089```ts 7090audioRecorder.on('reset', () => { // Set the 'reset' event callback. 7091 console.info('audio recorder reset called'); 7092}); 7093audioRecorder.reset(); 7094``` 7095 7096### on('prepare' | 'start' | 'pause' | 'resume' | 'stop' | 'release' | 'reset')<sup>(deprecated)</sup> 7097 7098on(type: 'prepare' | 'start' | 'pause' | 'resume' | 'stop' | 'release' | 'reset', callback: () => void): void 7099 7100Subscribes to the audio recording events. 7101 7102> **NOTE** 7103> 7104> 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. 7105 7106**System capability**: SystemCapability.Multimedia.Media.AudioRecorder 7107 7108**Parameters** 7109 7110| Name | Type | Mandatory| Description | 7111| -------- | -------- | ---- | ------------------------------------------------------------ | 7112| 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.| 7113| callback | ()=>void | Yes | Callback invoked when the event is triggered. | 7114 7115**Example** 7116 7117```ts 7118import { BusinessError } from '@kit.BasicServicesKit'; 7119 7120let audioRecorder: media.AudioRecorder = media.createAudioRecorder(); // Create an AudioRecorder instance. 7121let audioRecorderConfig: media.AudioRecorderConfig = { 7122 audioEncoder : media.AudioEncoder.AAC_LC, 7123 audioEncodeBitRate : 22050, 7124 audioSampleRate : 22050, 7125 numberOfChannels : 2, 7126 format : media.AudioOutputFormat.AAC_ADTS, 7127 uri : 'fd://xx', // The file must be created by the caller and granted with proper permissions. 7128 location : { latitude : 30, longitude : 130} 7129} 7130audioRecorder.on('error', (error: BusinessError) => { // Set the 'error' event callback. 7131 console.error(`audio error called, error: ${error}`); 7132}); 7133audioRecorder.on('prepare', () => { // Set the 'prepare' event callback. 7134 console.info('prepare called'); 7135 audioRecorder.start(); // // Start recording and trigger the 'start' event callback. 7136}); 7137audioRecorder.on('start', () => { // Set the 'start' event callback. 7138 console.info('audio recorder start called'); 7139}); 7140audioRecorder.on('pause', () => { // Set the 'pause' event callback. 7141 console.info('audio recorder pause called'); 7142}); 7143audioRecorder.on('resume', () => { // Set the 'resume' event callback. 7144 console.info('audio recorder resume called'); 7145}); 7146audioRecorder.on('stop', () => { // Set the 'stop' event callback. 7147 console.info('audio recorder stop called'); 7148}); 7149audioRecorder.on('release', () => { // Set the 'release' event callback. 7150 console.info('audio recorder release called'); 7151}); 7152audioRecorder.on('reset', () => { // Set the 'reset' event callback. 7153 console.info('audio recorder reset called'); 7154}); 7155audioRecorder.prepare(audioRecorderConfig) // // Set recording parameters and trigger the 'prepare' event callback. 7156``` 7157 7158### on('error')<sup>(deprecated)</sup> 7159 7160on(type: 'error', callback: ErrorCallback): void 7161 7162Subscribes to audio recording error events. After an error event is reported, you must handle the event and exit the recording. 7163 7164> **NOTE** 7165> 7166> 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. 7167 7168**System capability**: SystemCapability.Multimedia.Media.AudioRecorder 7169 7170**Parameters** 7171 7172| Name | Type | Mandatory| Description | 7173| -------- | ------------- | ---- | ------------------------------------------------------------ | 7174| type | string | Yes | Event type, which is **'error'** in this case.<br>This event is triggered when an error occurs during audio recording.| 7175| callback | [ErrorCallback](../apis-basic-services-kit/js-apis-base.md#errorcallback) | Yes | Callback invoked when the event is triggered. | 7176 7177**Example** 7178 7179```ts 7180import { BusinessError } from '@kit.BasicServicesKit'; 7181 7182let audioRecorderConfig: media.AudioRecorderConfig = { 7183 audioEncoder : media.AudioEncoder.AAC_LC, 7184 audioEncodeBitRate : 22050, 7185 audioSampleRate : 22050, 7186 numberOfChannels : 2, 7187 format : media.AudioOutputFormat.AAC_ADTS, 7188 uri : 'fd://xx', // The file must be created by the caller and granted with proper permissions. 7189 location : { latitude : 30, longitude : 130} 7190} 7191audioRecorder.on('error', (error: BusinessError) => { // Set the 'error' event callback. 7192 console.error(`audio error called, error: ${error}`); 7193}); 7194audioRecorder.prepare(audioRecorderConfig); // // Do not set any parameter in prepare and trigger the 'error' event callback. 7195``` 7196 7197## AudioRecorderConfig<sup>(deprecated)</sup> 7198 7199> **NOTE** 7200> 7201> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVRecorderConfig](#avrecorderconfig9) instead. 7202 7203Describes audio recording configurations. 7204 7205**System capability**: SystemCapability.Multimedia.Media.AudioRecorder 7206 7207| Name | Type | Mandatory| Description | 7208| ----------------------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | 7209| 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.| 7210| audioEncodeBitRate | number | No | Audio encoding bit rate. The default value is **48000**. | 7211| audioSampleRate | number | No | Audio sampling rate. The default value is **48000**.<br>Variable bit rate. The bit rate is for reference only. | 7212| numberOfChannels | number | No | Number of audio channels. The default value is **2**. | 7213| 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.| 7214| location | [Location](#location) | No | Geographical location of the recorded audio. | 7215| 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.| 7216| audioEncoderMime<sup>8+</sup> | [CodecMimeType](#codecmimetype8) | No | Container encoding format. | 7217| fileFormat<sup>8+</sup> | [ContainerFormatType](#containerformattype8) | No | Audio encoding format. | 7218 7219## AudioEncoder<sup>(deprecated)</sup> 7220 7221> **NOTE** 7222> 7223> This API is supported since API version 6 and deprecated since API version 8. You are advised to use [CodecMimeType](#codecmimetype8) instead. 7224 7225Enumerates the audio encoding formats. 7226 7227**System capability**: SystemCapability.Multimedia.Media.AudioRecorder 7228 7229| Name | Value | Description | 7230| ------- | ---- | ------------------------------------------------------------ | 7231| DEFAULT | 0 | Default encoding format.<br>This API is defined but not implemented yet. | 7232| AMR_NB | 1 | AMR-NB.<br>This API is defined but not implemented yet.| 7233| AMR_WB | 2 | Adaptive Multi Rate-Wide Band Speech Codec (AMR-WB).<br>This API is defined but not implemented yet.| 7234| AAC_LC | 3 | Advanced Audio Coding Low Complexity (AAC-LC).| 7235| HE_AAC | 4 | High-Efficiency Advanced Audio Coding (HE_AAC).<br>This API is defined but not implemented yet.| 7236 7237## AudioOutputFormat<sup>(deprecated)</sup> 7238 7239> **NOTE** 7240> 7241> This API is supported since API version 6 and deprecated since API version 8. You are advised to use [ContainerFormatType](#containerformattype8) instead. 7242 7243Enumerates the audio output formats. 7244 7245**System capability**: SystemCapability.Multimedia.Media.AudioRecorder 7246 7247| Name | Value | Description | 7248| -------- | ---- | ------------------------------------------------------------ | 7249| DEFAULT | 0 | Default output format.<br>This API is defined but not implemented yet. | 7250| MPEG_4 | 2 | MPEG-4. | 7251| AMR_NB | 3 | AMR_NB.<br>This API is defined but not implemented yet. | 7252| AMR_WB | 4 | AMR_WB.<br>This API is defined but not implemented yet. | 7253| AAC_ADTS | 6 | Audio Data Transport Stream (ADTS), which is a transport stream format of AAC-based audio.| 7254 7255 7256## media.createAVImageGenerator<sup>12+</sup> 7257 7258createAVImageGenerator(callback: AsyncCallback\<AVImageGenerator>): void 7259 7260Creates an **AVImageGenerator** instance. This API uses an asynchronous callback to return the result. 7261 7262**System capability**: SystemCapability.Multimedia.Media.AVImageGenerator 7263 7264**Parameters** 7265 7266| Name | Type | Mandatory| Description | 7267| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ | 7268| 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.| 7269 7270**Error codes** 7271 7272For details about the error codes, see [Media Error Codes](errorcode-media.md). 7273 7274| ID| Error Message | 7275| -------- | ------------------------------ | 7276| 5400101 | No memory. Returned by callback. | 7277 7278**Example** 7279 7280```ts 7281import { BusinessError } from '@kit.BasicServicesKit'; 7282 7283let avImageGenerator: media.AVImageGenerator; 7284media.createAVImageGenerator((error: BusinessError, generator: media.AVImageGenerator) => { 7285 if (generator != null) { 7286 avImageGenerator = generator; 7287 console.info('Succeeded in creating AVImageGenerator'); 7288 } else { 7289 console.error(`Failed to creat AVImageGenerator, error message:${error.message}`); 7290 } 7291}); 7292``` 7293 7294## media.createAVImageGenerator<sup>12+</sup> 7295 7296createAVImageGenerator(): Promise\<AVImageGenerator> 7297 7298Creates an **AVImageGenerator** instance. This API uses a promise to return the result. 7299 7300**System capability**: SystemCapability.Multimedia.Media.AVImageGenerator 7301 7302**Return value** 7303 7304| Type | Description | 7305| ------------------------------- | ------------------------------------------------------------ | 7306| 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.| 7307 7308**Error codes** 7309 7310For details about the error codes, see [Media Error Codes](errorcode-media.md). 7311 7312| ID| Error Message | 7313| -------- | ----------------------------- | 7314| 5400101 | No memory. Returned by promise. | 7315 7316**Example** 7317 7318```ts 7319import { BusinessError } from '@kit.BasicServicesKit'; 7320 7321let avImageGenerator: media.AVImageGenerator; 7322media.createAVImageGenerator().then((generator: media.AVImageGenerator) => { 7323 if (generator != null) { 7324 avImageGenerator = generator; 7325 console.info('Succeeded in creating AVImageGenerator'); 7326 } else { 7327 console.error('Failed to creat AVImageGenerator'); 7328 } 7329}).catch((error: BusinessError) => { 7330 console.error(`Failed to creat AVImageGenerator, error message:${error.message}`); 7331}); 7332``` 7333 7334## AVImageGenerator<sup>12+</sup> 7335 7336Provides APIs to obtain a thumbnail from a video. Before calling any API of **AVImageGenerator**, you must use [createAVImageGenerator()](#mediacreateavimagegenerator12) to create an **AVImageGenerator** instance. 7337 7338For details about the demo for obtaining video thumbnails, see [Obtaining Video Thumbnails](../../media/media/avimagegenerator.md). 7339 7340### Attributes 7341 7342**System capability**: SystemCapability.Multimedia.Media.AVImageGenerator 7343 7344| Name | Type | Readable| Writable| Description | 7345| --------------------------------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | 7346| 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.| 7347 7348### fetchFrameByTime<sup>12+</sup> 7349 7350fetchFrameByTime(timeUs: number, options: AVImageQueryOptions, param: PixelMapParams, callback: AsyncCallback\<image.PixelMap>): void 7351 7352Obtains a video thumbnail. This API uses an asynchronous callback to return the result. 7353 7354**System capability**: SystemCapability.Multimedia.Media.AVImageGenerator 7355 7356**Parameters** 7357 7358| Name | Type | Mandatory| Description | 7359| -------- | -------------------------------------------- | ---- | ----------------------------------- | 7360| timeUs | number | Yes | Time of the video for which a thumbnail is to be obtained, in μs.| 7361| options | [AVImageQueryOptions](#avimagequeryoptions12) | Yes | Relationship between the time passed in and the video frame.| 7362| param | [PixelMapParams](#pixelmapparams12) | Yes | Format parameters of the thumbnail to be obtained.| 7363| 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.| 7364 7365**Error codes** 7366 7367For details about the error codes, see [Media Error Codes](errorcode-media.md). 7368 7369| ID| Error Message | 7370| -------- | ------------------------------------------ | 7371| 5400102 | Operation not allowed. Returned by callback. | 7372| 5400106 | Unsupported format. Returned by callback. | 7373 7374**Example** 7375 7376```ts 7377import { BusinessError } from '@kit.BasicServicesKit'; 7378import { image } from '@kit.ImageKit'; 7379 7380let avImageGenerator: media.AVImageGenerator | undefined = undefined; 7381let pixel_map : image.PixelMap | undefined = undefined; 7382 7383// Initialize input parameters. 7384let timeUs: number = 0 7385 7386let queryOption: media.AVImageQueryOptions = media.AVImageQueryOptions.AV_IMAGE_QUERY_NEXT_SYNC 7387 7388let param: media.PixelMapParams = { 7389 width : 300, 7390 height : 300, 7391} 7392 7393// Obtain the thumbnail. 7394media.createAVImageGenerator((err: BusinessError, generator: media.AVImageGenerator) => { 7395 if(generator != null){ 7396 avImageGenerator = generator; 7397 console.info(`Succeeded in creating AVImageGenerator`); 7398 avImageGenerator.fetchFrameByTime(timeUs, queryOption, param, (error: BusinessError, pixelMap) => { 7399 if (error) { 7400 console.error(`Failed to fetch FrameByTime, err = ${JSON.stringify(error)}`) 7401 return 7402 } 7403 pixel_map = pixelMap; 7404 }); 7405 } else { 7406 console.error(`Failed to creat AVImageGenerator, error message:${err.message}`); 7407 }; 7408}); 7409``` 7410 7411### fetchFrameByTime<sup>12+</sup> 7412 7413fetchFrameByTime(timeUs: number, options: AVImageQueryOptions, param: PixelMapParams): Promise<image.PixelMap> 7414 7415Obtains a video thumbnail. This API uses a promise to return the result. 7416 7417**System capability**: SystemCapability.Multimedia.Media.AVImageGenerator 7418 7419**Parameters** 7420 7421| Name | Type | Mandatory| Description | 7422| -------- | -------------------------------------------- | ---- | ----------------------------------- | 7423| timeUs | number | Yes | Time of the video for which a thumbnail is to be obtained, in μs.| 7424| options | [AVImageQueryOptions](#avimagequeryoptions12) | Yes | Relationship between the time passed in and the video frame.| 7425| param | [PixelMapParams](#pixelmapparams12) | Yes | Format parameters of the thumbnail to be obtained.| 7426 7427**Return value** 7428 7429| Type | Description | 7430| -------------- | ---------------------------------------- | 7431| Promise\<[image.PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)> | Promise used to return the video thumbnail.| 7432 7433**Error codes** 7434 7435For details about the error codes, see [Media Error Codes](errorcode-media.md). 7436 7437| ID| Error Message | 7438| -------- | ----------------------------------------- | 7439| 5400102 | Operation not allowed. Returned by promise. | 7440| 5400106 | Unsupported format. Returned by promise. | 7441 7442**Example** 7443 7444```ts 7445import { BusinessError } from '@kit.BasicServicesKit'; 7446import { image } from '@kit.ImageKit'; 7447 7448let avImageGenerator: media.AVImageGenerator | undefined = undefined; 7449let pixel_map : image.PixelMap | undefined = undefined; 7450 7451// Initialize input parameters. 7452let timeUs: number = 0 7453 7454let queryOption: media.AVImageQueryOptions = media.AVImageQueryOptions.AV_IMAGE_QUERY_NEXT_SYNC 7455 7456let param: media.PixelMapParams = { 7457 width : 300, 7458 height : 300, 7459} 7460 7461// Obtain the thumbnail. 7462media.createAVImageGenerator((err: BusinessError, generator: media.AVImageGenerator) => { 7463 if(generator != null){ 7464 avImageGenerator = generator; 7465 console.info(`Succeeded in creating AVImageGenerator`); 7466 avImageGenerator.fetchFrameByTime(timeUs, queryOption, param).then((pixelMap: image.PixelMap) => { 7467 pixel_map = pixelMap; 7468 }).catch((error: BusinessError) => { 7469 console.error(`Failed to fetch FrameByTime, error message:${error.message}`); 7470 }); 7471 } else { 7472 console.error(`Failed to creat AVImageGenerator, error message:${err.message}`); 7473 }; 7474}); 7475``` 7476 7477### release<sup>12+</sup> 7478 7479release(callback: AsyncCallback\<void>): void 7480 7481Releases this **AVMetadataExtractor** instance. This API uses an asynchronous callback to return the result. 7482 7483**System capability**: SystemCapability.Multimedia.Media.AVImageGenerator 7484 7485**Parameters** 7486 7487| Name | Type | Mandatory| Description | 7488| -------- | -------------------------------------------- | ---- | ----------------------------------- | 7489| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| 7490 7491**Error codes** 7492 7493For details about the error codes, see [Media Error Codes](errorcode-media.md). 7494 7495| ID| Error Message | 7496| -------- | ------------------------------------------ | 7497| 5400102 | Operation not allowed. Returned by callback. | 7498 7499**Example** 7500 7501```ts 7502import { BusinessError } from '@kit.BasicServicesKit'; 7503 7504let avImageGenerator: media.AVImageGenerator | undefined = undefined; 7505 7506// Release the instance. 7507media.createAVImageGenerator((err: BusinessError, generator: media.AVImageGenerator) => { 7508 if(generator != null){ 7509 avImageGenerator = generator; 7510 console.info(`Succeeded in creating AVImageGenerator`); 7511 avImageGenerator.release((error: BusinessError) => { 7512 if (error) { 7513 console.error(`Failed to release, err = ${JSON.stringify(error)}`); 7514 return; 7515 } 7516 console.info(`Succeeded in releasing`); 7517 }); 7518 } else { 7519 console.error(`Failed to creat AVImageGenerator, error message:${err.message}`); 7520 }; 7521}); 7522``` 7523 7524### release<sup>12+</sup> 7525 7526release(): Promise\<void> 7527 7528Releases this **AVMetadataExtractor** instance. This API uses a promise to return the result. 7529 7530**System capability**: SystemCapability.Multimedia.Media.AVImageGenerator 7531 7532**Return value** 7533 7534| Type | Description | 7535| -------------- | ---------------------------------------- | 7536| Promise\<void> | Promise that returns no value.| 7537 7538**Error codes** 7539 7540For details about the error codes, see [Media Error Codes](errorcode-media.md). 7541 7542| ID| Error Message | 7543| -------- | ----------------------------------------- | 7544| 5400102 | Operation not allowed. Returned by promise. | 7545 7546**Example** 7547 7548```ts 7549import { BusinessError } from '@kit.BasicServicesKit'; 7550 7551let avImageGenerator: media.AVImageGenerator | undefined = undefined; 7552 7553// Release the instance. 7554media.createAVImageGenerator((err: BusinessError, generator: media.AVImageGenerator) => { 7555 if(generator != null){ 7556 avImageGenerator = generator; 7557 console.info(`Succeeded in creating AVImageGenerator`); 7558 avImageGenerator.release().then(() => { 7559 console.info(`Succeeded in releasing.`); 7560 }).catch((error: BusinessError) => { 7561 console.error(`Failed to release, error message:${error.message}`); 7562 }); 7563 } else { 7564 console.error(`Failed to creat AVImageGenerator, error message:${err.message}`); 7565 }; 7566}); 7567``` 7568 7569## AVImageQueryOptions<sup>12+</sup> 7570 7571Enumerates the relationship between the video frame and the time at which the video thumbnail is obtained. 7572 7573The 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. 7574 7575**System capability**: SystemCapability.Multimedia.Media.AVImageGenerator 7576 7577| Name | Value | Description | 7578| ------------------------ | --------------- | ------------------------------------------------------------ | 7579| AV_IMAGE_QUERY_NEXT_SYNC | 0 | The key frame at or next to the specified time is selected. | 7580| AV_IMAGE_QUERY_PREVIOUS_SYNC | 1 | The key frame at or prior to the specified time is selected.| 7581| AV_IMAGE_QUERY_CLOSEST_SYNC | 2 | The key frame closest to the specified time is selected. | 7582| AV_IMAGE_QUERY_CLOSEST | 3 | The frame (not necessarily a key frame) closest to the specified time is selected.| 7583 7584## PixelMapParams<sup>12+</sup> 7585 7586Defines the format parameters of the video thumbnail to be obtained. 7587 7588**System capability**: SystemCapability.Multimedia.Media.AVImageGenerator 7589 7590| Name | Type | Readable| Writable| Description | 7591|--------|--------|------|------|---------------------------------------------------------------------------------| 7592| 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.| 7593| 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.| 7594 7595## media.createMediaSourceWithUrl<sup>12+</sup> 7596 7597createMediaSourceWithUrl(url: string, headers?: Record\<string, string>): MediaSource 7598 7599Creates a media source for streaming media to be pre-downloaded. 7600 7601**Atomic service API**: This API can be used in atomic services since API version 13. 7602 7603**System capability**: SystemCapability.Multimedia.Media.Core 7604 7605**Parameters** 7606 7607| Name | Type | Mandatory| Description | 7608| -------- | -------- | ---- | -------------------- | 7609| 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. | 7610| headers | Record\<string, string> | No | HTTP header customized for streaming media pre-download.| 7611 7612**Return value** 7613 7614| Type | Description | 7615| -------------- | ------------------------------------------ | 7616| [MediaSource](#mediasource12) | **MediaSource** instance.| 7617 7618**Error codes** 7619 7620For details about the error codes, see [Media Error Codes](errorcode-media.md). 7621 7622| ID| Error Message | 7623| -------- | ----------------------------------------- | 7624| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 7625| 5400101 | No memory. | 7626 7627**Example 1** 7628 7629```ts 7630let headers: Record<string, string> = {"User-Agent" : "User-Agent-Value"}; 7631let mediaSource : media.MediaSource = media.createMediaSourceWithUrl("http://xxx", headers); 7632``` 7633 7634**Example 2** 7635 7636```ts 7637import { common } from '@kit.AbilityKit'; 7638import { resourceManager } from '@kit.LocalizationKit'; 7639 7640let context = getContext(this) as common.UIAbilityContext; 7641let mgr = context.resourceManager; 7642let fileDescriptor = await mgr.getRawFd("xxx.m3u8"); 7643 7644let fd:string = fileDescriptor.fd.toString(); 7645let offset:string = fileDescriptor.offset.toString(); 7646let length:string = fileDescriptor.length.toString(); 7647let fdUrl:string = "fd://" + fd + "?offset=" + offset + "&size=" + length; 7648 7649let headers: Record<string, string> = {"User-Agent" : "User-Agent-Value"}; 7650let mediaSource : media.MediaSource = media.createMediaSourceWithUrl(fdUrl, headers); 7651 7652let mimeType : media.AVMimeTypes = media.AVMimeTypes.APPLICATION_M3U8; 7653mediaSource.setMimeType(mimeType); 7654 7655``` 7656 7657## MediaSource<sup>12+</sup> 7658 7659Defines the media data information, which is from [createMediaSourceWithUrl](#mediacreatemediasourcewithurl12). 7660 7661**System capability**: SystemCapability.Multimedia.Media.Core 7662 7663### setMimeType<sup>12+</sup> 7664 7665setMimeType(mimeType: AVMimeTypes): void 7666 7667Sets the MIME type to help the player process extended media sources. 7668 7669**Atomic service API**: This API can be used in atomic services since API version 12. 7670 7671**System capability**: SystemCapability.Multimedia.Media.Core 7672 7673**Parameters** 7674 7675| Name | Type | Mandatory| Description | 7676| -------- | -------- | ---- | -------------------- | 7677| mimeType | [AVMimeTypes](#mediasource12) | Yes | MIME type.| 7678 7679## AVMimeTypes<sup>12+</sup> 7680 7681Enumerates the MIME type, which is set by using [setMimeType](#setmimetype12). 7682 7683**Atomic service API**: This API can be used in atomic services since API version 12. 7684 7685**System capability**: SystemCapability.Multimedia.Media.Core 7686 7687 7688| Name | Value | Description | 7689| ---------- | ---- | ------------------------------------------------------------ | 7690| APPLICATION_M3U8 | application/m3u8 | Local M3U8 file.| 7691 7692 7693## PlaybackStrategy<sup>12+</sup> 7694 7695Describes the playback strategy. 7696 7697**System capability**: SystemCapability.Multimedia.Media.Core 7698 7699| Name | Type | Mandatory| Description | 7700| -------- | -------- | ---- | -------------------- | 7701| 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.| 7702| 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.| 7703| 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.| 7704| 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.| 7705| mutedMediaType | [MediaType](#mediatype8) | No| Media type for muted playback. Only **MediaType.MEDIA_TYPE_AUD** can be set.| 7706| preferredAudioLanguage<sup>13+</sup> | string | No| Preferred audio track language. Set this parameter based on service requirements in DASH scenarios. In non-DASH scenarios, this parameter is not supported, and you are advised to retain the default value.<br>**Atomic service API**: This API can be used in atomic services since API version 13.| 7707| preferredSubtitleLanguage<sup>13+</sup> | string | No| Preferred subtitle language. Set this parameter based on service requirements in DASH scenarios. In non-DASH scenarios, this parameter is not supported, and you are advised to retain the default value.<br>**Atomic service API**: This API can be used in atomic services since API version 13.| 7708 7709## AVScreenCaptureRecordPreset<sup>12+</sup> 7710 7711Enumerates the encoding and container formats used during screen capture. 7712 7713**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture 7714 7715| Name | Value | Description | 7716| --------------------------------- | ---- | -------------------------------------------- | 7717| SCREEN_RECORD_PRESET_H264_AAC_MP4 | 0 | The H.264 video encoding format, AAC audio encoding format, and MP4 container format are used.| 7718| SCREEN_RECORD_PRESET_H265_AAC_MP4 | 1 | The H.265 video encoding format, AAC audio encoding format, and MP4 container format are used.| 7719 7720## AVScreenCaptureStateCode<sup>12+</sup> 7721 7722Enumerates the screen capture states used in callbacks. 7723 7724**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture 7725 7726| Name | Value | Description | 7727| ---------------------------------------- | ---- | ------------------------ | 7728| SCREENCAPTURE_STATE_STARTED | 0 | Screen capture is started. | 7729| SCREENCAPTURE_STATE_CANCELED | 1 | Screen capture is canceled. | 7730| SCREENCAPTURE_STATE_STOPPED_BY_USER | 2 | Screen capture is manually stopped by the user. | 7731| SCREENCAPTURE_STATE_INTERRUPTED_BY_OTHER | 3 | Screen capture is interrupted by another screen capture. | 7732| SCREENCAPTURE_STATE_STOPPED_BY_CALL | 4 | Screen capture is interrupted by an incoming call. | 7733| SCREENCAPTURE_STATE_MIC_UNAVAILABLE | 5 | The microphone is unavailable during screen capture.| 7734| SCREENCAPTURE_STATE_MIC_MUTED_BY_USER | 6 | The microphone is muted by the user. | 7735| SCREENCAPTURE_STATE_MIC_UNMUTED_BY_USER | 7 | The microphone is unmuted by the user. | 7736| SCREENCAPTURE_STATE_ENTER_PRIVATE_SCENE | 8 | The system enters a privacy page during screen capture. | 7737| SCREENCAPTURE_STATE_EXIT_PRIVATE_SCENE | 9 | The system exits a privacy page during screen capture. | 7738| SCREENCAPTURE_STATE_STOPPED_BY_USER_SWITCHES | 10 | Screen capture is interrupted by system user switchover. | 7739 7740## AVScreenCaptureRecordConfig<sup>12+</sup> 7741 7742Defines the screen capture parameters. 7743 7744**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture 7745 7746| Name | Type | Mandatory| Description | 7747| ----------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 7748| fd | number | Yes | FD of the file output. | 7749| frameWidth | number | No | Video width, in px. The default value varies according to the display in use.| 7750| frameHeight | number | No | Video height, in px. The default value varies according to the display in use.| 7751| videoBitrate | number | No | Video bit rate. The default value is **10000000**. | 7752| 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.| 7753| 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.| 7754| audioBitrate | number | No | Audio bit rate. This value is used for both internal capture and external capture (using microphones). The default value is **96000**.| 7755| preset | [AVScreenCaptureRecordPreset](#avscreencapturerecordpreset12) | No | Encoding and container format used. The default value is **SCREEN_RECORD_PRESET_H264_AAC_MP4**.| 7756 7757## AVScreenCaptureRecorder<sup>12+</sup> 7758 7759Provides APIs to manage screen capture. Before calling any API in **AVScreenCaptureRecorder**, you must use [createAVScreenCaptureRecorder()](#mediacreateavscreencapturerecorder12) to create an **AVScreenCaptureRecorder** instance. 7760 7761### init<sup>12+</sup> 7762 7763init(config: AVScreenCaptureRecordConfig): Promise\<void> 7764 7765Initializes screen capture and sets screen capture parameters. This API uses a promise to return the result. 7766 7767**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture 7768 7769**Parameters** 7770 7771| Name| Type | Mandatory| Description | 7772| ------ | ------------------------------------------------------------ | ---- | ------------------------ | 7773| config | [AVScreenCaptureRecordConfig](#avscreencapturerecordconfig12) | Yes | Screen capture parameters to set.| 7774 7775**Return value** 7776 7777| Type | Description | 7778| -------------- | ----------------------------------- | 7779| Promise\<void> | Promise that returns no value.| 7780 7781**Error codes** 7782 7783| ID| Error Message | 7784| -------- | ---------------------------------------------- | 7785| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. Return by promise. | 7786| 5400103 | IO error. Return by promise. | 7787| 5400105 | Service died. Return by promise. | 7788 7789**Example** 7790 7791```ts 7792import { BusinessError } from '@kit.BasicServicesKit'; 7793 7794let avCaptureConfig: media.AVScreenCaptureRecordConfig = { 7795 fd: 0, // Before passing in an FD to this parameter, the file must be created by the caller and granted with the write permissions. 7796 frameWidth: 640, 7797 frameHeight: 480 7798 // Add other parameters. 7799} 7800 7801avScreenCaptureRecorder.init(avCaptureConfig).then(() => { 7802 console.info('Succeeded in initing avScreenCaptureRecorder'); 7803}).catch((err: BusinessError) => { 7804 console.info('Failed to init avScreenCaptureRecorder, error: ' + err.message); 7805}) 7806``` 7807 7808### startRecording<sup>12+</sup> 7809 7810startRecording(): Promise\<void> 7811 7812Starts screen capture. This API uses a promise to return the result. 7813 7814**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture 7815 7816**Return value** 7817 7818| Type | Description | 7819| -------------- | -------------------------------- | 7820| Promise\<void> | Promise that returns no value.| 7821 7822**Error codes** 7823 7824| ID| Error Message | 7825| -------- | -------------------------------- | 7826| 5400103 | IO error. Return by promise. | 7827| 5400105 | Service died. Return by promise. | 7828 7829**Example** 7830 7831```ts 7832import { BusinessError } from '@kit.BasicServicesKit'; 7833 7834avScreenCaptureRecorder.startRecording().then(() => { 7835 console.info('Succeeded in starting avScreenCaptureRecorder'); 7836}).catch((err: BusinessError) => { 7837 console.info('Failed to start avScreenCaptureRecorder, error: ' + err.message); 7838}) 7839``` 7840 7841### stopRecording<sup>12+</sup> 7842 7843stopRecording(): Promise\<void> 7844 7845Stops screen capture. This API uses a promise to return the result. 7846 7847**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture 7848 7849**Return value** 7850 7851| Type | Description | 7852| -------------- | --------------------------------- | 7853| Promise\<void> | Promise that returns no value.| 7854 7855**Error codes** 7856 7857| ID| Error Message | 7858| -------- | -------------------------------- | 7859| 5400103 | IO error. Return by promise. | 7860| 5400105 | Service died. Return by promise. | 7861 7862**Example** 7863 7864```ts 7865import { BusinessError } from '@kit.BasicServicesKit'; 7866 7867avScreenCaptureRecorder.stopRecording().then(() => { 7868 console.info('Succeeded in stopping avScreenCaptureRecorder'); 7869}).catch((err: BusinessError) => { 7870 console.info('Failed to stop avScreenCaptureRecorder, error: ' + err.message); 7871}) 7872``` 7873 7874### skipPrivacyMode<sup>12+</sup> 7875 7876skipPrivacyMode(windowIDs: Array\<number>): Promise\<void> 7877 7878During screen capture, the application can exempt its privacy windows from security purposes. This API uses a promise to return the result. 7879For example, if a user enters a password in this application during screen capture, the application will not display a black screen. 7880 7881**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture 7882 7883**Parameters** 7884 7885| Name| Type | Mandatory| Description | 7886| ------ | ------- | ---- | --------------------------------------------------------- | 7887| 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).| 7888 7889**Return value** 7890 7891| Type | Description | 7892| -------------- | -------------------------------- | 7893| Promise\<void> | Promise used to return the window IDs.| 7894 7895**Error codes** 7896 7897| ID| Error Message | 7898| -------- | -------------------------------- | 7899| 5400103 | IO error. Return by promise. | 7900| 5400105 | Service died. Return by promise. | 7901 7902**Example** 7903 7904```ts 7905import { BusinessError } from '@kit.BasicServicesKit'; 7906 7907let windowIDs = []; 7908avScreenCaptureRecorder.skipPrivacyMode(windowIDs).then(() => { 7909 console.info('Succeeded in skipping privacy mode'); 7910}).catch((err: BusinessError) => { 7911 console.info('Failed to skip privacy mode, error: ' + err.message); 7912}) 7913``` 7914 7915### setMicEnabled<sup>12+</sup> 7916 7917setMicEnabled(enable: boolean): Promise\<void> 7918 7919Enables or disables the microphone. This API uses a promise to return the result. 7920 7921**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture 7922 7923**Parameters** 7924 7925| Name| Type | Mandatory| Description | 7926| ------ | ------- | ---- | --------------------------------------------------------- | 7927| enable | boolean | Yes | Whether to enable or disable the microphone. The value **true** means to enable the microphone, and **false** means the opposite.| 7928 7929**Return value** 7930 7931| Type | Description | 7932| -------------- | --------------------------------------- | 7933| Promise\<void> | Promise that returns no value.| 7934 7935**Error codes** 7936 7937| ID| Error Message | 7938| -------- | -------------------------------- | 7939| 5400103 | IO error. Return by promise. | 7940| 5400105 | Service died. Return by promise. | 7941 7942**Example** 7943 7944```ts 7945import { BusinessError } from '@kit.BasicServicesKit'; 7946 7947avScreenCaptureRecorder.setMicEnabled(true).then(() => { 7948 console.info('Succeeded in setMicEnabled avScreenCaptureRecorder'); 7949}).catch((err: BusinessError) => { 7950 console.info('Failed to setMicEnabled avScreenCaptureRecorder, error: ' + err.message); 7951}) 7952``` 7953 7954### release<sup>12+</sup> 7955 7956release(): Promise\<void> 7957 7958Releases this **AVScreenCaptureRecorder** instance. This API uses a promise to return the result. 7959 7960**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture 7961 7962**Return value** 7963 7964| Type | Description | 7965| -------------- | --------------------------------- | 7966| Promise\<void> | Promise that returns no value.| 7967 7968**Error codes** 7969 7970| ID| Error Message | 7971| -------- | -------------------------------- | 7972| 5400103 | IO error. Return by promise. | 7973| 5400105 | Service died. Return by promise. | 7974 7975**Example** 7976 7977```ts 7978import { BusinessError } from '@kit.BasicServicesKit'; 7979 7980avScreenCaptureRecorder.release().then(() => { 7981 console.info('Succeeded in releasing avScreenCaptureRecorder'); 7982}).catch((err: BusinessError) => { 7983 console.info('Faile to release avScreenCaptureRecorder, error: ' + err.message); 7984}) 7985``` 7986 7987### on('stateChange')<sup>12+</sup> 7988 7989on(type: 'stateChange', callback: Callback\<AVScreenCaptureStateCode>): void 7990 7991Subscribes 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. 7992 7993**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture 7994 7995**Parameters** 7996 7997| Name | Type | Mandatory| Description | 7998| -------- | -------- | ---- | ------------------------------------------------------------ | 7999| type | string | Yes | Event type, which is **'stateChange'** in this case. | 8000| callback | function | Yes | Callback invoked when the event is triggered. [AVScreenCaptureStateCode](#avscreencapturestatecode12) indicates the new state.| 8001 8002**Example** 8003 8004```ts 8005avScreenCaptureRecorder.on('stateChange', (state: media.AVScreenCaptureStateCode) => { 8006 console.info('avScreenCaptureRecorder stateChange to ' + state); 8007}) 8008``` 8009 8010### on('error')<sup>12+</sup> 8011 8012on(type: 'error', callback: ErrorCallback): void 8013 8014Subscribes 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. 8015 8016**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture 8017 8018**Parameters** 8019 8020| Name | Type | Mandatory| Description | 8021| -------- | ------------- | ---- | --------------------------------------- | 8022| type | string | Yes | Event type, which is **'error'** in this case.| 8023| callback | [ErrorCallback](../apis-basic-services-kit/js-apis-base.md#errorcallback) | Yes | Callback invoked when the event is triggered. | 8024 8025**Error codes** 8026 8027| ID| Error Message | 8028| -------- | -------------------------------- | 8029| 201 | permission denied. | 8030| 5400103 | IO error. Return by ErrorCallback. | 8031| 5400105 | Service died. Return by ErrorCallback. | 8032 8033**Example** 8034 8035```ts 8036avScreenCaptureRecorder.on('error', (err: BusinessError) => { 8037 console.error('avScreenCaptureRecorder error:' + err.message); 8038}) 8039``` 8040 8041### off('stateChange')<sup>12+</sup> 8042 8043 off(type: 'stateChange', callback?: Callback\<AVScreenCaptureStateCode>): void 8044 8045Unsubscribes from screen capture state changes. You can specify a callback to cancel the specified subscription. 8046 8047**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture 8048 8049**Parameters** 8050 8051| Name | Type | Mandatory| Description | 8052| -------- | -------- | ---- | ------------------------------------------------------------ | 8053| type | string | Yes | Event type, which is **'stateChange'** in this case. | 8054| callback | function | No | Callback used for unsubscription. [AVScreenCaptureStateCode](#avscreencapturestatecode12) indicates the new state. If this parameter is not specified, the last subscription is canceled.| 8055 8056**Example** 8057 8058```ts 8059avScreenCaptureRecorder.off('stateChange'); 8060``` 8061 8062### off('error')<sup>12+</sup> 8063 8064off(type: 'error', callback?: ErrorCallback): void 8065 8066Unsubscribes from AVScreenCaptureRecorder errors. You can specify a callback to cancel the specified subscription. 8067 8068**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture 8069 8070**Parameters** 8071 8072| Name | Type | Mandatory| Description | 8073| -------- | -------- | ---- | ---------------------------------------------------------- | 8074| type | string | Yes | Event type, which is **'error'** in this case. | 8075| 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.| 8076 8077**Example** 8078 8079```ts 8080avScreenCaptureRecorder.off('error'); 8081``` 8082