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