1# Interface (AVPlayer) 2<!--Kit: Media Kit--> 3<!--Subsystem: Multimedia--> 4<!--Owner: @xushubo; @chennotfound--> 5<!--Designer: @dongyu_dy--> 6<!--Tester: @xchaosioda--> 7<!--Adviser: @zengyawen--> 8 9> **NOTE** 10> 11> - 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. 12> - The initial APIs of this interface are supported since API version 9. 13 14AVPlayer is a playback management class. It provides APIs to manage and play media assets. Before calling any API in AVPlayer, you must use [createAVPlayer()](arkts-apis-media-f.md#mediacreateavplayer9) to create an AVPlayer instance. 15 16Applications must properly manage AVPlayer instances according to their specific needs, creating and freeing them when necessary. Holding too many AVPlayer instances can lead to high memory usage, and in some cases, the system might terminate applications to free up resources. 17 18For 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). 19 20> **NOTE** 21> 22> When using the AVPlayer instance, you are advised to register the following callbacks to proactively obtain status changes: 23> 24> - [on('stateChange')](#onstatechange9): listens for AVPlayer state changes. 25> - [on('error')](#onerror9): listens for error events. 26 27## Modules to Import 28 29```ts 30import { media } from '@kit.MediaKit'; 31``` 32 33## Properties 34 35**System capability**: SystemCapability.Multimedia.Media.AVPlayer 36 37| Name | Type | Read-Only| Optional| Description | 38| --------------------------------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | 39| 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, AMR, and APE 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.| 40| fdSrc<sup>9+</sup> | [AVFileDescriptor](arkts-apis-media-i.md#avfiledescriptor9) | No | Yes | FD of the media asset. It can be set only when the AVPlayer is in the idle state.<br>This property 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, AMR, and APE 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.| 41| dataSrc<sup>10+</sup> | [AVDataSrcDescriptor](arkts-apis-media-i.md#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, AMR, and APE 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.| 42| 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#getxcomponentsurfaceid9).<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 43| loop<sup>9+</sup> | boolean | No | No | Whether to loop playback. **true** to loop, **false** otherwise. The default value is **false**. It is a dynamic property<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.| 44| videoScaleType<sup>9+</sup> | [VideoScaleType](arkts-apis-media-e.md#videoscaletype9) | No | Yes | Video scale type. The default value is **VIDEO_SCALE_TYPE_FIT**. It is a dynamic property<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.| 45| audioInterruptMode<sup>9+</sup> | [audio.InterruptMode](../apis-audio-kit/arkts-apis-audio-e.md#interruptmode9) | No | Yes | Audio interruption mode. The default value is **SHARE_MODE**. It is a dynamic property<br>and can be set only when the AVPlayer is in the prepared, playing, paused, or completed state.<br>To take effect, this property 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.| 46| audioRendererInfo<sup>10+</sup> | [audio.AudioRendererInfo](../apis-audio-kit/arkts-apis-audio-i.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/arkts-apis-audio-i.md#audiorendererinfo8).<br>This parameter can be set only when the AVPlayer is in the initialized state.<br>To take effect, this property 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.| 47| audioEffectMode<sup>10+</sup> | [audio.AudioEffectMode](../apis-audio-kit/arkts-apis-audio-e.md#audioeffectmode10) | No | Yes | Audio effect mode. The audio effect mode is a dynamic property 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.| 48| state<sup>9+</sup> | [AVPlayerState](arkts-apis-media-t.md#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. | 49| 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.| 50| 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.| 51| 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.| 52| 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.| 53 54## on('stateChange')<sup>9+</sup> 55 56on(type: 'stateChange', callback: OnAVPlayerStateChangeHandle): void 57 58Subscribes to AVPlayer state changes. 59 60**Atomic service API**: This API can be used in atomic services since API version 11. 61 62**System capability**: SystemCapability.Multimedia.Media.AVPlayer 63 64**Parameters** 65 66| Name | Type | Mandatory| Description | 67| -------- | -------- | ---- | ------------------------------------------------------------ | 68| type | string | Yes | Event type, which is **'stateChange'** in this case. This event can be triggered by both user operations and the system.| 69| callback | [OnAVPlayerStateChangeHandle](arkts-apis-media-t.md#onavplayerstatechangehandle12) | Yes | Callback invoked when the event is triggered.| 70 71**Example** 72 73```ts 74let avPlayer = await media.createAVPlayer(); 75avPlayer.on('stateChange', async (state: string, reason: media.StateChangeReason) => { 76 switch (state) { 77 case 'idle': 78 console.info('state idle called'); 79 break; 80 case 'initialized': 81 console.info('initialized prepared called'); 82 break; 83 case 'prepared': 84 console.info('state prepared called'); 85 break; 86 case 'playing': 87 console.info('state playing called'); 88 break; 89 case 'paused': 90 console.info('state paused called'); 91 break; 92 case 'completed': 93 console.info('state completed called'); 94 break; 95 case 'stopped': 96 console.info('state stopped called'); 97 break; 98 case 'released': 99 console.info('state released called'); 100 break; 101 case 'error': 102 console.info('state error called'); 103 break; 104 default: 105 console.info('unknown state :' + state); 106 break; 107 } 108}); 109``` 110 111## off('stateChange')<sup>9+</sup> 112 113off(type: 'stateChange', callback?: OnAVPlayerStateChangeHandle): void 114 115Unsubscribes from [AVPlayerState](arkts-apis-media-t.md#avplayerstate9) state changes. 116 117**Atomic service API**: This API can be used in atomic services since API version 11. 118 119**System capability**: SystemCapability.Multimedia.Media.AVPlayer 120 121**Parameters** 122 123| Name| Type | Mandatory| Description | 124| ------ | ------ | ---- | ----------------------------------------------------- | 125| type | string | Yes | Event type, which is **'stateChange'** in this case.| 126| callback | [OnAVPlayerStateChangeHandle](arkts-apis-media-t.md#onavplayerstatechangehandle12) | No | Callback invoked when the event is triggered.<br>This parameter is supported since API version 12.| 127 128**Example** 129 130```ts 131let avPlayer = await media.createAVPlayer(); 132avPlayer.off('stateChange'); 133``` 134 135## on('error')<sup>9+</sup> 136 137on(type: 'error', callback: ErrorCallback): void 138 139Subscribes to [AVPlayer](arkts-apis-media-AVPlayer.md) errors. This event is used only for error prompt and does not require the user to stop playback control. If the [AVPlayerState](arkts-apis-media-t.md#avplayerstate9) is also switched to error, call [reset()](#reset9) or [release()](#release9) to exit the playback. 140 141**Atomic service API**: This API can be used in atomic services since API version 11. 142 143**System capability**: SystemCapability.Multimedia.Media.AVPlayer 144 145**Parameters** 146 147| Name | Type | Mandatory| Description | 148| -------- | -------- | ---- | ------------------------------------------------------------ | 149| type | string | Yes | Event type, which is **'error'** in this case. This event can be triggered by both user operations and the system.| 150| callback | [ErrorCallback](../apis-basic-services-kit/js-apis-base.md#errorcallback) | Yes | Callback used to return the error code ID and error message.| 151 152**Error codes** 153 154For details about the error codes, see [Media Error Codes](errorcode-media.md). 155 156In 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. 157 158| ID| Error Message | 159| -------- | --------------------- | 160| 201 | Permission denied. | 161| 401 | The parameter check failed. | 162| 801 | Capability not supported. | 163| 5400101 | No memory. | 164| 5400102 | Operation not allowed.| 165| 5400103 | I/O error. | 166| 5400104 | Time out. | 167| 5400105 | Service died. | 168| 5400106 | Unsupported format. | 169| 5411001 | IO can not find host. | 170| 5411002 | IO connection timeout. | 171| 5411003 | IO network abnormal. | 172| 5411004 | IO network unavailable. | 173| 5411005 | IO no permission. | 174| 5411006 | IO request denied. | 175| 5411007 | IO resource not found. | 176| 5411008 | IO SSL client cert needed. | 177| 5411009 | IO SSL connect fail. | 178| 5411010 | IO SSL server cert untrusted. | 179| 5411011 | IO unsupported request. | 180 181**Example** 182 183```ts 184import { BusinessError } from '@kit.BasicServicesKit'; 185let avPlayer = await media.createAVPlayer(); 186avPlayer.on('error', (error: BusinessError) => { 187 console.info('error happened,and error message is :' + error.message); 188 console.info('error happened,and error code is :' + error.code); 189}); 190``` 191 192## off('error')<sup>9+</sup> 193 194off(type: 'error', callback?: ErrorCallback): void 195 196Unsubscribes from AVPlayer errors. 197 198**Atomic service API**: This API can be used in atomic services since API version 11. 199 200**System capability**: SystemCapability.Multimedia.Media.AVPlayer 201 202**Parameters** 203 204| Name| Type | Mandatory| Description | 205| ------ | ------ | ---- | ----------------------------------------- | 206| type | string | Yes | Event type, which is **'error'** in this case.| 207| 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.| 208 209**Example** 210 211```ts 212import { BusinessError } from '@kit.BasicServicesKit'; 213 214let avPlayer = await media.createAVPlayer(); 215avPlayer.off('error'); 216``` 217 218## setMediaSource<sup>12+</sup> 219 220setMediaSource(src:MediaSource, strategy?: PlaybackStrategy): Promise\<void> 221 222Sets 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. 223 224**Atomic service API**: This API can be used in atomic services since API version 12. 225 226**System capability**: SystemCapability.Multimedia.Media.AVPlayer 227 228**Parameters** 229 230| Name | Type | Mandatory| Description | 231| -------- | -------- | ---- | -------------------- | 232| src | [MediaSource](arkts-apis-media-MediaSource.md) | Yes | Source of the streaming media to pre-download.| 233| strategy | [PlaybackStrategy](arkts-apis-media-i.md#playbackstrategy12) | No | strategy for playing the pre-downloaded streaming media.| 234 235**Return value** 236 237| Type | Description | 238| -------------- | ------------------------------------------ | 239| Promise\<void> | Promise that returns no value.| 240 241**Error codes** 242 243For details about the error codes, see [Media Error Codes](errorcode-media.md). 244 245| ID| Error Message | 246| -------- | ----------------------------------------- | 247| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 248| 5400102 | Operation not allowed. Return by promise. | 249 250**Example** 251 252<!--code_no_check--> 253```ts 254let player = await media.createAVPlayer(); 255let headers: Record<string, string> = {"User-Agent" : "User-Agent-Value"}; 256let mediaSource : media.MediaSource = media.createMediaSourceWithUrl("http://xxx", headers); 257let playStrategy : media.PlaybackStrategy = { 258 preferredWidth: 1, 259 preferredHeight: 2, 260 preferredBufferDuration: 3, 261 preferredHdr: false, 262 preferredBufferDurationForPlaying: 1, 263 thresholdForAutoQuickPlay: 5 264}; 265player.setMediaSource(mediaSource, playStrategy); 266``` 267 268## setPlaybackStrategy<sup>12+</sup> 269 270setPlaybackStrategy(strategy: PlaybackStrategy): Promise\<void> 271 272Sets a playback strategy. This API can be called only when the AVPlayer is in the initialized state. 273 274**Atomic service API**: This API can be used in atomic services since API version 12. 275 276**System capability**: SystemCapability.Multimedia.Media.AVPlayer 277 278**Parameters** 279 280| Name | Type | Mandatory| Description | 281| -------- | -------- | ---- | -------------------- | 282| strategy | [PlaybackStrategy](arkts-apis-media-i.md#playbackstrategy12) | Yes | Playback strategy.| 283 284**Return value** 285 286| Type | Description | 287| -------------- | ------------------------------------ | 288| Promise\<void> | Promise that returns no value.| 289 290**Error codes** 291 292For details about the error codes, see [Media Error Codes](errorcode-media.md). 293 294| ID| Error Message | 295| -------- | ----------------------------------------- | 296| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. 2. Parameter verification failed. | 297| 5400102 | Operation not allowed. Return by promise. | 298 299**Example** 300 301<!--code_no_check--> 302```ts 303import { common } from '@kit.AbilityKit'; 304 305private context: Context | undefined; 306constructor(context: Context) { 307 this.context = context; // this.getUIContext().getHostContext(); 308} 309 310let player = await media.createAVPlayer(); 311let fileDescriptor = await this.context?.resourceManager.getRawFd('xxx.mp4'); 312player.fdSrc = fileDescriptor 313let playStrategy : media.PlaybackStrategy = { 314 preferredWidth: 1, 315 preferredHeight: 2, 316 preferredBufferDuration: 3, 317 preferredHdr: false, 318 mutedMediaType: media.MediaType.MEDIA_TYPE_AUD, 319 preferredBufferDurationForPlaying: 1, 320 thresholdForAutoQuickPlay: 5 321}; 322player.setPlaybackStrategy(playStrategy); 323``` 324 325## setPlaybackRange<sup>18+</sup> 326 327setPlaybackRange(startTimeMs: number, endTimeMs: number, mode?: SeekMode) : Promise\<void> 328 329Sets the playback range and seeks to the start position of the range based on the specified [SeekMode](arkts-apis-media-e.md#seekmode8). After the setting, only the content in the specified range of the audio or video file is played. This API uses a promise to return the result. It can be used in the initialized, prepared, paused, stopped, or completed state. 330 331**Atomic service API**: This API can be used in atomic services since API version 18. 332 333**System capability**: SystemCapability.Multimedia.Media.AVPlayer 334 335**Parameters** 336 337| Name | Type | Mandatory| Description | 338| -------- | ---------------------- | ---- | --------------------------- | 339| startTimeMs | number | Yes | Start position of the range, in ms. The value range is [0, duration). If **-1** is passed in, the system starts playing from position 0.| 340| endTimeMs | number | Yes | End position of the range, in ms. The value range is (startTimeMs, duration]. If **-1** is passed in, the system plays the content until it reaches the final part of the asset.| 341| mode | [SeekMode](arkts-apis-media-e.md#seekmode8) | No | Seek mode, which can be **SeekMode.SEEK_PREV_SYNC** or **SeekMode.SEEK_CLOSEST**.<br>The default value is **SeekMode.SEEK_PREV_SYNC**.| 342 343**Return value** 344 345| Type | Description | 346| -------------- | ------------------------------------ | 347| Promise\<void> | Promise that returns no value.| 348 349**Error codes** 350 351For details about the error codes, see [Media Error Codes](errorcode-media.md). 352 353| ID| Error Message | 354| -------- | ------------------------------------------ | 355| 401 | The parameter check failed. Return by promise. | 356| 5400102 | Operation not allowed. Return by promise. | 357 358**Example** 359 360```ts 361import { BusinessError } from '@kit.BasicServicesKit'; 362 363let avPlayer = await media.createAVPlayer(); 364avPlayer.setPlaybackRange(0, 6000, media.SeekMode.SEEK_CLOSEST).then(() => { 365 console.info('Succeeded setPlaybackRange'); 366}).catch((err: BusinessError) => { 367 console.error('Failed to setPlaybackRange' + err.message); 368}); 369``` 370 371## prepare<sup>9+</sup> 372 373prepare(callback: AsyncCallback\<void>): void 374 375Prepares 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. 376 377**Atomic service API**: This API can be used in atomic services since API version 11. 378 379**System capability**: SystemCapability.Multimedia.Media.AVPlayer 380 381**Parameters** 382 383| Name | Type | Mandatory| Description | 384| -------- | -------- | ---- | -------------------- | 385| callback | AsyncCallback\<void> | Yes | Callback used to return the result.| 386 387**Error codes** 388 389For details about the error codes, see [Media Error Codes](errorcode-media.md). 390 391| ID| Error Message | 392| -------- | ------------------------------------------ | 393| 5400102 | Operation not allowed. Return by callback. | 394| 5400106 | Unsupported format. Return by callback. | 395 396**Example** 397 398```ts 399import { BusinessError } from '@kit.BasicServicesKit'; 400 401let avPlayer = await media.createAVPlayer(); 402// Here is only an example. In real development, you must wait for the stateChange event to successfully trigger and reach the initialized state before proceeding. 403avPlayer.prepare((err: BusinessError) => { 404 if (err) { 405 console.error('Failed to prepare,error message is :' + err.message); 406 } else { 407 console.info('Succeeded in preparing'); 408 } 409}); 410``` 411 412## prepare<sup>9+</sup> 413 414prepare(): Promise\<void> 415 416Prepares 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. 417 418If your application frequently switches between short videos, you can create multiple AVPlayer objects to prepare the next video in advance, thereby improving the switching performance. For details, see [Smooth Switchover Between Online Short Videos](https://developer.huawei.com/consumer/en/doc/best-practices/bpta-smooth-switching). 419 420**Atomic service API**: This API can be used in atomic services since API version 11. 421 422**System capability**: SystemCapability.Multimedia.Media.AVPlayer 423 424**Return value** 425 426| Type | Description | 427| -------------- | ------------------------- | 428| Promise\<void> | Promise that returns no value.| 429 430**Error codes** 431 432For details about the error codes, see [Media Error Codes](errorcode-media.md). 433 434| ID| Error Message | 435| -------- | ----------------------------------------- | 436| 5400102 | Operation not allowed. Return by promise. | 437| 5400106 | Unsupported format. Return by promise. | 438 439**Example** 440 441```ts 442import { BusinessError } from '@kit.BasicServicesKit'; 443 444let avPlayer = await media.createAVPlayer(); 445// Here is only an example. In real development, you must wait for the stateChange event to successfully trigger and reach the initialized state before proceeding. 446avPlayer.prepare().then(() => { 447 console.info('Succeeded in preparing'); 448}, (err: BusinessError) => { 449 console.error('Failed to prepare,error message is :' + err.message); 450}); 451``` 452 453## setMediaMuted<sup>12+</sup> 454 455setMediaMuted(mediaType: MediaType, muted: boolean ): Promise\<void> 456 457Mutes or unmutes the audio. 458 459Starting from API version 20, this API can be used to mute or unmute the video display. 460 461This API can be called only when the AVPlayer is in the prepared, playing, paused, or completed state. 462 463**Atomic service API**: This API can be used in atomic services since API version 12. 464 465**System capability**: SystemCapability.Multimedia.Media.AVPlayer 466 467**Parameters** 468 469| Name | Type | Mandatory| Description | 470| -------- | -------- | ---- | -------------------- | 471| mediaType | [MediaType](arkts-apis-media-e.md#mediatype8) | Yes | Media type.| 472| muted | boolean | Yes | For API version 12 to 19, only audio formats are supported. This parameter specifies whether to mute or unmute the audio. **true** to mute, **false** otherwise.<br>Starting from API version 20, video formats are also supported. This parameter specifies whether to mute or unmute the video display. **true** to mute, **false** otherwise.| 473 474**Return value** 475 476| Type | Description | 477| -------------- | ------------------------- | 478| Promise\<void> | Promise that returns no value.| 479 480**Error codes** 481 482For details about the error codes, see [Media Error Codes](errorcode-media.md). 483 484| ID| Error Message| 485| -------- | ----------------------------------------- | 486| 401 | The parameter check failed. Return by promise. | 487| 5400102 | Operation not allowed. Return by promise. | 488 489**Example** 490 491```ts 492import { BusinessError } from '@kit.BasicServicesKit'; 493 494let avPlayer = await media.createAVPlayer(); 495// Here is only an example. In real development, you must wait for the stateChange event to successfully trigger and reach the initialized state before proceeding. 496avPlayer.prepare().then(() => { 497 console.info('Succeeded in preparing'); 498 avPlayer.setMediaMuted(media.MediaType.MEDIA_TYPE_AUD, true); 499}, (err: BusinessError) => { 500 console.error('Failed to prepare,error message is :' + err.message); 501}); 502``` 503 504## play<sup>9+</sup> 505 506play(callback: AsyncCallback\<void>): void 507 508Starts 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. 509 510**Atomic service API**: This API can be used in atomic services since API version 11. 511 512**System capability**: SystemCapability.Multimedia.Media.AVPlayer 513 514**Parameters** 515 516| Name | Type | Mandatory| Description | 517| -------- | -------- | ---- | -------------------- | 518| callback | AsyncCallback\<void> | Yes | Callback used to return the result.| 519 520**Error codes** 521 522For details about the error codes, see [Media Error Codes](errorcode-media.md). 523 524| ID| Error Message | 525| -------- | ------------------------------------------ | 526| 5400102 | Operation not allowed. Return by callback. | 527 528**Example** 529 530```ts 531import { BusinessError } from '@kit.BasicServicesKit'; 532 533let avPlayer = await media.createAVPlayer(); 534// Here is only an example. In real development, you must wait for the stateChange event to successfully trigger and reach the prepared, paused, or completed state before proceeding. 535avPlayer.play((err: BusinessError) => { 536 if (err) { 537 console.error('Failed to play,error message is :' + err.message); 538 } else { 539 console.info('Succeeded in playing'); 540 } 541}); 542``` 543 544## play<sup>9+</sup> 545 546play(): Promise\<void> 547 548Starts 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. 549 550**Atomic service API**: This API can be used in atomic services since API version 11. 551 552**System capability**: SystemCapability.Multimedia.Media.AVPlayer 553 554**Return value** 555 556| Type | Description | 557| -------------- | ------------------------- | 558| Promise\<void> | Promise that returns no value.| 559 560**Error codes** 561 562For details about the error codes, see [Media Error Codes](errorcode-media.md). 563 564| ID| Error Message | 565| -------- | ----------------------------------------- | 566| 5400102 | Operation not allowed. Return by promise. | 567 568**Example** 569 570```ts 571import { BusinessError } from '@kit.BasicServicesKit'; 572 573let avPlayer = await media.createAVPlayer(); 574// Here is only an example. In real development, you must wait for the stateChange event to successfully trigger and reach the prepared, paused, or completed state before proceeding. 575avPlayer.play().then(() => { 576 console.info('Succeeded in playing'); 577}, (err: BusinessError) => { 578 console.error('Failed to play,error message is :' + err.message); 579}); 580``` 581 582## pause<sup>9+</sup> 583 584pause(callback: AsyncCallback\<void>): void 585 586Pauses 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. 587 588**Atomic service API**: This API can be used in atomic services since API version 11. 589 590**System capability**: SystemCapability.Multimedia.Media.AVPlayer 591 592**Parameters** 593 594| Name | Type | Mandatory| Description | 595| -------- | -------- | ---- | -------------------- | 596| callback | AsyncCallback\<void> | Yes | Callback used to return the result.| 597 598**Error codes** 599 600For details about the error codes, see [Media Error Codes](errorcode-media.md). 601 602| ID| Error Message | 603| -------- | ------------------------------------------ | 604| 5400102 | Operation not allowed. Return by callback. | 605 606**Example** 607 608```ts 609import { BusinessError } from '@kit.BasicServicesKit'; 610 611let avPlayer = await media.createAVPlayer(); 612// Here is only an example. In real development, you must wait for the stateChange event to successfully trigger and reach the playing state before proceeding. 613avPlayer.pause((err: BusinessError) => { 614 if (err) { 615 console.error('Failed to pause,error message is :' + err.message); 616 } else { 617 console.info('Succeeded in pausing'); 618 } 619}); 620``` 621 622## pause<sup>9+</sup> 623 624pause(): Promise\<void> 625 626Pauses 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. 627 628**Atomic service API**: This API can be used in atomic services since API version 11. 629 630**System capability**: SystemCapability.Multimedia.Media.AVPlayer 631 632**Return value** 633 634| Type | Description | 635| -------------- | ------------------------- | 636| Promise\<void> | Promise that returns no value.| 637 638**Error codes** 639 640For details about the error codes, see [Media Error Codes](errorcode-media.md). 641 642| ID| Error Message | 643| -------- | ----------------------------------------- | 644| 5400102 | Operation not allowed. Return by promise. | 645 646**Example** 647 648```ts 649import { BusinessError } from '@kit.BasicServicesKit'; 650 651let avPlayer = await media.createAVPlayer(); 652// Here is only an example. In real development, you must wait for the stateChange event to successfully trigger and reach the playing state before proceeding. 653avPlayer.pause().then(() => { 654 console.info('Succeeded in pausing'); 655}, (err: BusinessError) => { 656 console.error('Failed to pause,error message is :' + err.message); 657}); 658``` 659 660## stop<sup>9+</sup> 661 662stop(callback: AsyncCallback\<void>): void 663 664Stops 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. 665 666**Atomic service API**: This API can be used in atomic services since API version 11. 667 668**System capability**: SystemCapability.Multimedia.Media.AVPlayer 669 670**Parameters** 671 672| Name | Type | Mandatory| Description | 673| -------- | -------- | ---- | -------------------- | 674| callback | AsyncCallback\<void> | Yes | Callback used to return the result.| 675 676**Error codes** 677 678For details about the error codes, see [Media Error Codes](errorcode-media.md). 679 680| ID| Error Message | 681| -------- | ------------------------------------------ | 682| 5400102 | Operation not allowed. Return by callback. | 683 684**Example** 685 686```ts 687import { BusinessError } from '@kit.BasicServicesKit'; 688 689let avPlayer = await media.createAVPlayer(); 690// Here is only an example. In real development, you must wait for the stateChange event to successfully trigger and reach the prepared, playing, paused, or completed state before proceeding. 691avPlayer.stop((err: BusinessError) => { 692 if (err) { 693 console.error('Failed to stop,error message is :' + err.message); 694 } else { 695 console.info('Succeeded in stopping'); 696 } 697}); 698``` 699 700## stop<sup>9+</sup> 701 702stop(): Promise\<void> 703 704Stops 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. 705 706**Atomic service API**: This API can be used in atomic services since API version 11. 707 708**System capability**: SystemCapability.Multimedia.Media.AVPlayer 709 710**Return value** 711 712| Type | Description | 713| -------------- | ------------------------- | 714| Promise\<void> | Promise that returns no value.| 715 716**Error codes** 717 718For details about the error codes, see [Media Error Codes](errorcode-media.md). 719 720| ID| Error Message | 721| -------- | ----------------------------------------- | 722| 5400102 | Operation not allowed. Return by promise. | 723 724**Example** 725 726```ts 727import { BusinessError } from '@kit.BasicServicesKit'; 728 729let avPlayer = await media.createAVPlayer(); 730// Here is only an example. In real development, you must wait for the stateChange event to successfully trigger and reach the prepared, playing, paused, or completed state before proceeding. 731avPlayer.stop().then(() => { 732 console.info('Succeeded in stopping'); 733}, (err: BusinessError) => { 734 console.error('Failed to stop,error message is :' + err.message); 735}); 736``` 737 738## reset<sup>9+</sup> 739 740reset(callback: AsyncCallback\<void>): void 741 742Resets 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. 743 744**Atomic service API**: This API can be used in atomic services since API version 11. 745 746**System capability**: SystemCapability.Multimedia.Media.AVPlayer 747 748**Parameters** 749 750| Name | Type | Mandatory| Description | 751| -------- | -------- | ---- | -------------------- | 752| callback | AsyncCallback\<void> | Yes | Callback used to return the result.| 753 754**Error codes** 755 756For details about the error codes, see [Media Error Codes](errorcode-media.md). 757 758| ID| Error Message | 759| -------- | ------------------------------------------ | 760| 5400102 | Operation not allowed. Return by callback. | 761 762**Example** 763 764```ts 765import { BusinessError } from '@kit.BasicServicesKit'; 766 767let avPlayer = await media.createAVPlayer(); 768// Here is only an example. In real development, you must wait for the stateChange event to successfully trigger and reach the initialized, prepared, playing, paused, completed, stopped, or error state before proceeding. 769avPlayer.reset((err: BusinessError) => { 770 if (err) { 771 console.error('Failed to reset,error message is :' + err.message); 772 } else { 773 console.info('Succeeded in resetting'); 774 } 775}); 776``` 777 778## reset<sup>9+</sup> 779 780reset(): Promise\<void> 781 782Resets 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. 783 784**Atomic service API**: This API can be used in atomic services since API version 11. 785 786**System capability**: SystemCapability.Multimedia.Media.AVPlayer 787 788**Return value** 789 790| Type | Description | 791| -------------- | ------------------------- | 792| Promise\<void> | Promise that returns no value.| 793 794**Error codes** 795 796For details about the error codes, see [Media Error Codes](errorcode-media.md). 797 798| ID| Error Message | 799| -------- | ----------------------------------------- | 800| 5400102 | Operation not allowed. Return by promise. | 801 802**Example** 803 804```ts 805import { BusinessError } from '@kit.BasicServicesKit'; 806 807let avPlayer = await media.createAVPlayer(); 808// Here is only an example. In real development, you must wait for the stateChange event to successfully trigger and reach the initialized, prepared, playing, paused, completed, stopped, or error state before proceeding. 809avPlayer.reset().then(() => { 810 console.info('Succeeded in resetting'); 811}, (err: BusinessError) => { 812 console.error('Failed to reset,error message is :' + err.message); 813}); 814``` 815 816## release<sup>9+</sup> 817 818release(callback: AsyncCallback\<void>): void 819 820Releases 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. 821 822**Atomic service API**: This API can be used in atomic services since API version 11. 823 824**System capability**: SystemCapability.Multimedia.Media.AVPlayer 825 826**Parameters** 827 828| Name | Type | Mandatory| Description | 829| -------- | -------- | ---- | -------------------- | 830| callback | AsyncCallback\<void> | Yes | Callback used to return the result.| 831 832**Error codes** 833 834For details about the error codes, see [Media Error Codes](errorcode-media.md). 835 836| ID| Error Message | 837| -------- | ------------------------------------------ | 838| 5400102 | Operation not allowed. Return by callback. | 839 840**Example** 841 842```ts 843import { BusinessError } from '@kit.BasicServicesKit'; 844 845let avPlayer = await media.createAVPlayer(); 846// Here is only an example. In real development, you must wait for the stateChange event to successfully trigger and reach a state other than released before proceeding. 847avPlayer.release((err: BusinessError) => { 848 if (err) { 849 console.error('Failed to release,error message is :' + err.message); 850 } else { 851 console.info('Succeeded in releasing'); 852 } 853}); 854``` 855 856## release<sup>9+</sup> 857 858release(): Promise\<void> 859 860Releases 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. 861 862**Atomic service API**: This API can be used in atomic services since API version 11. 863 864**System capability**: SystemCapability.Multimedia.Media.AVPlayer 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| 5400102 | Operation not allowed. Return by promise. | 879 880**Example** 881 882```ts 883import { BusinessError } from '@kit.BasicServicesKit'; 884 885let avPlayer = await media.createAVPlayer(); 886// Here is only an example. In real development, you must wait for the stateChange event to successfully trigger and reach a state other than released before proceeding. 887avPlayer.release().then(() => { 888 console.info('Succeeded in releasing'); 889}, (err: BusinessError) => { 890 console.error('Failed to release,error message is :' + err.message); 891}); 892``` 893 894## getTrackDescription<sup>9+</sup> 895 896getTrackDescription(callback: AsyncCallback\<Array\<MediaDescription>>): void 897 898Obtains 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. 899 900**Atomic service API**: This API can be used in atomic services since API version 11. 901 902**System capability**: SystemCapability.Multimedia.Media.AVPlayer 903 904**Parameters** 905 906| Name | Type | Mandatory| Description | 907| -------- | ------------------------------------------------------------ | ---- | -------------------------------------------- | 908| callback | AsyncCallback<Array<[MediaDescription](arkts-apis-media-i.md#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.| 909 910**Error codes** 911 912For details about the error codes, see [Media Error Codes](errorcode-media.md). 913 914| ID| Error Message | 915| -------- | ------------------------------------------ | 916| 5400102 | Operation not allowed. Return by callback. | 917 918**Example** 919 920```ts 921import { BusinessError } from '@kit.BasicServicesKit'; 922 923let avPlayer = await media.createAVPlayer(); 924// Here is only an example. In real development, you must wait for the stateChange event to successfully trigger and reach the prepared, playing, or paused state before proceeding. 925avPlayer.getTrackDescription((error: BusinessError, arrList: Array<media.MediaDescription>) => { 926 if ((arrList) != null) { 927 console.info('Succeeded in doing getTrackDescription'); 928 } else { 929 console.error(`Failed to do getTrackDescription, error:${error}`); 930 } 931}); 932``` 933 934## getTrackDescription<sup>9+</sup> 935 936getTrackDescription(): Promise\<Array\<MediaDescription>> 937 938Obtains 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. 939 940**Atomic service API**: This API can be used in atomic services since API version 11. 941 942**System capability**: SystemCapability.Multimedia.Media.AVPlayer 943 944**Return value** 945 946| Type | Description | 947| ------------------------------------------------------ | ------------------------------------------------- | 948| Promise<Array<[MediaDescription](arkts-apis-media-i.md#mediadescription8)>> | Promise used to return the MediaDescription array that holds the audio and video track information.| 949 950**Error codes** 951 952For details about the error codes, see [Media Error Codes](errorcode-media.md). 953 954| ID| Error Message | 955| -------- | ----------------------------------------- | 956| 5400102 | Operation not allowed. Return by promise. | 957 958**Example** 959 960```ts 961import { BusinessError } from '@kit.BasicServicesKit'; 962 963let avPlayer = await media.createAVPlayer(); 964// Here is only an example. In real development, you must wait for the stateChange event to successfully trigger and reach the prepared, playing, or paused state before proceeding. 965avPlayer.getTrackDescription().then((arrList: Array<media.MediaDescription>) => { 966 console.info('Succeeded in getting TrackDescription'); 967}).catch((error: BusinessError) => { 968 console.error(`Failed to get TrackDescription, error:${error}`); 969}); 970``` 971 972## getSelectedTracks<sup>12+</sup> 973 974getSelectedTracks(): Promise\<Array\<number>> 975 976Obtains 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. 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**Return value** 983 984| Type | Description | 985| ------------------------------------------------------ | ------------------------------------------------- | 986| Promise\<Array\<number>> | Promise used to return the index array.| 987 988**Error codes** 989 990For details about the error codes, see [Media Error Codes](errorcode-media.md). 991 992| ID| Error Message | 993| -------- | ----------------------------------------- | 994| 5400102 | Operation not allowed. | 995 996**Example** 997 998```ts 999import { BusinessError } from '@kit.BasicServicesKit'; 1000 1001let avPlayer = await media.createAVPlayer(); 1002// Here is only an example. In real development, you must wait for the stateChange event to successfully trigger and reach the prepared, playing, or paused state before proceeding. 1003avPlayer.getSelectedTracks().then((arrList: Array<number>) => { 1004 console.info('Succeeded in getting SelectedTracks'); 1005}).catch((error: BusinessError) => { 1006 console.error(`Failed to get SelectedTracks, error:${error}`); 1007}); 1008``` 1009 1010## getPlaybackInfo<sup>12+</sup> 1011 1012getPlaybackInfo(): Promise\<PlaybackInfo> 1013 1014Obtains 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. 1015 1016**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1017 1018**Return value** 1019 1020| Type | Description | 1021| ------------------------------------------------------ | ------------------------------------------------- | 1022| Promise<[PlaybackInfo](arkts-apis-media-i.md#playbackinfo12)> | Promise used to return **PlaybackInfo**.| 1023 1024**Example** 1025 1026```ts 1027import { BusinessError } from '@kit.BasicServicesKit'; 1028 1029let avPlayer: media.AVPlayer | undefined = undefined; 1030let playbackInfo: media.PlaybackInfo | undefined = undefined; 1031media.createAVPlayer(async (err: BusinessError, player: media.AVPlayer) => { 1032 if (player != null) { 1033 avPlayer = player; 1034 console.info(`Succeeded in creating AVPlayer`); 1035 if (avPlayer) { 1036 try { 1037 playbackInfo = await avPlayer.getPlaybackInfo(); 1038 console.info(`AVPlayer getPlaybackInfo = ${JSON.stringify(playbackInfo)}`); // Print PlaybackInfo. 1039 } catch (error) { 1040 console.error(`error = ${error}`); 1041 } 1042 } 1043 } else { 1044 console.error(`Failed to create AVPlayer, error message:${err.message}`); 1045 } 1046}); 1047``` 1048 1049## getPlaybackPosition<sup>18+</sup> 1050 1051getPlaybackPosition(): number 1052 1053Obtains the current playback position. This API can be called only when the AVPlayer is in the prepared, playing, paused, or completed state. 1054 1055**Atomic service API**: This API can be used in atomic services since API version 18. 1056 1057**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1058 1059**Return value** 1060 1061| Type | Description | 1062| ------------------------------------------------------ | ------------------------------------------------- | 1063| number | Current playback time, in milliseconds.| 1064 1065**Error codes** 1066 1067For details about the error codes, see [Media Error Codes](errorcode-media.md). 1068 1069| ID| Error Message | 1070| -------- | ----------------------------------------- | 1071| 5400102 | Operation not allowed. | 1072 1073**Example** 1074 1075```ts 1076import { BusinessError } from '@kit.BasicServicesKit'; 1077 1078let avPlayer = await media.createAVPlayer(); 1079// Here is only an example. In real development, you must wait for the stateChange event to successfully trigger and reach the initialized state before proceeding. 1080avPlayer.prepare().then(() => { 1081 console.info('Succeeded in preparing'); 1082 let playbackPosition: number = avPlayer.getPlaybackPosition(); 1083 console.info(`AVPlayer getPlaybackPosition== ${playbackPosition}`); 1084}, (err: BusinessError) => { 1085 console.error('Failed to prepare,error message is :' + err.message); 1086}); 1087``` 1088 1089## selectTrack<sup>12+</sup> 1090 1091selectTrack(index: number, mode?: SwitchMode): Promise\<void> 1092 1093Selects 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. 1094 1095**Atomic service API**: This API can be used in atomic services since API version 12. 1096 1097**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1098 1099**Parameters** 1100 1101| Name | Type | Mandatory| Description | 1102| -------- | -------- | ---- | -------------------- | 1103| index | number | Yes | Index of the track. You can call [getTrackDescription](#gettrackdescription9-1) to obtain all track information [MediaDescription](arkts-apis-media-i.md#mediadescription8) of the current resource.| 1104| mode | [SwitchMode](arkts-apis-media-e.md#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.| 1105 1106**Return value** 1107 1108| Type | Description | 1109| -------------- | ------------------------- | 1110| Promise\<void> | Promise that returns no value.| 1111 1112**Error codes** 1113 1114For details about the error codes, see [Media Error Codes](errorcode-media.md). 1115 1116| ID| Error Message | 1117| -------- | ----------------------------------------- | 1118| 401 | The parameter check failed. Return by promise. | 1119| 5400102 | Operation not allowed. Return by promise. | 1120 1121**Example** 1122 1123<!--code_no_check--> 1124```ts 1125import { BusinessError } from '@kit.BasicServicesKit'; 1126 1127let avPlayer: media.AVPlayer = await media.createAVPlayer(); 1128let audioTrackIndex: Object = 0; 1129avPlayer.getTrackDescription((error: BusinessError, arrList: Array<media.MediaDescription>) => { 1130 if (arrList != null) { 1131 for (let i = 0; i < arrList.length; i++) { 1132 if (i != 0) { 1133 // Obtain the audio track list. 1134 audioTrackIndex = arrList[i][media.MediaDescriptionKey.MD_KEY_TRACK_INDEX]; 1135 } 1136 } 1137 } else { 1138 console.error(`Failed to get TrackDescription, error:${error}`); 1139 } 1140}); 1141 1142// Select an audio track. 1143avPlayer.selectTrack(parseInt(audioTrackIndex.toString())); 1144``` 1145 1146## deselectTrack<sup>12+</sup> 1147 1148deselectTrack(index: number): Promise\<void> 1149 1150Deselects 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. 1151 1152**Atomic service API**: This API can be used in atomic services since API version 12. 1153 1154**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1155 1156**Parameters** 1157 1158| Name | Type | Mandatory| Description | 1159| -------- | -------- | ---- | -------------------- | 1160| index | number | Yes | Track index, which is obtained from [MediaDescription](arkts-apis-media-i.md#mediadescription8) by calling [getTrackDescription](#gettrackdescription9-1).| 1161 1162**Return value** 1163 1164| Type | Description | 1165| -------------- | ------------------------- | 1166| Promise\<void> | Promise that returns no value.| 1167 1168**Error codes** 1169 1170For details about the error codes, see [Media Error Codes](errorcode-media.md). 1171 1172| ID| Error Message | 1173| -------- | ----------------------------------------- | 1174| 401 | The parameter check failed. Return by promise. | 1175| 5400102 | Operation not allowed. Return by promise. | 1176 1177**Example** 1178 1179<!--code_no_check--> 1180```ts 1181import { BusinessError } from '@kit.BasicServicesKit'; 1182 1183let avPlayer: media.AVPlayer = await media.createAVPlayer(); 1184let audioTrackIndex: Object = 0; 1185avPlayer.getTrackDescription((error: BusinessError, arrList: Array<media.MediaDescription>) => { 1186 if (arrList != null) { 1187 for (let i = 0; i < arrList.length; i++) { 1188 if (i != 0) { 1189 // Obtain the audio track list. 1190 audioTrackIndex = arrList[i][media.MediaDescriptionKey.MD_KEY_TRACK_INDEX]; 1191 } 1192 } 1193 } else { 1194 console.error(`Failed to get TrackDescription, error:${error}`); 1195 } 1196}); 1197 1198// Select an audio track. 1199avPlayer.selectTrack(parseInt(audioTrackIndex.toString())); 1200// Deselect the audio track and restore to the default audio track. 1201avPlayer.deselectTrack(parseInt(audioTrackIndex.toString())); 1202``` 1203 1204## setDecryptionConfig<sup>11+</sup> 1205 1206setDecryptionConfig(mediaKeySession: drm.MediaKeySession, secureVideoPath: boolean): void 1207 1208Sets 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. 1209 1210**Atomic service API**: This API can be used in atomic services since API version 12. 1211 1212**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1213 1214**Parameters** 1215 1216| Name | Type | Mandatory| Description | 1217| -------- | ------------------------------------------------------------ | ---- | -------------------------------------------- | 1218| mediaKeySession | [drm.MediaKeySession](../apis-drm-kit/arkts-apis-drm-MediaKeySession.md) | Yes | Decryption session.| 1219| secureVideoPath | boolean | Yes| Secure video channel. **true** if a secure video channel is selected, **false** otherwise.| 1220 1221**Error codes** 1222 1223For details about the error codes, see [Media Error Codes](errorcode-media.md). 1224 1225| ID| Error Message | 1226| -------- | ----------------------------------------- | 1227| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 1228 1229**Example** 1230 1231For details about the DRM module, see [@ohos.multimedia.drm](../apis-drm-kit/arkts-apis-drm.md). 1232 1233```ts 1234import { drm } from '@kit.DrmKit'; 1235 1236let avPlayer = await media.createAVPlayer(); 1237// Create a media key system. 1238let keySystem:drm.MediaKeySystem = drm.createMediaKeySystem('com.clearplay.drm'); 1239// Create a media key session. 1240let keySession:drm.MediaKeySession = keySystem.createMediaKeySession(drm.ContentProtectionLevel.CONTENT_PROTECTION_LEVEL_SW_CRYPTO); 1241// Generate a media key request and set the response to the media key request. 1242// Flag indicating whether a secure video channel is used. 1243let secureVideoPath:boolean = false; 1244// Set the decryption configuration. 1245avPlayer.setDecryptionConfig(keySession, secureVideoPath); 1246``` 1247 1248## getMediaKeySystemInfos<sup>11+</sup> 1249 1250getMediaKeySystemInfos(): Array\<drm.MediaKeySystemInfo> 1251 1252Obtains 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. 1253 1254**Atomic service API**: This API can be used in atomic services since API version 12. 1255 1256**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1257 1258**Return value** 1259 1260| Type | Description | 1261| ------------------------------------------------------ | ------------------------------------------------- | 1262| Array<[drm.MediaKeySystemInfo](../apis-drm-kit/arkts-apis-drm-i.md#mediakeysysteminfo)> | Array of MediaKeySystemInfo objects, each of which contains the **uuid** and **pssh** properties.| 1263 1264**Example** 1265 1266```ts 1267import { drm } from '@kit.DrmKit'; 1268 1269let avPlayer = await media.createAVPlayer(); 1270// Here is only an example. In real development, you must wait for the mediaKeySystemInfoUpdate event to successfully trigger before proceeding. 1271const infos = avPlayer.getMediaKeySystemInfos(); 1272console.info('GetMediaKeySystemInfos count: ' + infos.length); 1273for (let i = 0; i < infos.length; i++) { 1274 console.info('GetMediaKeySystemInfos uuid: ' + infos[i]["uuid"]); 1275 console.info('GetMediaKeySystemInfos pssh: ' + infos[i]["pssh"]); 1276} 1277``` 1278 1279## seek<sup>9+</sup> 1280 1281seek(timeMs: number, mode?:SeekMode): void 1282 1283Seeks 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. 1284This API is not supported in live mode. 1285 1286**Atomic service API**: This API can be used in atomic services since API version 11. 1287 1288**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1289 1290**Parameters** 1291 1292| Name| Type | Mandatory| Description | 1293| ------ | ---------------------- | ---- | ------------------------------------------------------------ | 1294| timeMs | number | Yes | Position to seek to, in ms. The value range is [0, [duration](#properties)]. In SEEK_CONTINUOU mode, the value **-1** can be used to indicate the end of SEEK_CONTINUOUS mode.| 1295| mode | [SeekMode](arkts-apis-media-e.md#seekmode8) | No | Seek mode based on the video I frame. The default value is **SEEK_PREV_SYNC**. **Set this parameter only for video playback.**| 1296 1297**Example** 1298 1299```ts 1300let avPlayer = await media.createAVPlayer(); 1301let seekTime: number = 1000; 1302// Here is only an example. In real development, you must wait for the stateChange event to successfully trigger and reach the prepared, playing, paused, or completed state before proceeding. 1303avPlayer.seek(seekTime, media.SeekMode.SEEK_PREV_SYNC); 1304``` 1305 1306```ts 1307// Use SEEK_CONTINUOUS with the onChange callback of the Slider. When slideMode is Moving, it triggers continuous seeking during the drag. 1308let avPlayer = await media.createAVPlayer(); 1309let slideMovingTime: number = 2000; 1310// Here is only an example. In real development, you must wait for the stateChange event to successfully trigger and reach the prepared, playing, paused, or completed state before proceeding. 1311avPlayer.seek(slideMovingTime, media.SeekMode.SEEK_CONTINUOUS); 1312 1313// To end the seek when slideMode is End, call seek(-1, media.SeekMode.SEEK_CONTINUOUS). 1314avPlayer.seek(-1, media.SeekMode.SEEK_CONTINUOUS); 1315``` 1316 1317## isSeekContinuousSupported<sup>18+</sup> 1318 1319isSeekContinuousSupported() : boolean 1320 1321Checks whether the media source supports [seek](#seek9) in SEEK_CONTINUOUS mode (specified by [SeekMode](arkts-apis-media-e.md#seekmode8)). The actual value is returned when this API is called in the prepared, playing, paused, or completed state. The value **false** is returned if it is called in other states. For devices that do not support the seek operation in SEEK_CONTINUOUS mode, **false** is returned. 1322 1323**Atomic service API**: This API can be used in atomic services since API version 18. 1324 1325**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1326 1327**Return value** 1328 1329| Type | Description | 1330| -------------- | ------------------------------------------ | 1331| boolean | Check result for the support of the seek operation in SEEK_CONTINUOUS mode. **true** if supported, **false** otherwise.| 1332 1333**Example** 1334 1335```ts 1336let avPlayer = await media.createAVPlayer(); 1337// Here is only an example. In real development, you must wait for the stateChange event to successfully trigger and reach the prepared, playing, paused, or completed state before proceeding. 1338let isSupported = avPlayer.isSeekContinuousSupported(); 1339``` 1340 1341## on('seekDone')<sup>9+</sup> 1342 1343on(type: 'seekDone', callback: Callback\<number>): void 1344 1345Subscribes to the event to check whether the seek operation takes effect. 1346 1347**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1348 1349**Atomic service API**: This API can be used in atomic services since API version 11. 1350 1351**Parameters** 1352 1353| Name | Type | Mandatory| Description | 1354| -------- | -------- | ---- | ------------------------------------------------------------ | 1355| type | string | Yes | Event type, which is **'seekDone'** in this case. This event is triggered each time **seek()** is called, except in SEEK_CONTINUOUS mode.| 1356| 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](arkts-apis-media-e.md#seekmode8) may cause the actual position to be different from that requested by the user. The exact position can be obtained from the **currentTime** property. The time in this callback only means that the requested seek operation is complete.| 1357 1358**Example** 1359 1360```ts 1361let avPlayer = await media.createAVPlayer(); 1362avPlayer.on('seekDone', (seekDoneTime:number) => { 1363 console.info('seekDone called,and seek time is:' + seekDoneTime); 1364}); 1365``` 1366 1367## off('seekDone')<sup>9+</sup> 1368 1369off(type: 'seekDone', callback?: Callback\<number>): void 1370 1371Unsubscribes from the event that checks whether the seek operation takes effect. 1372 1373**Atomic service API**: This API can be used in atomic services since API version 11. 1374 1375**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1376 1377**Parameters** 1378 1379| Name| Type | Mandatory| Description | 1380| ------ | ------ | ---- | ---------------------------------------------------- | 1381| type | string | Yes | Event type, which is **'seekDone'** in this case.| 1382| 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](arkts-apis-media-e.md#seekmode8) may cause the actual position to be different from that requested by the user. The exact position can be obtained from the **currentTime** property. The time in this callback only means that the requested seek operation is complete.<br>This parameter is supported since API version 12.| 1383 1384**Example** 1385 1386```ts 1387let avPlayer = await media.createAVPlayer(); 1388avPlayer.off('seekDone'); 1389``` 1390 1391## setSpeed<sup>9+</sup> 1392 1393setSpeed(speed: PlaybackSpeed): void 1394 1395Sets 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. 1396This API is not supported in live mode. 1397 1398**Atomic service API**: This API can be used in atomic services since API version 12. 1399 1400**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1401 1402**Parameters** 1403 1404| Name| Type | Mandatory| Description | 1405| ------ | -------------------------------- | ---- | ------------------ | 1406| speed | [PlaybackSpeed](arkts-apis-media-e.md#playbackspeed8) | Yes | Playback speed to set.| 1407 1408**Example** 1409 1410```ts 1411let avPlayer = await media.createAVPlayer(); 1412// Here is only an example. In real development, you must wait for the stateChange event to successfully trigger and reach the prepared, playing, paused, or completed state before proceeding. 1413avPlayer.setSpeed(media.PlaybackSpeed.SPEED_FORWARD_2_00_X); 1414``` 1415 1416## on('speedDone')<sup>9+</sup> 1417 1418on(type: 'speedDone', callback: Callback\<number>): void 1419 1420Subscribes to the event to check whether the playback speed is successfully set. 1421 1422**Atomic service API**: This API can be used in atomic services since API version 12. 1423 1424**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1425 1426**Parameters** 1427 1428| Name | Type | Mandatory| Description | 1429| -------- | -------- | ---- | ------------------------------------------------------------ | 1430| type | string | Yes | Event type, which is **'speedDone'** in this case. This event is triggered each time **setSpeed()** is called.| 1431| 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](arkts-apis-media-e.md#playbackspeed8).| 1432 1433**Example** 1434 1435```ts 1436let avPlayer = await media.createAVPlayer(); 1437avPlayer.on('speedDone', (speed:number) => { 1438 console.info('speedDone called,and speed value is:' + speed); 1439}); 1440``` 1441 1442## off('speedDone')<sup>9+</sup> 1443 1444off(type: 'speedDone', callback?: Callback\<number>): void 1445 1446Unsubscribes from the event that checks whether the playback speed is successfully set. 1447 1448**Atomic service API**: This API can be used in atomic services since API version 19. 1449 1450**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1451 1452**Parameters** 1453 1454| Name| Type | Mandatory| Description | 1455| ------ | ------ | ---- | --------------------------------------------------------- | 1456| type | string | Yes | Event type, which is **'speedDone'** in this case.| 1457| 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](arkts-apis-media-e.md#playbackspeed8).<br>This parameter is supported since API version 12.| 1458 1459**Example** 1460 1461```ts 1462let avPlayer = await media.createAVPlayer(); 1463avPlayer.off('speedDone'); 1464``` 1465 1466## setPlaybackRate<sup>20+</sup> 1467 1468setPlaybackRate(rate: number): void 1469 1470Sets the playback rate. This API can be called only when the AVPlayer is in the prepared, playing, paused, or completed state. The value range is [0.125, 4.0]. You can check whether the setting takes effect through the [playbackRateDone](#onplaybackratedone20) event. 1471 1472> **NOTE** 1473> 1474> This API is not supported in live mode. 1475 1476**Atomic service API**: This API can be used in atomic services since API version 20. 1477 1478**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1479 1480**Parameters** 1481 1482| Name| Type | Mandatory| Description | 1483| ------ | -------------------------------- | ---- | ------------------ | 1484| rate | number | Yes | Playback rate, which is in the range [0.125, 4.0].| 1485 1486**Error codes** 1487 1488For details about the error codes, see [Media Error Codes](errorcode-media.md). 1489 1490| ID| Error Message | 1491| -------- | ------------------------------------------ | 1492| 5400108 | The parameter check failed, parameter value out of range. | 1493| 5400102 | Operation not allowed, if invalid state or live stream. | 1494 1495**Example** 1496 1497```ts 1498let avPlayer = await media.createAVPlayer(); 1499// Here is only an example. In real development, you must wait for the stateChange event to successfully trigger and reach the prepared, playing, paused, or completed state before proceeding. 1500avPlayer.setPlaybackRate(2.0); 1501``` 1502 1503## on('playbackRateDone')<sup>20+</sup> 1504 1505on(type: 'playbackRateDone', callback: OnPlaybackRateDone): void 1506 1507Subscribes to the event indicating that the playback rate set by calling [setPlaybackRate](#setplaybackrate20) is applied. 1508 1509**Atomic service API**: This API can be used in atomic services since API version 20. 1510 1511**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1512 1513**Parameters** 1514 1515| Name | Type | Mandatory| Description | 1516| -------- | -------- | ---- | ------------------------------------------------------------ | 1517| type | string | Yes | Event type, which is **'playbackRateDone'** in this case. This event is triggered each time **setPlaybackRate** is called.| 1518| callback | [OnPlaybackRateDone](#onplaybackratedone20) | Yes | Callback invoked when the event is triggered. It reports the new playback rate.<br>This parameter is supported since API version 20.| 1519 1520**Example** 1521 1522```ts 1523let avPlayer = await media.createAVPlayer(); 1524avPlayer.on('playbackRateDone', (rate:number) => { 1525 console.info('playbackRateDone called,and rate value is:' + rate); 1526}); 1527``` 1528 1529## off('playbackRateDone')<sup>20+</sup> 1530 1531off(type: 'playbackRateDone', callback?: OnPlaybackRateDone): void 1532 1533Unsubscribes from the event indicating that the playback rate set by calling [setPlaybackRate](#setplaybackrate20) is applied. 1534 1535**Atomic service API**: This API can be used in atomic services since API version 20. 1536 1537**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1538 1539**Parameters** 1540 1541| Name| Type | Mandatory| Description | 1542| ------ | ------ | ---- | --------------------------------------------------------- | 1543| type | string | Yes | Event type, which is **'playbackRateDone'** in this case.| 1544| callback | [OnPlaybackRateDone](#onplaybackratedone20) | No | Callback invoked when the event is triggered. It reports the new playback rate. If this parameter is specified, only the specified callback is unregistered. Otherwise, all callbacks associated with the specified event will be unregistered.<br>This parameter is supported since API version 20.| 1545 1546**Example** 1547 1548```ts 1549let avPlayer = await media.createAVPlayer(); 1550avPlayer.off('playbackRateDone'); 1551``` 1552 1553## setBitrate<sup>9+</sup> 1554 1555setBitrate(bitrate: number): void 1556 1557Sets 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. 1558 1559**Atomic service API**: This API can be used in atomic services since API version 12. 1560 1561**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1562 1563**Parameters** 1564 1565| Name | Type | Mandatory| Description | 1566| ------- | ------ | ---- | ------------------------------------------------------------ | 1567| 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.| 1568 1569**Example** 1570 1571```ts 1572let avPlayer = await media.createAVPlayer(); 1573let bitrate: number = 96000; 1574// Here is only an example. In real development, you must wait for the stateChange event to successfully trigger and reach the prepared, playing, paused, or completed state before proceeding. 1575avPlayer.setBitrate(bitrate); 1576``` 1577 1578## on('bitrateDone')<sup>9+</sup> 1579 1580on(type: 'bitrateDone', callback: Callback\<number>): void 1581 1582Subscribes to the event to check whether the bit rate is successfully set. 1583 1584**Atomic service API**: This API can be used in atomic services since API version 12. 1585 1586**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1587 1588**Parameters** 1589 1590| Name | Type | Mandatory| Description | 1591| -------- | -------- | ---- | ------------------------------------------------------------ | 1592| type | string | Yes | Event type, which is **'bitrateDone'** in this case. This event is triggered each time **setBitrate()** is called.| 1593| callback | Callback\<number> | Yes | Callback invoked when the event is triggered. It reports the effective bit rate. | 1594 1595**Example** 1596 1597```ts 1598let avPlayer = await media.createAVPlayer(); 1599avPlayer.on('bitrateDone', (bitrate:number) => { 1600 console.info('bitrateDone called,and bitrate value is:' + bitrate); 1601}); 1602``` 1603 1604## off('bitrateDone')<sup>9+</sup> 1605 1606off(type: 'bitrateDone', callback?: Callback\<number>): void 1607 1608Unsubscribes from the event that checks whether the bit rate is successfully set. 1609 1610**Atomic service API**: This API can be used in atomic services since API version 19. 1611 1612**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1613 1614**Parameters** 1615 1616| Name| Type | Mandatory| Description | 1617| ------ | ------ | ---- | ------------------------------------------------------------ | 1618| type | string | Yes | Event type, which is **'bitrateDone'** in this case.| 1619| 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. | 1620 1621**Example** 1622 1623```ts 1624let avPlayer = await media.createAVPlayer(); 1625avPlayer.off('bitrateDone'); 1626``` 1627 1628## on('availableBitrates')<sup>9+</sup> 1629 1630on(type: 'availableBitrates', callback: Callback\<Array\<number>>): void 1631 1632Subscribes to available bit rates of HLS/DASH streams. This event is reported only after the AVPlayer switches to the prepared state. 1633 1634**Atomic service API**: This API can be used in atomic services since API version 12. 1635 1636**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1637 1638**Parameters** 1639 1640| Name | Type | Mandatory| Description | 1641| -------- | -------- | ---- | ------------------------------------------------------------ | 1642| type | string | Yes | Event type, which is **'availableBitrates'** in this case. This event is triggered once after the AVPlayer switches to the prepared state.| 1643| 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.| 1644 1645**Example** 1646 1647```ts 1648let avPlayer = await media.createAVPlayer(); 1649avPlayer.on('availableBitrates', (bitrates: Array<number>) => { 1650 console.info('availableBitrates called,and availableBitrates length is:' + bitrates.length); 1651}); 1652``` 1653 1654## off('availableBitrates')<sup>9+</sup> 1655 1656off(type: 'availableBitrates', callback?: Callback\<Array\<number>>): void 1657 1658Unsubscribes from available bit rates of HLS/DASH streams. This event is reported after [prepare](#prepare9) is called. 1659 1660**Atomic service API**: This API can be used in atomic services since API version 12. 1661 1662**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1663 1664**Parameters** 1665 1666| Name| Type | Mandatory| Description | 1667| ------ | ------ | ---- | ------------------------------------------------------------ | 1668| type | string | Yes | Event type, which is **'availableBitrates'** in this case.| 1669| 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.| 1670 1671**Example** 1672 1673```ts 1674let avPlayer = await media.createAVPlayer(); 1675avPlayer.off('availableBitrates'); 1676``` 1677 1678 1679## on('mediaKeySystemInfoUpdate')<sup>11+</sup> 1680 1681on(type: 'mediaKeySystemInfoUpdate', callback: Callback\<Array\<drm.MediaKeySystemInfo>>): void 1682 1683Subscribes to media key system information changes. 1684 1685**Atomic service API**: This API can be used in atomic services since API version 12. 1686 1687**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1688 1689**Parameters** 1690 1691| Name | Type | Mandatory| Description | 1692| -------- | -------- | ---- | ------------------------------------------------------------ | 1693| 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.| 1694| callback | Callback\<Array\<drm.[MediaKeySystemInfo](../apis-drm-kit/arkts-apis-drm-i.md#mediakeysysteminfo)>> | Yes | Callback invoked when the event is triggered. It reports a **MediaKeySystemInfo** array.| 1695 1696**Example** 1697 1698```ts 1699import { drm } from '@kit.DrmKit'; 1700 1701let avPlayer = await media.createAVPlayer(); 1702avPlayer.on('mediaKeySystemInfoUpdate', (mediaKeySystemInfo: Array<drm.MediaKeySystemInfo>) => { 1703 for (let i = 0; i < mediaKeySystemInfo.length; i++) { 1704 console.info('mediaKeySystemInfoUpdate happened uuid: ' + mediaKeySystemInfo[i]["uuid"]); 1705 console.info('mediaKeySystemInfoUpdate happened pssh: ' + mediaKeySystemInfo[i]["pssh"]); 1706 } 1707}); 1708``` 1709 1710## off('mediaKeySystemInfoUpdate')<sup>11+</sup> 1711 1712off(type: 'mediaKeySystemInfoUpdate', callback?: Callback\<Array\<drm.MediaKeySystemInfo>>): void; 1713 1714Unsubscribes from media key system information changes. 1715 1716**Atomic service API**: This API can be used in atomic services since API version 12. 1717 1718**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1719 1720**Parameters** 1721 1722| Name| Type | Mandatory| Description | 1723| ------ | ------ | ---- | ------------------------------------------------------------ | 1724| type | string | Yes | Event type, which is **'mediaKeySystemInfoUpdate'** in this case.| 1725| callback | Callback\<Array\<drm.[MediaKeySystemInfo](../apis-drm-kit/arkts-apis-drm-i.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.| 1726 1727**Example** 1728 1729```ts 1730let avPlayer = await media.createAVPlayer(); 1731avPlayer.off('mediaKeySystemInfoUpdate'); 1732``` 1733 1734## setVolume<sup>9+</sup> 1735 1736setVolume(volume: number): void 1737 1738Sets 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. 1739 1740**Atomic service API**: This API can be used in atomic services since API version 12. 1741 1742**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1743 1744**Parameters** 1745 1746| Name| Type | Mandatory| Description | 1747| ------ | ------ | ---- | ------------------------------------------------------------ | 1748| volume | number | Yes | Relative volume. The value ranges from 0.00 to 1.00. The value **1.00** indicates the maximum volume (100%).| 1749 1750**Example** 1751 1752```ts 1753let avPlayer = await media.createAVPlayer(); 1754let volume: number = 1.0; 1755avPlayer.setVolume(volume); 1756``` 1757 1758## on('volumeChange')<sup>9+</sup> 1759 1760on(type: 'volumeChange', callback: Callback\<number>): void 1761 1762Subscribes to the event to check whether the volume is successfully set. 1763 1764**Atomic service API**: This API can be used in atomic services since API version 12. 1765 1766**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1767 1768**Parameters** 1769 1770| Name | Type | Mandatory| Description | 1771| -------- | -------- | ---- | ------------------------------------------------------------ | 1772| type | string | Yes | Event type, which is **'volumeChange'** in this case. This event is triggered each time **setVolume()** is called.| 1773| callback | Callback\<number> | Yes | Callback invoked when the event is triggered. It reports the effective volume. | 1774 1775**Example** 1776 1777```ts 1778let avPlayer = await media.createAVPlayer(); 1779avPlayer.on('volumeChange', (vol: number) => { 1780 console.info('volumeChange called,and new volume is :' + vol); 1781}); 1782``` 1783 1784## off('volumeChange')<sup>9+</sup> 1785 1786off(type: 'volumeChange', callback?: Callback\<number>): void 1787 1788Unsubscribes from the event that checks whether the volume is successfully set. 1789 1790**Atomic service API**: This API can be used in atomic services since API version 19. 1791 1792**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1793 1794**Parameters** 1795 1796| Name| Type | Mandatory| Description | 1797| ------ | ------ | ---- | ------------------------------------------------------------ | 1798| type | string | Yes | Event type, which is **'volumeChange'** in this case.| 1799| 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. | 1800 1801**Example** 1802 1803```ts 1804let avPlayer = await media.createAVPlayer(); 1805avPlayer.off('volumeChange'); 1806``` 1807 1808## on('endOfStream')<sup>9+</sup> 1809 1810on(type: 'endOfStream', callback: Callback\<void>): void 1811 1812Subscribes to the event that indicates the end of the stream being played. If **[loop](#properties) = 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. 1813 1814**Atomic service API**: This API can be used in atomic services since API version 12. 1815 1816**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1817 1818**Parameters** 1819 1820| Name | Type | Mandatory| Description | 1821| -------- | -------- | ---- | ------------------------------------------------------------ | 1822| type | string | Yes | Event type, which is **'endOfStream'** in this case. This event is triggered when the AVPlayer finishes playing the media asset.| 1823| callback | Callback\<void> | Yes | Callback invoked when the event is triggered. | 1824 1825**Example** 1826 1827```ts 1828let avPlayer = await media.createAVPlayer(); 1829avPlayer.on('endOfStream', () => { 1830 console.info('endOfStream called'); 1831}); 1832``` 1833 1834## off('endOfStream')<sup>9+</sup> 1835 1836off(type: 'endOfStream', callback?: Callback\<void>): void 1837 1838Unsubscribes from the event that indicates the end of the stream being played. 1839 1840**Atomic service API**: This API can be used in atomic services since API version 19. 1841 1842**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1843 1844**Parameters** 1845 1846| Name| Type | Mandatory| Description | 1847| ------ | ------ | ---- | ------------------------------------------------------------ | 1848| type | string | Yes | Event type, which is **'endOfStream'** in this case.| 1849| callback | Callback\<void> | No | Callback invoked when the event is triggered.<br>This parameter is supported since API version 12. | 1850 1851**Example** 1852 1853```ts 1854let avPlayer = await media.createAVPlayer(); 1855avPlayer.off('endOfStream'); 1856``` 1857 1858## on('timeUpdate')<sup>9+</sup> 1859 1860on(type: 'timeUpdate', callback: Callback\<number>): void 1861 1862Subscribes 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. 1863 1864The **'timeUpdate'** event is not supported in live mode. 1865 1866**Atomic service API**: This API can be used in atomic services since API version 11. 1867 1868**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1869 1870**Parameters** 1871 1872| Name | Type | Mandatory| Description | 1873| -------- | -------- | ---- | ---------------------------------------------- | 1874| type | string | Yes | Event type, which is **'timeUpdate'** in this case.| 1875| callback | Callback\<number> | Yes | Callback used to return the current time. | 1876 1877**Example** 1878 1879```ts 1880let avPlayer = await media.createAVPlayer(); 1881avPlayer.on('timeUpdate', (time:number) => { 1882 console.info('timeUpdate called,and new time is :' + time); 1883}); 1884``` 1885 1886## off('timeUpdate')<sup>9+</sup> 1887 1888off(type: 'timeUpdate', callback?: Callback\<number>): void 1889 1890Unsubscribes from playback position changes. 1891 1892**Atomic service API**: This API can be used in atomic services since API version 11. 1893 1894**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1895 1896**Parameters** 1897 1898| Name| Type | Mandatory| Description | 1899| ------ | ------ | ---- | -------------------------------------------------- | 1900| type | string | Yes | Event type, which is **'timeUpdate'** in this case.| 1901| callback | Callback\<number> | No | Callback used to return the current time.<br>This parameter is supported since API version 12. | 1902 1903**Example** 1904 1905```ts 1906let avPlayer = await media.createAVPlayer(); 1907avPlayer.off('timeUpdate'); 1908``` 1909 1910## on('durationUpdate')<sup>9+</sup> 1911 1912 1913on(type: 'durationUpdate', callback: Callback\<number>): void 1914 1915Subscribes 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. 1916The **'durationUpdate'** event is not supported in live mode. 1917 1918**Atomic service API**: This API can be used in atomic services since API version 12. 1919 1920**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1921 1922**Parameters** 1923 1924| Name | Type | Mandatory| Description | 1925| -------- | -------- | ---- | -------------------------------------------------- | 1926| type | string | Yes | Event type, which is **'durationUpdate'** in this case.| 1927| callback | Callback\<number> | Yes | Callback used to return the resource duration. | 1928 1929**Example** 1930 1931```ts 1932let avPlayer = await media.createAVPlayer(); 1933avPlayer.on('durationUpdate', (duration: number) => { 1934 console.info('durationUpdate called,new duration is :' + duration); 1935}); 1936``` 1937 1938## off('durationUpdate')<sup>9+</sup> 1939 1940off(type: 'durationUpdate', callback?: Callback\<number>): void 1941 1942Unsubscribes from media asset duration changes. 1943 1944**Atomic service API**: This API can be used in atomic services since API version 19. 1945 1946**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1947 1948**Parameters** 1949 1950| Name| Type | Mandatory| Description | 1951| ------ | ------ | ---- | ------------------------------------------------------ | 1952| type | string | Yes | Event type, which is **'durationUpdate'** in this case.| 1953| callback | Callback\<number> | No | Callback used to return the resource duration.<br>This parameter is supported since API version 12. | 1954 1955**Example** 1956 1957```ts 1958let avPlayer = await media.createAVPlayer(); 1959avPlayer.off('durationUpdate'); 1960``` 1961 1962## on('bufferingUpdate')<sup>9+</sup> 1963 1964on(type: 'bufferingUpdate', callback: OnBufferingUpdateHandler): void 1965 1966Subscribes to audio and video buffer changes. This subscription is supported only in network playback scenarios. 1967 1968**Atomic service API**: This API can be used in atomic services since API version 12. 1969 1970**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1971 1972**Parameters** 1973 1974| Name | Type | Mandatory| Description | 1975| -------- | -------- | ---- | ------------------------------------------------------------ | 1976| type | string | Yes | Event type, which is **'bufferingUpdate'** in this case. | 1977| callback | [OnBufferingUpdateHandler](arkts-apis-media-t.md#onbufferingupdatehandler12) | Yes | Callback invoked when the event is triggered.| 1978 1979**Example** 1980 1981```ts 1982let avPlayer = await media.createAVPlayer(); 1983avPlayer.on('bufferingUpdate', (infoType: media.BufferingInfoType, value: number) => { 1984 console.info('bufferingUpdate called,and infoType value is:' + infoType + ', value is :' + value); 1985}); 1986``` 1987 1988## off('bufferingUpdate')<sup>9+</sup> 1989 1990off(type: 'bufferingUpdate', callback?: OnBufferingUpdateHandler): void 1991 1992Unsubscribes from audio and video buffer changes. 1993 1994**Atomic service API**: This API can be used in atomic services since API version 12. 1995 1996**System capability**: SystemCapability.Multimedia.Media.AVPlayer 1997 1998**Parameters** 1999 2000| Name| Type | Mandatory| Description | 2001| ------ | ------ | ---- | --------------------------------------------------------- | 2002| type | string | Yes | Event type, which is **'bufferingUpdate'** in this case.| 2003| callback | [OnBufferingUpdateHandler](arkts-apis-media-t.md#onbufferingupdatehandler12) | No | Callback invoked when the event is triggered.| 2004 2005**Example** 2006 2007```ts 2008let avPlayer = await media.createAVPlayer(); 2009avPlayer.off('bufferingUpdate'); 2010``` 2011 2012## on('startRenderFrame')<sup>9+</sup> 2013 2014on(type: 'startRenderFrame', callback: Callback\<void>): void 2015 2016Subscribes 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. 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 **'startRenderFrame'** in this case.| 2027| callback | Callback\<void> | Yes | Callback invoked when the event is triggered. | 2028 2029**Example** 2030 2031```ts 2032let avPlayer = await media.createAVPlayer(); 2033avPlayer.on('startRenderFrame', () => { 2034 console.info('startRenderFrame called'); 2035}); 2036``` 2037 2038## off('startRenderFrame')<sup>9+</sup> 2039 2040off(type: 'startRenderFrame', callback?: Callback\<void>): void 2041 2042Unsubscribes from the event that indicates rendering starts for the first frame. 2043 2044**Atomic service API**: This API can be used in atomic services since API version 19. 2045 2046**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2047 2048**Parameters** 2049 2050| Name| Type | Mandatory| Description | 2051| ------ | ------ | ---- | ------------------------------------------------------------ | 2052| type | string | Yes | Event type, which is **'startRenderFrame'** in this case.| 2053| callback | Callback\<void> | No | Callback invoked when the event is triggered.<br>This parameter is supported since API version 12. | 2054 2055**Example** 2056 2057```ts 2058let avPlayer = await media.createAVPlayer(); 2059avPlayer.off('startRenderFrame'); 2060``` 2061 2062## on('videoSizeChange')<sup>9+</sup> 2063 2064on(type: 'videoSizeChange', callback: OnVideoSizeChangeHandler): void 2065 2066Subscribes 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. 2067 2068**Atomic service API**: This API can be used in atomic services since API version 12. 2069 2070**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2071 2072**Parameters** 2073 2074| Name | Type | Mandatory| Description | 2075| -------- | -------- | ---- | ------------------------------------------------------------ | 2076| type | string | Yes | Event type, which is **'videoSizeChange'** in this case.| 2077| callback | [OnVideoSizeChangeHandler](arkts-apis-media-t.md#onvideosizechangehandler12) | Yes | Callback invoked when the event is triggered. | 2078 2079**Example** 2080 2081```ts 2082let avPlayer = await media.createAVPlayer(); 2083avPlayer.on('videoSizeChange', (width: number, height: number) => { 2084 console.info('videoSizeChange called,and width is:' + width + ', height is :' + height); 2085}); 2086``` 2087 2088## off('videoSizeChange')<sup>9+</sup> 2089 2090off(type: 'videoSizeChange', callback?: OnVideoSizeChangeHandler): void 2091 2092Unsubscribes from video size changes. 2093 2094**Atomic service API**: This API can be used in atomic services since API version 12. 2095 2096**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2097 2098**Parameters** 2099 2100| Name| Type | Mandatory| Description | 2101| ------ | ------ | ---- | ------------------------------------------------------------ | 2102| type | string | Yes | Event type, which is **'videoSizeChange'** in this case.| 2103| callback | [OnVideoSizeChangeHandler](arkts-apis-media-t.md#onvideosizechangehandler12) | No | Callback invoked when the event is triggered.<br>This parameter is supported since API version 12. | 2104 2105**Example** 2106 2107```ts 2108let avPlayer = await media.createAVPlayer(); 2109avPlayer.off('videoSizeChange'); 2110``` 2111 2112## on('audioInterrupt')<sup>9+</sup> 2113 2114on(type: 'audioInterrupt', callback: Callback\<audio.InterruptEvent>): void 2115 2116Subscribes 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/arkts-apis-audio-e.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). 2117 2118**Atomic service API**: This API can be used in atomic services since API version 12. 2119 2120**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2121 2122**Parameters** 2123 2124| Name | Type | Mandatory| Description | 2125| -------- | ------------------------------------------------------------ | ---- | -------------------------------------------------------- | 2126| type | string | Yes | Event type, which is **'audioInterrupt'** in this case.| 2127| callback | Callback\<[audio.InterruptEvent](../apis-audio-kit/arkts-apis-audio-i.md#interruptevent9)> | Yes | Callback invoked when the event is triggered. | 2128 2129**Example** 2130 2131```ts 2132import { audio } from '@kit.AudioKit'; 2133 2134let avPlayer = await media.createAVPlayer(); 2135avPlayer.on('audioInterrupt', (info: audio.InterruptEvent) => { 2136 console.info('audioInterrupt called,and InterruptEvent info is:' + info); 2137}); 2138``` 2139 2140## off('audioInterrupt')<sup>9+</sup> 2141 2142off(type: 'audioInterrupt', callback?: Callback<audio.InterruptEvent>): void 2143 2144Unsubscribes from the audio interruption event. 2145 2146**Atomic service API**: This API can be used in atomic services since API version 12. 2147 2148**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2149 2150**Parameters** 2151 2152| Name| Type | Mandatory| Description | 2153| ------ | ------ | ---- | ------------------------------------------------------------ | 2154| type | string | Yes | Event type, which is **'audioInterrupt'** in this case.| 2155| callback | Callback\<[audio.InterruptEvent](../apis-audio-kit/arkts-apis-audio-i.md#interruptevent9)> | No | Callback invoked when the event is triggered.<br>This parameter is supported since API version 12. | 2156 2157**Example** 2158 2159```ts 2160let avPlayer = await media.createAVPlayer(); 2161avPlayer.off('audioInterrupt'); 2162``` 2163 2164## on('audioOutputDeviceChangeWithInfo')<sup>11+</sup> 2165 2166on(type: 'audioOutputDeviceChangeWithInfo', callback: Callback\<audio.AudioStreamDeviceChangeInfo>): void 2167 2168Subscribes to audio stream output device changes and reasons. This API uses an asynchronous callback to return the result. 2169 2170When 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). 2171 2172**Atomic service API**: This API can be used in atomic services since API version 12. 2173 2174**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2175 2176**Parameters** 2177 2178| Name | Type | Mandatory| Description | 2179| :------- | :------------------------- | :--- | :------------------------------------------ | 2180| type | string | Yes | Event type, which is **'audioOutputDeviceChangeWithInfo'** in this case.| 2181| callback | Callback\<[audio.AudioStreamDeviceChangeInfo](../apis-audio-kit/arkts-apis-audio-i.md#audiostreamdevicechangeinfo11)> | Yes | Callback used to return the output device descriptor of the current audio stream and the change reason.| 2182 2183**Error codes** 2184 2185| ID| Error Message | 2186| -------- | ------------------------------------------ | 2187| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 2188 2189**Example** 2190 2191```ts 2192import { audio } from '@kit.AudioKit'; 2193 2194let avPlayer = await media.createAVPlayer(); 2195avPlayer.on('audioOutputDeviceChangeWithInfo', (data: audio.AudioStreamDeviceChangeInfo) => { 2196 console.info(`${JSON.stringify(data)}`); 2197}); 2198``` 2199 2200## off('audioOutputDeviceChangeWithInfo')<sup>11+</sup> 2201 2202off(type: 'audioOutputDeviceChangeWithInfo', callback?: Callback\<audio.AudioStreamDeviceChangeInfo>): void 2203 2204Unsubscribes from audio stream output device changes and reasons. This API uses an asynchronous callback to return the result. 2205 2206**Atomic service API**: This API can be used in atomic services since API version 12. 2207 2208**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2209 2210**Parameters** 2211 2212| Name | Type | Mandatory| Description | 2213| :------- | :------------------------- | :--- | :------------------------------------------ | 2214| type | string | Yes | Event type, which is **'audioOutputDeviceChangeWithInfo'** in this case.| 2215| callback | Callback\<[audio.AudioStreamDeviceChangeInfo](../apis-audio-kit/arkts-apis-audio-i.md#audiostreamdevicechangeinfo11)> | No | Callback used to return the output device descriptor of the current audio stream and the change reason.| 2216 2217**Error codes** 2218 2219| ID| Error Message | 2220| -------- | ------------------------------------------ | 2221| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 2222 2223**Example** 2224 2225```ts 2226let avPlayer = await media.createAVPlayer(); 2227avPlayer.off('audioOutputDeviceChangeWithInfo'); 2228``` 2229 2230## addSubtitleFromFd<sup>12+</sup> 2231 2232addSubtitleFromFd(fd: number, offset?: number, length?: number): Promise\<void> 2233 2234Adds 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. 2235 2236**Atomic service API**: This API can be used in atomic services since API version 12. 2237 2238**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2239 2240**Parameters** 2241 2242| Name| Type | Mandatory| Description | 2243| ------ | ---------------------- | ---- | ------------------------------------------------------------ | 2244| fd | number | Yes | Resource handle, which is obtained by calling [resourceManager.getRawFd](../apis-localization-kit/js-apis-resource-manager.md#getrawfd9).| 2245| 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. The default value is **0**.| 2246| 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. The default value is **0**.| 2247 2248**Return value** 2249 2250| Type | Description | 2251| -------------- | ------------------------------------------ | 2252| Promise\<void> | Promise that returns no value.| 2253 2254**Error codes** 2255 2256| ID| Error Message | 2257| -------- | ------------------------------------------ | 2258| 401 | The parameter check failed. Return by promise. | 2259| 5400102 | Operation not allowed. Return by promise. | 2260 2261**Example** 2262 2263<!--code_no_check--> 2264```ts 2265import { common } from '@kit.AbilityKit' 2266 2267let avPlayer = await media.createAVPlayer(); 2268private context: Context | undefined; 2269constructor(context: Context) { 2270 this.context = context; // this.getUIContext().getHostContext(); 2271} 2272let fileDescriptor = await this.context?.resourceManager.getRawFd('xxx.srt'); 2273 2274avPlayer.addSubtitleFromFd(fileDescriptor.fd, fileDescriptor.offset, fileDescriptor.length); 2275``` 2276 2277## addSubtitleFromUrl<sup>12+</sup> 2278 2279addSubtitleFromUrl(url: string): Promise\<void> 2280 2281Adds 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. 2282 2283**Atomic service API**: This API can be used in atomic services since API version 12. 2284 2285**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2286 2287**Parameters** 2288 2289| Name| Type | Mandatory| Description | 2290| ------ | ------ | ---- | ------------------------------------------------------------ | 2291| url | string | Yes | Address of the external subtitle file.| 2292 2293**Return value** 2294 2295| Type | Description | 2296| -------------- | ------------------------------------------ | 2297| Promise\<void> | Promise that returns no value.| 2298 2299**Error codes** 2300 2301| ID| Error Message | 2302| -------- | ------------------------------------------ | 2303| 401 | The parameter check failed. Return by promise. | 2304| 5400102 | Operation not allowed. Return by promise. | 2305 2306**Example** 2307 2308<!--code_no_check--> 2309```ts 2310let fdUrl:string = 'http://xxx.xxx.xxx/xx/index.srt'; 2311let avPlayer: media.AVPlayer = await media.createAVPlayer(); 2312avPlayer.addSubtitleFromUrl(fdUrl); 2313``` 2314 2315## on('subtitleUpdate')<sup>12+</sup> 2316 2317on(type: 'subtitleUpdate', callback: Callback\<SubtitleInfo>): void 2318 2319Subscribes 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. 2320 2321**Atomic service API**: This API can be used in atomic services since API version 12. 2322 2323**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2324 2325**Parameters** 2326 2327| Name | Type | Mandatory| Description | 2328| -------- | -------- | ---- | ------------------------------------------------------------ | 2329| type | string | Yes | Event type, which is **'subtitleUpdate'** in this case. The event is triggered when the external subtitle is updated.| 2330| callback | function | Yes | Callback invoked when the subtitle is updated.| 2331 2332**Example** 2333 2334```ts 2335let avPlayer = await media.createAVPlayer(); 2336avPlayer.on('subtitleUpdate', async (info: media.SubtitleInfo) => { 2337 if (info) { 2338 let text = (!info.text) ? '' : info.text 2339 let startTime = (!info.startTime) ? 0 : info.startTime 2340 let duration = (!info.duration) ? 0 : info.duration 2341 console.info('subtitleUpdate info: text=' + text + ' startTime=' + startTime +' duration=' + duration); 2342 } else { 2343 console.info('subtitleUpdate info is null'); 2344 } 2345}); 2346``` 2347 2348## off('subtitleUpdate')<sup>12+</sup> 2349 2350off(type: 'subtitleUpdate', callback?: Callback\<SubtitleInfo>): void 2351 2352Unsubscribes from subtitle update events. 2353 2354**Atomic service API**: This API can be used in atomic services since API version 12. 2355 2356**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2357 2358**Parameters** 2359 2360| Name | Type | Mandatory| Description | 2361| -------- | -------- | ---- | ------------------------------------------------------------ | 2362| type | string | Yes | Event type, which is **'subtitleUpdate'** in this case. The event is triggered when the external subtitle is updated.| 2363| callback | function | No | Callback that has been registered to listen for subtitle update events.| 2364 2365**Example** 2366 2367```ts 2368let avPlayer = await media.createAVPlayer(); 2369avPlayer.off('subtitleUpdate'); 2370``` 2371 2372## on('trackChange')<sup>12+</sup> 2373 2374on(type: 'trackChange', callback: OnTrackChangeHandler): void 2375 2376Subscribes 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. 2377 2378**Atomic service API**: This API can be used in atomic services since API version 12. 2379 2380**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2381 2382**Parameters** 2383 2384| Name | Type | Mandatory| Description | 2385| -------- | -------- | ---- | ------------------------------------------------------------ | 2386| type | string | Yes | Event type, which is **'trackChange'** in this case. The event is triggered when the track changes.| 2387| callback | [OnTrackChangeHandler](arkts-apis-media-t.md#ontrackchangehandler12) | Yes | Callback invoked when the event is triggered.| 2388 2389**Example** 2390 2391```ts 2392let avPlayer = await media.createAVPlayer(); 2393avPlayer.on('trackChange', (index: number, isSelect: boolean) => { 2394 console.info('trackChange info: index=' + index + ' isSelect=' + isSelect); 2395}); 2396``` 2397 2398## off('trackChange')<sup>12+</sup> 2399 2400off(type: 'trackChange', callback?: OnTrackChangeHandler): void 2401 2402Unsubscribes from track change events. 2403 2404**Atomic service API**: This API can be used in atomic services since API version 12. 2405 2406**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2407 2408**Parameters** 2409 2410| Name | Type | Mandatory| Description | 2411| -------- | -------- | ---- | ------------------------------------------------------------ | 2412| type | string | Yes | Event type, which is **'trackChange'** in this case. The event is triggered when the track changes.| 2413| callback | [OnTrackChangeHandler](arkts-apis-media-t.md#ontrackchangehandler12) | No | Callback that has been registered to listen for track changes.| 2414 2415**Example** 2416 2417```ts 2418let avPlayer = await media.createAVPlayer(); 2419avPlayer.off('trackChange'); 2420``` 2421 2422## on('trackInfoUpdate')<sup>12+</sup> 2423 2424on(type: 'trackInfoUpdate', callback: Callback\<Array\<MediaDescription>>): void 2425 2426Subscribes 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. 2427 2428**Atomic service API**: This API can be used in atomic services since API version 12. 2429 2430**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2431 2432**Parameters** 2433 2434| Name | Type | Mandatory| Description | 2435| -------- | -------- | ---- | ------------------------------------------------------------ | 2436| type | string | Yes | Event type, which is **'trackInfoUpdate'** in this case. The event is triggered when the track information is updated.| 2437| callback | Callback\<Array\<[MediaDescription](arkts-apis-media-i.md#mediadescription8)>> | Yes | Callback invoked when the event is triggered.| 2438 2439**Example** 2440 2441```ts 2442let avPlayer = await media.createAVPlayer(); 2443avPlayer.on('trackInfoUpdate', (info: Array<media.MediaDescription>) => { 2444 if (info) { 2445 for (let i = 0; i < info.length; i++) { 2446 let propertyIndex: Object = info[i][media.MediaDescriptionKey.MD_KEY_TRACK_INDEX]; 2447 let propertyType: Object = info[i][media.MediaDescriptionKey.MD_KEY_TRACK_TYPE]; 2448 console.info('track info: index=' + propertyIndex + ' tracktype=' + propertyType); 2449 } 2450 } else { 2451 console.info('track info is null'); 2452 } 2453}); 2454``` 2455 2456## off('trackInfoUpdate')<sup>12+</sup> 2457 2458off(type: 'trackInfoUpdate', callback?: Callback\<Array\<MediaDescription>>): void 2459 2460Unsubscribes from track information update events. 2461 2462**Atomic service API**: This API can be used in atomic services since API version 12. 2463 2464**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2465 2466**Parameters** 2467 2468| Name | Type | Mandatory| Description | 2469| -------- | -------- | ---- | ------------------------------------------------------------ | 2470| type | string | Yes | Event type, which is **'trackInfoUpdate'** in this case. The event is triggered when the track information is updated.| 2471| callback | Callback\<Array\<[MediaDescription](arkts-apis-media-i.md#mediadescription8)>> | No | Callback that has been registered to listen for track information updates.| 2472 2473**Example** 2474 2475```ts 2476let avPlayer = await media.createAVPlayer(); 2477avPlayer.off('trackInfoUpdate'); 2478``` 2479 2480## on('amplitudeUpdate')<sup>13+</sup> 2481 2482on(type: 'amplitudeUpdate', callback: Callback\<Array\<number>>): void 2483 2484Subscribes to update events of the maximum audio level value, which is periodically reported when audio resources are played. 2485 2486**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2487 2488**Parameters** 2489 2490| Name | Type | Mandatory| Description | 2491| -------- | -------- | ---- | ------------------------------------------------------------ | 2492| type | string | Yes | Event type, which is **'amplitudeUpdate'** in this case. The event is triggered when the amplitude changes.| 2493| callback | Callback\<Array\<number>> | Yes | Callback invoked when the event is triggered.| 2494 2495**Example** 2496 2497```ts 2498let avPlayer = await media.createAVPlayer(); 2499avPlayer.on('amplitudeUpdate', (value: Array<number>) => { 2500 console.info(`amplitudeUpdate called,and amplitudeUpdate = ${value}`); 2501}); 2502``` 2503 2504## off('amplitudeUpdate')<sup>13+</sup> 2505 2506off(type: 'amplitudeUpdate', callback?: Callback\<Array\<number>>): void 2507 2508Unsubscribes from update events of the maximum amplitude. 2509 2510**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2511 2512**Parameters** 2513 2514| Name| Type | Mandatory| Description | 2515| ------ | ------ | ---- | ------------------------------------------------------------ | 2516| type | string | Yes | Event type, which is **'amplitudeUpdate'** in this case. The event is triggered when the amplitude changes.| 2517| callback | Callback\<Array\<number>> | No | Callback that has been registered to listen for amplitude updates.| 2518 2519**Example** 2520 2521```ts 2522let avPlayer = await media.createAVPlayer(); 2523avPlayer.off('amplitudeUpdate'); 2524``` 2525 2526## on('seiMessageReceived')<sup>18+</sup> 2527 2528on(type: 'seiMessageReceived', payloadTypes: Array\<number>, callback: OnSeiMessageHandle): void 2529 2530Subscribes to events indicating that a Supplemental Enhancement Information (SEI) message is received. This applies only to HTTP-FLV live streaming and is triggered when SEI messages are present in the video stream. You must initiate the subscription before calling **prepare**. If you initiate multiple subscriptions to this event, the last subscription is applied. 2531 2532**Atomic service API**: This API can be used in atomic services since API version 18. 2533 2534**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2535 2536**Parameters** 2537 2538| Name | Type | Mandatory| Description | 2539| -------- | -------- | ---- | ------------------------------------------------------------ | 2540| type | string | Yes| Event type, which is **'seiMessageReceived'** in this case. The event is triggered when an SEI message is received.| 2541| payloadTypes | Array\<number> | Yes| Array of subscribed-to payload types of SEI messages. Currently, only payloadType = 5 is supported.| 2542| callback | [OnSeiMessageHandle](arkts-apis-media-t.md#onseimessagehandle18) | Yes| Callback used to listen for SEI message events and receive the subscribed-to payload types.| 2543 2544**Example** 2545 2546```ts 2547import util from '@ohos.util'; 2548 2549let avPlayer = await media.createAVPlayer(); 2550 2551avPlayer.on('seiMessageReceived', [5], (messages: Array<media.SeiMessage>, playbackPosition?: number) => 2552{ 2553 console.info('seiMessageReceived playbackPosition ' + playbackPosition); 2554 2555 for (let key = 0; key < messages.length; key++) { 2556 console.info('seiMessageReceived messages payloadType ' + messages[key].payloadType + ' payload size ' + messages[key].payload.byteLength); 2557 2558 let textDecoder = util.TextDecoder.create("utf-8",{ignoreBOM: true}); 2559 let ab = messages[key]?.payload?.slice(16, messages[key].payload.byteLength); 2560 let result: Uint8Array = new Uint8Array(ab); 2561 let retStr: string = textDecoder.decodeToString(result); 2562 console.info('seiMessageReceived messages payload ' + retStr); 2563 } 2564}); 2565``` 2566 2567## off('seiMessageReceived')<sup>18+</sup> 2568 2569off(type: 'seiMessageReceived', payloadTypes?: Array\<number>, callback?: OnSeiMessageHandle): void 2570 2571Unsubscribes from the events indicating that an SEI message is received. 2572 2573**Atomic service API**: This API can be used in atomic services since API version 18. 2574 2575**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2576 2577**Parameters** 2578 2579| Name| Type | Mandatory| Description | 2580| ------ | ------ | ---- | ------------------------------------------------------------ | 2581| type | string | Yes | Event type, which is **'seiMessageReceived'** in this case. The event is triggered when an SEI message is received.| 2582| payloadTypes | Array\<number> | No | Array of subscribed-to payload types of SEI messages.| 2583| callback | [OnSeiMessageHandle](arkts-apis-media-t.md#onseimessagehandle18) | No | Callback used to listen for SEI message events and receive the subscribed-to payload types.| 2584 2585**Example** 2586 2587```ts 2588let avPlayer = await media.createAVPlayer(); 2589avPlayer.off('seiMessageReceived'); 2590``` 2591 2592## setSuperResolution<sup>18+</sup> 2593 2594setSuperResolution(enabled: boolean) : Promise\<void> 2595 2596Enables or disables super resolution. This API can be called when the AVPlayer is in the initialized, prepared, playing, paused, completed, or stopped state. This API uses a promise to return the result. 2597 2598Before calling [prepare()](#prepare9), enable super resolution by using [PlaybackStrategy](arkts-apis-media-i.md#playbackstrategy12). 2599 2600**Atomic service API**: This API can be used in atomic services since API version 18. 2601 2602**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2603 2604**Parameters** 2605 2606| Name| Type | Mandatory| Description | 2607| ------ | ------ | ---- | ------------------------------------------------------------ | 2608| enabled | boolean | Yes | Whether to enable or disable super resolution. **true** to enable, **false** otherwise.| 2609 2610**Return value** 2611 2612| Type | Description | 2613| -------------- | ------------------------------------------ | 2614| Promise\<void> | Promise that returns no value.| 2615 2616**Error codes** 2617 2618For details about the error codes, see [Media Error Codes](errorcode-media.md). 2619 2620| ID| Error Message | 2621| -------- | ------------------------------------------ | 2622| 5400102 | Operation not allowed. Return by promise. | 2623| 5410003 | Super-resolution not supported. Return by promise. | 2624| 5410004 | Missing enable super-resolution feature in [PlaybackStrategy](arkts-apis-media-i.md#playbackstrategy12). Return by promise. | 2625 2626**Example** 2627 2628```ts 2629let avPlayer = await media.createAVPlayer(); 2630// Here is only an example. In real development, you must wait for the stateChange event to successfully trigger and reach the initialized, prepared, playing, paused, completed, or stopped state before proceeding. 2631avPlayer.setSuperResolution(true); 2632``` 2633 2634## setVideoWindowSize<sup>18+</sup> 2635 2636setVideoWindowSize(width: number, height: number) : Promise\<void> 2637 2638Sets the resolution of the output video after super resolution. This API can be called when the AVPlayer is in the initialized, prepared, playing, paused, completed, or stopped state. This API uses a promise to return the result. The input parameter values s must be in the range of 320 x 320 to 1920 x 1080 (in px). 2639 2640Before calling [prepare()](#prepare9), enable super resolution by using [PlaybackStrategy](arkts-apis-media-i.md#playbackstrategy12). 2641 2642**Atomic service API**: This API can be used in atomic services since API version 18. 2643 2644**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2645 2646**Parameters** 2647 2648| Name| Type | Mandatory| Description | 2649| ------ | ------ | ---- | ------------------------------------------------------------ | 2650| width | number | Yes | Target width of the output video after super resolution. The value range is [320-1920], in px.| 2651| height | number | Yes | Target height of the output video after super resolution. The value range is [320-1080], in px.| 2652 2653**Return value** 2654 2655| Type | Description | 2656| -------------- | ------------------------------------------ | 2657| Promise\<void> | Promise that returns no value.| 2658 2659**Error codes** 2660 2661For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Media Error Codes](errorcode-media.md). 2662 2663| ID| Error Message | 2664| -------- | ------------------------------------------ | 2665| 401 | Parameter error. Return by promise. | 2666| 5400102 | Operation not allowed. Return by promise. | 2667| 5410003 | Super-resolution not supported. Return by promise. | 2668| 5410004 | Missing enable super-resolution feature in [PlaybackStrategy](arkts-apis-media-i.md#playbackstrategy12). Return by promise. | 2669 2670**Example** 2671 2672```ts 2673let avPlayer = await media.createAVPlayer(); 2674// Here is only an example. In real development, you must wait for the stateChange event to successfully trigger and reach the initialized, prepared, playing, paused, completed, or stopped state before proceeding. 2675avPlayer.setVideoWindowSize(1920, 1080); 2676``` 2677 2678## on('superResolutionChanged')<sup>18+</sup> 2679 2680on(type:'superResolutionChanged', callback: OnSuperResolutionChanged): void 2681 2682Subscribes to the event indicating that super resolution is enabled or disabled. 2683 2684**Atomic service API**: This API can be used in atomic services since API version 18. 2685 2686**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2687 2688**Parameters** 2689 2690| Name | Type | Mandatory| Description | 2691| -------- | -------- | ---- | ------------------------------------------------------------ | 2692| type | string | Yes| Event type, which is **'superResolutionChanged'** in this case. The event is triggered when super resolution is enabled or disabled.| 2693| callback | [OnSuperResolutionChanged](arkts-apis-media-t.md#onsuperresolutionchanged-18) | Yes| Callback used to listen for super resolution status changes.| 2694 2695**Example** 2696 2697```ts 2698let avPlayer = await media.createAVPlayer(); 2699avPlayer.on('superResolutionChanged', (enabled: boolean) => { 2700 console.info('superResolutionChanged called, and enabled is:' + enabled); 2701}); 2702``` 2703 2704## off('superResolutionChanged')<sup>18+</sup> 2705 2706off(type:'superResolutionChanged', callback?: OnSuperResolutionChanged): void 2707 2708Unsubscribes from the event indicating that super resolution is enabled or disabled. 2709 2710**Atomic service API**: This API can be used in atomic services since API version 18. 2711 2712**System capability**: SystemCapability.Multimedia.Media.AVPlayer 2713 2714**Parameters** 2715 2716| Name | Type | Mandatory| Description | 2717| -------- | -------- | ---- | ------------------------------------------------------------ | 2718| type | string | Yes| Event type, which is **'superResolutionChanged'** in this case. The event is triggered when super resolution is enabled or disabled.| 2719| callback | [OnSuperResolutionChanged](arkts-apis-media-t.md#onsuperresolutionchanged-18) | No| Callback used to listen for super resolution status changes.| 2720 2721**Example** 2722 2723```ts 2724let avPlayer = await media.createAVPlayer(); 2725avPlayer.off('superResolutionChanged'); 2726``` 2727