• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.multimedia.media (Media)
2
3> **NOTE**
4>
5> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
6
7The multimedia subsystem provides a set of simple and easy-to-use APIs for you to access the system and use media resources.
8
9This subsystem offers the following audio and video services:
10
11- Audio and video playback ([AVPlayer](#avplayer9)<sup>9+</sup>)
12
13- Audio and video recording [AVRecorder](#avrecorder9)<sup>9+</sup>)
14
15- Video transcoding ([AVTranscoder](#avtranscoder12)<sup>12+</sup>)
16
17- Obtaining audio and video metadata ([AVMetadataExtractor](#avmetadataextractor11)<sup>11+</sup>)
18
19- Obtaining video thumbnails ([AVImageGenerator](#avimagegenerator12)<sup>12+</sup>)
20
21- Screen capture ([AVScreenCaptureRecorder](#avscreencapturerecorder12)<sup>12+</sup>)
22
23## Modules to Import
24
25```ts
26import { media } from '@kit.MediaKit';
27```
28
29## media.createAVPlayer<sup>9+</sup>
30
31createAVPlayer(callback: AsyncCallback\<AVPlayer>): void
32
33Creates an **AVPlayer** instance. This API uses an asynchronous callback to return the result.
34
35> **NOTE**
36>
37> - You are advised to create a maximum of 16 **AVPlayer** instances for an application in both audio and video playback scenarios.<!--Del-->
38> - The actual number of instances that can be created may be different. It depends on the specifications of the device chip in use. For example, in the case of RK3568, you are advised to create a maximum of 6 **AVPlayer** instances for an application in audio and video playback scenarios.<!--DelEnd-->
39
40**Atomic service API**: This API can be used in atomic services since API version 11.
41
42**System capability**: SystemCapability.Multimedia.Media.AVPlayer
43
44**Parameters**
45
46| Name  | Type                                 | Mandatory| Description                                                        |
47| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ |
48| callback | AsyncCallback\<[AVPlayer](#avplayer9)> | Yes  | Callback used to return the result. If the operation is successful, an **AVPlayer** instance is returned; otherwise, **null** is returned. The instance can be used to play audio and video.|
49
50**Error codes**
51
52For details about the error codes, see [Media Error Codes](errorcode-media.md).
53
54| ID| Error Message                      |
55| -------- | ------------------------------ |
56| 5400101  | No memory. Return by callback. |
57
58**Example**
59
60```ts
61import { BusinessError } from '@kit.BasicServicesKit';
62
63let avPlayer: media.AVPlayer;
64media.createAVPlayer((error: BusinessError, video: media.AVPlayer) => {
65  if (video != null) {
66    avPlayer = video;
67    console.info('Succeeded in creating AVPlayer');
68  } else {
69    console.error(`Failed to create AVPlayer, error message:${error.message}`);
70  }
71});
72```
73
74## media.createAVPlayer<sup>9+</sup>
75
76createAVPlayer(): Promise\<AVPlayer>
77
78Creates an **AVPlayer** instance. This API uses a promise to return the result.
79
80> **NOTE**
81>
82> - You are advised to create a maximum of 16 **AVPlayer** instances for an application in both audio and video playback scenarios.<!--Del-->
83> - The actual number of instances that can be created may be different. It depends on the specifications of the device chip in use. For example, in the case of RK3568, you are advised to create a maximum of 6 **AVPlayer** instances for an application in audio and video playback scenarios.<!--DelEnd-->
84
85**Atomic service API**: This API can be used in atomic services since API version 11.
86
87**System capability**: SystemCapability.Multimedia.Media.AVPlayer
88
89**Return value**
90
91| Type                           | Description                                                        |
92| ------------------------------- | ------------------------------------------------------------ |
93| Promise\<[AVPlayer](#avplayer9)> | Promise used to return the result. If the operation is successful, an **AVPlayer** instance is returned; otherwise, **null** is returned. The instance can be used to play audio and video.|
94
95**Error codes**
96
97For details about the error codes, see [Media Error Codes](errorcode-media.md).
98
99| ID| Error Message                     |
100| -------- | ----------------------------- |
101| 5400101  | No memory. Return by promise. |
102
103**Example**
104
105```ts
106import { BusinessError } from '@kit.BasicServicesKit';
107
108let avPlayer: media.AVPlayer;
109media.createAVPlayer().then((video: media.AVPlayer) => {
110  if (video != null) {
111    avPlayer = video;
112    console.info('Succeeded in creating AVPlayer');
113  } else {
114    console.error('Failed to create AVPlayer');
115  }
116}).catch((error: BusinessError) => {
117  console.error(`Failed to create AVPlayer, error message:${error.message}`);
118});
119```
120
121## media.createAVRecorder<sup>9+</sup>
122
123createAVRecorder(callback: AsyncCallback\<AVRecorder>): void
124
125Creates an **AVRecorder** instance. This API uses an asynchronous callback to return the result.
126
127> **NOTE**
128>
129> An application can create multiple **AVRecorder** instances. However, because the device shares a common audio channel, only one instance can record audio at a time. Any attempt to create the second instance for audio recording fails due to audio channel conflicts.
130
131**System capability**: SystemCapability.Multimedia.Media.AVRecorder
132
133**Parameters**
134
135| Name  | Type                                      | Mandatory| Description                                                        |
136| -------- | ------------------------------------------ | ---- | ------------------------------------------------------------ |
137| callback | AsyncCallback\<[AVRecorder](#avrecorder9)> | Yes  | Callback used to return the result. If the operation is successful, an **AVRecorder** instance is returned; otherwise, **null** is returned. The instance can be used to record audio and video.|
138
139**Error codes**
140
141For details about the error codes, see [Media Error Codes](errorcode-media.md).
142
143| ID| Error Message                      |
144| -------- | ------------------------------ |
145| 5400101  | No memory. Return by callback. |
146
147**Example**
148
149```ts
150import { BusinessError } from '@kit.BasicServicesKit';
151let avRecorder: media.AVRecorder;
152
153media.createAVRecorder((error: BusinessError, recorder: media.AVRecorder) => {
154  if (recorder != null) {
155    avRecorder = recorder;
156    console.info('Succeeded in creating AVRecorder');
157  } else {
158    console.error(`Failed to create AVRecorder, error message:${error.message}`);
159  }
160});
161```
162
163## media.createAVRecorder<sup>9+</sup>
164
165createAVRecorder(): Promise\<AVRecorder>
166
167Creates an **AVRecorder** instance. This API uses a promise to return the result.
168
169> **NOTE**
170>
171> An application can create multiple **AVRecorder** instances. However, because the device shares a common audio channel, only one instance can record audio at a time. Any attempt to create the second instance for audio recording fails due to audio channel conflicts.
172
173**Atomic service API**: This API can be used in atomic services since API version 12.
174
175**System capability**: SystemCapability.Multimedia.Media.AVRecorder
176
177**Return value**
178
179| Type                                | Description                                                        |
180| ------------------------------------ | ------------------------------------------------------------ |
181| Promise\<[AVRecorder](#avrecorder9)> | Promise used to return the result. If the operation is successful, an **AVRecorder** instance is returned; otherwise, **null** is returned. The instance can be used to record audio and video.|
182
183**Error codes**
184
185For details about the error codes, see [Media Error Codes](errorcode-media.md).
186
187| ID| Error Message                     |
188| -------- | ----------------------------- |
189| 5400101  | No memory. Return by promise. |
190
191**Example**
192
193```ts
194import { BusinessError } from '@kit.BasicServicesKit';
195
196let avRecorder: media.AVRecorder;
197media.createAVRecorder().then((recorder: media.AVRecorder) => {
198  if (recorder != null) {
199    avRecorder = recorder;
200    console.info('Succeeded in creating AVRecorder');
201  } else {
202    console.error('Failed to create AVRecorder');
203  }
204}).catch((error: BusinessError) => {
205  console.error(`Failed to create AVRecorder, error message:${error.message}`);
206});
207```
208
209## media.createAVTranscoder<sup>12+</sup>
210
211createAVTranscoder(): Promise\<AVTranscoder>
212
213Creates an **AVTranscoder** instance. This API uses a promise to return the result.
214
215> **NOTE**
216
217> A maximum of 2 **AVTranscoder** instances can be created.
218
219**System capability**: SystemCapability.Multimedia.Media.AVTranscoder
220
221**Return value**
222
223| Type                           | Description                                                        |
224| ------------------------------- | ------------------------------------------------------------ |
225| Promise\<[AVTranscoder](#avtranscoder12)> | Promise used to return the result. If the operation is successful, an **AVTranscoder** instance is returned; otherwise, **null** is returned. The instance can be used for video transcoding.|
226
227**Error codes**
228
229For details about the error codes, see [Media Error Codes](errorcode-media.md).
230
231| ID| Error Message                     |
232| -------- | ----------------------------- |
233| 5400101  | No memory. Return by promise. |
234
235**Example**
236
237```ts
238import { BusinessError } from '@kit.BasicServicesKit';
239
240let avTranscoder: media.AVTranscoder;
241media.createAVTranscoder().then((transcoder: media.AVTranscoder) => {
242  if (transcoder != null) {
243    avTranscoder = transcoder;
244    console.info('Succeeded in creating AVTranscoder');
245  } else {
246    console.error('Failed to create AVTranscoder');
247  }
248}).catch((error: BusinessError) => {
249  console.error(`Failed to create AVTranscoder, error message:${error.message}`);
250});
251```
252
253## media.createAVMetadataExtractor<sup>11+</sup>
254
255createAVMetadataExtractor(callback: AsyncCallback\<AVMetadataExtractor>): void
256
257Creates an **AVMetadataExtractor** instance. This API uses an asynchronous callback to return the result.
258
259**System capability**: SystemCapability.Multimedia.Media.AVMetadataExtractor
260
261**Parameters**
262
263| Name  | Type                                 | Mandatory| Description                                                        |
264| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ |
265| callback | AsyncCallback\<[AVMetadataExtractor](#avmetadataextractor11)> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the **AVMetadataExtractor** instance created; otherwise, **err** is an error object.|
266
267**Error codes**
268
269For details about the error codes, see [Media Error Codes](errorcode-media.md).
270
271| ID| Error Message                      |
272| -------- | ------------------------------ |
273| 5400101  | No memory. Returned by callback. |
274
275**Example**
276
277```ts
278import { BusinessError } from '@kit.BasicServicesKit';
279
280let avMetadataExtractor: media.AVMetadataExtractor;
281media.createAVMetadataExtractor((error: BusinessError, extractor: media.AVMetadataExtractor) => {
282  if (extractor != null) {
283    avMetadataExtractor = extractor;
284    console.info('Succeeded in creating AVMetadataExtractor');
285  } else {
286    console.error(`Failed to create AVMetadataExtractor, error message:${error.message}`);
287  }
288});
289```
290
291## media.createAVMetadataExtractor<sup>11+</sup>
292
293createAVMetadataExtractor(): Promise\<AVMetadataExtractor>
294
295Creates an **AVMetadataExtractor** instance. This API uses a promise to return the result.
296
297**System capability**: SystemCapability.Multimedia.Media.AVMetadataExtractor
298
299**Error codes**
300
301For details about the error codes, see [Media Error Codes](errorcode-media.md).
302
303| ID| Error Message                      |
304| -------- | ------------------------------ |
305| 5400101  | No memory. Returned by promise. |
306
307**Example**
308
309```ts
310import { BusinessError } from '@kit.BasicServicesKit';
311
312let avMetadataExtractor: media.AVMetadataExtractor;
313media.createAVMetadataExtractor().then((extractor: media.AVMetadataExtractor) => {
314  if (extractor != null) {
315    avMetadataExtractor = extractor;
316    console.info('Succeeded in creating AVMetadataExtractor');
317  } else {
318    console.error(`Failed to create AVMetadataExtractor`);
319  }
320}).catch((error: BusinessError) => {
321  console.error(`Failed to create AVMetadataExtractor, error message:${error.message}`);
322});
323```
324
325## media.createSoundPool<sup>10+</sup>
326
327createSoundPool(maxStreams: number, audioRenderInfo: audio.AudioRendererInfo, callback: AsyncCallback\<SoundPool>): void
328
329Creates a **SoundPool** instance. This API uses an asynchronous callback to return the result.
330
331> **NOTE**
332>
333> - In versions earlier than API version 18, the bottom layer of the created **SoundPool** object is in singleton mode. Therefore, an application process can create only one **SoundPool** instance.
334> - In API version 18 and later versions, the bottom layer of the created **SoundPool** object is in multiton mode. Therefore, an application process can create a maximum of 128 **SoundPool** instances.
335
336**System capability**: SystemCapability.Multimedia.Media.SoundPool
337
338**Parameters**
339
340| Name  | Type                                           | Mandatory| Description                                                        |
341| -------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ |
342| maxStreams | number | Yes  | Maximum number of streams that can be played by the **SoundPool** instance. The value is an integer ranging from 1 to 32.|
343| audioRenderInfo | [audio.AudioRendererInfo](../apis-audio-kit/js-apis-audio.md#audiorendererinfo8)  | Yes  | Audio renderer parameters. When the **usage** parameter in **audioRenderInfo** is set to **STREAM_USAGE_UNKNOWN**, **STREAM_USAGE_MUSIC**, **STREAM_USAGE_MOVIE**, or **STREAM_USAGE_AUDIOBOOK**, the SoundPool uses the audio mixing mode when playing a short sound, without interrupting the playback of other audios.|
344| callback | AsyncCallback<[SoundPool](js-apis-inner-multimedia-soundPool.md)> | Yes  | Callback used to return the result. If the operation is successful, a **SoundPool** instance is returned; otherwise, **null** is returned. The instance is used for loading and playback.|
345
346**Error codes**
347
348For details about the error codes, see [Media Error Codes](errorcode-media.md).
349
350| ID| Error Message                      |
351| -------- | ------------------------------ |
352| 5400101  | No memory. Return by callback. |
353
354**Example**
355
356```js
357import { audio } from '@kit.AudioKit';
358
359let soundPool: media.SoundPool;
360let audioRendererInfo: audio.AudioRendererInfo = {
361  usage : audio.StreamUsage.STREAM_USAGE_MUSIC,
362  rendererFlags : 0
363}
364
365media.createSoundPool(5, audioRendererInfo, (error, soundPool_: media.SoundPool) => {
366  if (error) {
367    console.error(`Failed to createSoundPool`)
368    return;
369  } else {
370    soundPool = soundPool_;
371    console.info(`Succeeded in createSoundPool`)
372  }
373});
374```
375
376## media.createSoundPool<sup>10+</sup>
377
378createSoundPool(maxStreams: number, audioRenderInfo: audio.AudioRendererInfo): Promise\<SoundPool>
379
380Creates a **SoundPool** instance. This API uses a promise to return the result.
381
382> **NOTE**
383>
384> - In versions earlier than API version 18, the bottom layer of the created **SoundPool** object is in singleton mode. Therefore, an application process can create only one **SoundPool** instance.
385> - In API version 18 and later versions, the bottom layer of the created **SoundPool** object is in multiton mode. Therefore, an application process can create a maximum of 128 **SoundPool** instances.
386
387**System capability**: SystemCapability.Multimedia.Media.SoundPool
388
389**Parameters**
390
391| Name  | Type                                           | Mandatory| Description                                                        |
392| -------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ |
393| maxStreams | number | Yes  | Maximum number of streams that can be played by the **SoundPool** instance. The value is an integer ranging from 1 to 32.|
394| audioRenderInfo | [audio.AudioRendererInfo](../apis-audio-kit/js-apis-audio.md#audiorendererinfo8)  | Yes  | Audio renderer parameters.|
395
396**Return value**
397
398| Type                                     | Description                                                        |
399| ----------------------------------------- | ------------------------------------------------------------ |
400| Promise<[SoundPool](js-apis-inner-multimedia-soundPool.md)> | Promise used to return the result. If the operation is successful, a **SoundPool** instance is returned; otherwise, **null** is returned. The instance is used for loading and playback.|
401
402**Error codes**
403
404For details about the error codes, see [Media Error Codes](errorcode-media.md).
405
406| ID| Error Message                     |
407| -------- | ----------------------------- |
408| 5400101  | No memory. Return by promise. |
409
410**Example**
411
412```js
413import { audio } from '@kit.AudioKit';
414import { BusinessError } from '@kit.BasicServicesKit';
415
416let soundPool: media.SoundPool;
417let audioRendererInfo: audio.AudioRendererInfo = {
418  usage : audio.StreamUsage.STREAM_USAGE_MUSIC,
419  rendererFlags : 0
420}
421
422media.createSoundPool(5, audioRendererInfo).then((soundpool_: media.SoundPool) => {
423  if (soundpool_ != null) {
424    soundPool = soundpool_;
425    console.info('Succceeded in creating SoundPool');
426  } else {
427    console.error('Failed to create SoundPool');
428  }
429}, (error: BusinessError) => {
430  console.error(`soundpool catchCallback, error message:${error.message}`);
431});
432```
433
434## media.createAVScreenCaptureRecorder<sup>12+</sup>
435
436createAVScreenCaptureRecorder(): Promise\<AVScreenCaptureRecorder>
437
438Creates an **AVScreenCaptureRecorder** instance. This API uses a promise to return the result.
439
440**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture
441
442**Return value**
443
444| Type                                                        | Description                                                        |
445| ------------------------------------------------------------ | ------------------------------------------------------------ |
446| Promise\<[AVScreenCaptureRecorder](#avscreencapturerecorder12)> | Promise used to return the result. If the operation is successful, an **AVScreenCaptureRecorder** instance is returned; otherwise, **null** is returned. The instance can be used for screen capture.|
447
448**Error codes**
449
450| ID| Error Message                      |
451| -------- | ------------------------------ |
452| 5400101  | No memory. Return by promise. |
453
454**Example**
455
456```ts
457import { BusinessError } from '@kit.BasicServicesKit';
458
459let avScreenCaptureRecorder: media.AVScreenCaptureRecorder;
460media.createAVScreenCaptureRecorder().then((captureRecorder: media.AVScreenCaptureRecorder) => {
461  if (captureRecorder != null) {
462    avScreenCaptureRecorder = captureRecorder;
463    console.info('Succeeded in createAVScreenCaptureRecorder');
464  } else {
465    console.error('Failed to createAVScreenCaptureRecorder');
466  }
467}).catch((error: BusinessError) => {
468  console.error(`createAVScreenCaptureRecorder catchCallback, error message:${error.message}`);
469});
470```
471
472## SoundPool<sup>10+</sup>
473
474type SoundPool = _SoundPool
475
476SoundPool, which provides APIs for loading, unloading, playing, and stopping playing system sounds, setting the volume, and setting the number of loops.
477
478**System capability**: SystemCapability.Multimedia.Media.SoundPool
479
480| Type    | Description                      |
481| -------- | ------------------------------ |
482| [_SoundPool](js-apis-inner-multimedia-soundPool.md#soundpool)  | Provides APIs for loading, unloading, playing, and stopping playing system sounds, setting the volume, and setting the number of loops.|
483
484## PlayParameters<sup>10+</sup>
485
486type PlayParameters = _PlayParameters
487
488Describes the playback parameters of the sound pool.
489
490**System capability**: SystemCapability.Multimedia.Media.SoundPool
491
492| Type    | Description                      |
493| -------- | ------------------------------ |
494| [_PlayParameters](js-apis-inner-multimedia-soundPool.md#playparameters)  | Playback parameters of the sound pool.|
495
496## AVErrorCode<sup>9+</sup>
497
498Enumerates the [media error codes](errorcode-media.md).
499
500**Atomic service API**: This API can be used in atomic services since API version 11.
501
502**System capability**: SystemCapability.Multimedia.Media.Core
503
504| Name                                 | Value     | Description                                |
505| :------------------------------------ | ------- | ------------------------------------ |
506| AVERR_OK                              | 0       | The operation is successful.                      |
507| AVERR_NO_PERMISSION                   | 201     | No permission to perform the operation.              |
508| AVERR_INVALID_PARAMETER               | 401     | Invalid input parameter.                  |
509| AVERR_UNSUPPORT_CAPABILITY            | 801     | Unsupported API.       |
510| AVERR_NO_MEMORY                       | 5400101 | The system memory is insufficient or the number of services reaches the upper limit.|
511| AVERR_OPERATE_NOT_PERMIT              | 5400102 | The operation is not allowed in the current state or you do not have the permission to perform the operation.|
512| AVERR_IO                              | 5400103 | The data stream is abnormal.                |
513| AVERR_TIMEOUT                         | 5400104 | The system or network response times out.            |
514| AVERR_SERVICE_DIED                    | 5400105 | The service process is dead.                  |
515| AVERR_UNSUPPORT_FORMAT                | 5400106 | The format of the media asset is not supported.      |
516| AVERR_AUDIO_INTERRUPTED<sup>11+</sup> | 5400107 | The audio focus is interrupted.                  |
517| AVERR_IO_HOST_NOT_FOUND<sup>14+</sup> | 5411001 | Failed to parse the server address or connect to the server.<br>**Atomic service API**: This API can be used in atomic services since API version 14.       |
518| AVERR_IO_CONNECTION_TIMEOUT<sup>14+</sup> | 5411002 | Network connection times out.<br>**Atomic service API**: This API can be used in atomic services since API version 14.       |
519| AVERR_IO_NETWORK_ABNORMAL<sup>14+</sup> | 5411003 | Data or links are abnormal due to network exceptions.<br>**Atomic service API**: This API can be used in atomic services since API version 14.       |
520| AVERR_IO_NETWORK_UNAVAILABLE<sup>14+</sup> | 5411004 | The network is disabled.<br>**Atomic service API**: This API can be used in atomic services since API version 14.       |
521| AVERR_IO_NO_PERMISSION<sup>14+</sup> | 5411005 | No access permission.<br>**Atomic service API**: This API can be used in atomic services since API version 14.       |
522| AVERR_IO_REQUEST_DENIED<sup>14+</sup> | 5411006 | The client request parameter is incorrect or exceeds the processing capability.<br>**Atomic service API**: This API can be used in atomic services since API version 14.       |
523| AVERR_IO_RESOURCE_NOT_FOUND<sup>14+</sup> | 5411007 | No network resource is available.<br>**Atomic service API**: This API can be used in atomic services since API version 14.       |
524| AVERR_IO_SSL_CLIENT_CERT_NEEDED<sup>14+</sup> | 5411008 | The server fails to verify the client certificate.<br>**Atomic service API**: This API can be used in atomic services since API version 14.       |
525| AVERR_IO_SSL_CONNECTION_FAILED<sup>14+</sup> | 5411009 | The SSL connection fails.<br>**Atomic service API**: This API can be used in atomic services since API version 14.       |
526| AVERR_IO_SSL_SERVER_CERT_UNTRUSTED<sup>14+</sup> | 5411010 | The client fails to verify the server certificate.<br>**Atomic service API**: This API can be used in atomic services since API version 14.       |
527| AVERR_IO_UNSUPPORTED_REQUEST<sup>14+</sup> | 5411011 | The request is not supported due to a network protocol error.<br>**Atomic service API**: This API can be used in atomic services since API version 14.       |
528| AVERR_SEEK_CONTINUOUS_UNSUPPORTED<sup>18+</sup> | 5410002 | The seek operation in SEEK_CONTINUOUS mode is not supported.<br>**Atomic service API**: This API can be used in atomic services since API version 18.       |
529| AVERR_SUPER_RESOLUTION_UNSUPPORTED<sup>18+</sup> | 5410003 | Super resolution is not supported.<br>**Atomic service API**: This API can be used in atomic services since API version 18.       |
530| AVERR_SUPER_RESOLUTION_NOT_ENABLED<sup>18+</sup> | 5410004 | Super resolution is not enabled.<br>**Atomic service API**: This API can be used in atomic services since API version 18.       |
531
532## MediaType<sup>8+</sup>
533
534Enumerates the media types.
535
536**System capability**: SystemCapability.Multimedia.Media.Core
537
538| Name          | Value                   | Description                |
539| -------------- | --------------------- | ------------------- |
540| MEDIA_TYPE_AUD | 0                     | Media.<br>**Atomic service API**: This API can be used in atomic services since API version 11.          |
541| MEDIA_TYPE_VID | 1                     | Video.<br>**Atomic service API**: This API can be used in atomic services since API version 11.         |
542| MEDIA_TYPE_SUBTITLE<sup>12+</sup> | 2    | Subtitle.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
543
544## CodecMimeType<sup>8+</sup>
545
546Enumerates the codec MIME types.
547
548**System capability**: SystemCapability.Multimedia.Media.Core
549
550| Name        | Value                   | Description                    |
551| ------------ | --------------------- | ------------------------ |
552| VIDEO_H263   | 'video/h263'          | Video in H.263 format.     |
553| VIDEO_AVC    | 'video/avc'           | Video in AVC format.      |
554| VIDEO_MPEG2  | 'video/mpeg2'         | Video in MPEG-2 format.    |
555| VIDEO_MPEG4  | 'video/mp4v-es'         | Video in MPEG-4 format.    |
556| VIDEO_VP8    | 'video/x-vnd.on2.vp8' | Video in VP8 format.      |
557| VIDEO_HEVC<sup>11+</sup>   | 'video/hevc'          | Video in H.265 format.|
558| AUDIO_AAC    | 'audio/mp4a-latm'     | Audio in MP4A-LATM format.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
559| AUDIO_VORBIS | 'audio/vorbis'        | Audio in Vorbis format.   |
560| AUDIO_FLAC   | 'audio/flac'          | Audio in FLAC format.     |
561| AUDIO_MP3<sup>12+</sup>   | 'audio/mpeg'          | Audio in MPEG format.     |
562| AUDIO_G711MU<sup>12+</sup>   | 'audio/g711mu'     | Audio in G.711 μ-law format.|
563| AUDIO_AMR_NB<sup>18+</sup>   | 'audio/3gpp'     | Audio in AMR-NB format.|
564| AUDIO_AMR_WB<sup>18+</sup>   | 'audio/amr-wb'     | Audio in AMR-WB format.|
565
566## MediaDescriptionKey<sup>8+</sup>
567
568Enumerates the media description keys.
569
570**System capability**: SystemCapability.Multimedia.Media.Core
571
572| Name                    | Value             | Description                                                        |
573| ------------------------ | --------------- | ------------------------------------------------------------ |
574| MD_KEY_TRACK_INDEX       | 'track_index'   | Track index, which is a number.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
575| MD_KEY_TRACK_TYPE        | 'track_type'    | Track type, which is a number. For details, see [MediaType](#mediatype8).<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
576| MD_KEY_CODEC_MIME        | 'codec_mime'    | Codec MIME type, which is a string.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
577| MD_KEY_DURATION          | 'duration'      | Media duration, which is a number, in units of ms.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
578| MD_KEY_BITRATE           | 'bitrate'       | Bit rate, which is a number, in units of bit/s.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
579| MD_KEY_WIDTH             | 'width'         | Video width, which is a number, in units of pixel.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
580| MD_KEY_HEIGHT            | 'height'        | Video height, which is a number, in units of pixel.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
581| MD_KEY_FRAME_RATE        | 'frame_rate'    | Video frame rate, which is a number, measured in frames per 100 seconds.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
582| MD_KEY_AUD_CHANNEL_COUNT | 'channel_count' | Number of audio channels, which is a number.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
583| MD_KEY_AUD_SAMPLE_RATE   | 'sample_rate'   | Sampling rate, which is a number, in units of Hz.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
584| MD_KEY_AUD_SAMPLE_DEPTH<sup>12+</sup>  | 'sample_depth'  | Bit depth, which is a number, in units of bits.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
585| MD_KEY_LANGUAGE<sup>12+</sup>  | 'language'  | Subtitle language, which is a string.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
586| MD_KEY_TRACK_NAME<sup>12+</sup>  | 'track_name'  | Track name, which is a string.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
587| MD_KEY_HDR_TYPE<sup>12+</sup>  | 'hdr_type'  | Codec track type, which is a string.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
588
589## PlaybackInfoKey<sup>12+</sup>
590
591Enumerates the playback description keys.
592
593**System capability**: SystemCapability.Multimedia.Media.Core
594
595| Name                    | Value             | Description                                                        |
596| ------------------------ | --------------- | ------------------------------------------------------------ |
597| SERVER_IP_ADDRESS        | 'server_ip_address'    | IP address of the server, which is a string. |
598| AVG_DOWNLOAD_RATE        | 'average_download_rate'| Average download rate, which is a number, in units of bit/s.|
599| DOWNLOAD_RATE            | 'download_rate'        | Download rate in one second, which is a number, in units of bit/s.|
600| IS_DOWNLOADING           | 'is_downloading'       | Download status, which is a number. The value **1** means that the downloaded is in progress, and **0** means that the download is complete.|
601| BUFFER_DURATION          | 'buffer_duration'      | Duration that the cached data can be played, which is a number, in units of seconds.|
602
603## BufferingInfoType<sup>8+</sup>
604
605Enumerates the buffering event types.
606
607**Atomic service API**: This API can be used in atomic services since API version 12.
608
609**System capability**: SystemCapability.Multimedia.Media.Core
610
611| Name             | Value  | Description                            |
612| ----------------- | ---- | -------------------------------- |
613| BUFFERING_START   | 1    | Buffering starts. When this event is triggered, the player pauses the playback.<br>**Atomic service API**: This API can be used in atomic services since API version 12.                  |
614| BUFFERING_END     | 2    | Buffering ends. When this event is triggered, the player resumes the playback.<br>**Atomic service API**: This API can be used in atomic services since API version 12.                  |
615| BUFFERING_PERCENT | 3    | Buffering percentage. You can use this event to monitor the buffering status.<br>**Atomic service API**: This API can be used in atomic services since API version 12.                |
616| CACHED_DURATION   | 4    | Estimated duration, in ms, that the buffered data can be played. This event is triggered once the data change amount in the buffer exceeds 500 ms. You can use this event to develop a progress bar.<br>**Atomic service API**: This API can be used in atomic services since API version 12. |
617
618## StateChangeReason<sup>9+</sup>
619
620Enumerates the reasons for the state transition of the **AVPlayer** or **AVRecorder** instance. The enum value is reported together with **state**.
621
622**Atomic service API**: This API can be used in atomic services since API version 11.
623
624**System capability**: SystemCapability.Multimedia.Media.Core
625
626| Name      | Value  | Description                                                        |
627| ---------- | ---- | ------------------------------------------------------------ |
628| USER       | 1    | State transition triggered by user behavior. It happens when a user or the client calls an API.|
629| BACKGROUND | 2    | State transition caused by background system behavior. For example, if an application does not have the permission of Media Controller, the application is forcibly suspended or stopped by the system when it switches to the background.|
630
631## AVPlayer<sup>9+</sup>
632
633A playback management class that provides APIs to manage and play media assets. Before calling any API in **AVPlayer**, you must use [createAVPlayer()](#mediacreateavplayer9) to create an **AVPlayer** instance.
634
635For 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).
636
637> **NOTE**
638>
639> When using the **AVPlayer** instance, you are advised to register the following callbacks to proactively obtain status changes:
640> - [on('stateChange')](#onstatechange9): listens for AVPlayer state changes.
641> - [on('error')](#onerror9): listens for error events.
642
643### Attributes
644
645**System capability**: SystemCapability.Multimedia.Media.AVPlayer
646
647| Name                                               | Type                                                        | Read-Only| Optional| Description                                                        |
648| --------------------------------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ |
649| url<sup>9+</sup>                                    | string                                                       | No  | Yes  | URL of the media asset. It can be set only when the AVPlayer is in the idle state. <br>The video formats MP4, MPEG-TS, and MKV are supported.<br>The audio formats M4A, AAC, MP3, OGG, WAV, FLAC, and AMR are supported.<br>**Example of supported URLs**:<br>1. FD: fd://xx<br>![](figures/en-us_image_url.png)<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.|
650| fdSrc<sup>9+</sup>                                  | [AVFileDescriptor](#avfiledescriptor9)                       | No  | Yes  | FD of the media asset. It can be set only when the AVPlayer is in the idle state.<br>This attribute is required when media assets of an application are continuously stored in a file.<br>The video formats MP4, MPEG-TS, and MKV are supported.<br>The audio formats M4A, AAC, MP3, OGG, WAV, FLAC, and AMR are supported.<br>**Example:**<br>Assume that a media file that stores continuous assets consists of the following:<br>Video 1 (address offset: 0, byte length: 100)<br>Video 2 (address offset: 101; byte length: 50)<br>Video 3 (address offset: 151, byte length: 150)<br>1. To play video 1: AVFileDescriptor { fd = resource handle; offset = 0; length = 100; }<br>2. To play video 2: AVFileDescriptor { fd = resource handle; offset = 101; length = 50; }<br>3. To play video 3: AVFileDescriptor { fd = resource handle; offset = 151; length = 150; }<br>To play an independent media file, use **src=fd://xx**.<br>**NOTE**<br>WebM is no longer supported since API version 11.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
651| dataSrc<sup>10+</sup>                               | [AVDataSrcDescriptor](#avdatasrcdescriptor10)                | No  | Yes  | Descriptor of a streaming media asset. It can be set only when the AVPlayer is in the idle state.<br>Use scenario: An application starts playing a media file while the file is still being downloaded from the remote to the local host.<br>The video formats MP4, MPEG-TS, and MKV are supported.<br>The audio formats M4A, AAC, MP3, OGG, WAV, FLAC, and AMR are supported.<br>**Example:**<br>A user is obtaining an audio and video file from a remote server and wants to play the downloaded file content. To implement this scenario, do as follows:<br>1. Obtain the total file size, in bytes. If the total size cannot be obtained, set **fileSize** to **-1**.<br>2. Implement the **func** callback to fill in data. If **fileSize** is **-1**, the format of **func** is **func(buffer: ArrayBuffer, length: number)**, and the AVPlayer obtains data in sequence; otherwise, the format is **func(buffer: ArrayBuffer, length: number, pos: number)**, and the AVPlayer seeks and obtains data in the required positions.<br>3. Set **AVDataSrcDescriptor {fileSize = size, callback = func}**.<br>**Notes:**<br>If the media file to play is in MP4/M4A format, ensure that the **moov** field (specifying the media information) is before the **mdat** field (specifying the media data) or the fields before the **moov** field is less than 10 MB. Otherwise, the parsing fails and the media file cannot be played.<br>**NOTE**<br>WebM is no longer supported since API version 11.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
652| surfaceId<sup>9+</sup>                              | string                                                       | No  | Yes  | Video window ID. By default, there is no video window.<br>This parameter can be set when the AVPlayer is in the initialized state.<br>It can be set again when the AVPlayer is in the prepared, playing, paused, completed, or stopped state, in the prerequisite that the video window ID has been set in the initialized state. After the new setting is performed, the video is played in the new window.<br>It is used to render the window for video playback and therefore is not required in audio-only playback scenarios.<br>**Example:**<br>[Create a surface ID through XComponent](../apis-arkui/arkui-ts/ts-basic-components-xcomponent.md#getxcomponentsurfaceid).<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
653| loop<sup>9+</sup>                                   | boolean                                                      | No  | No  | Whether to loop playback. The value **true** means to loop playback, and **false** (default) means the opposite. It is a dynamic attribute<br>and can be set only when the AVPlayer is in the prepared, playing, paused, or completed state.<br>This setting is not supported in live mode.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
654| videoScaleType<sup>9+</sup>                         | [VideoScaleType](#videoscaletype9)                           | No  | Yes  | Video scale type. The default value is **VIDEO_SCALE_TYPE_FIT**. It is a dynamic attribute<br>and can be set only when the AVPlayer is in the prepared, playing, paused, or completed state.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
655| audioInterruptMode<sup>9+</sup>                     | [audio.InterruptMode](../apis-audio-kit/js-apis-audio.md#interruptmode9)       | No  | Yes  | Audio interruption mode. The default value is **SHARE_MODE**. It is a dynamic attribute<br>and can be set only when the AVPlayer is in the prepared, playing, paused, or completed state.<br>To take effect, this attribute must be set before [play()](#play9) is called for the first time.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
656| audioRendererInfo<sup>10+</sup>                     | [audio.AudioRendererInfo](../apis-audio-kit/js-apis-audio.md#audiorendererinfo8) | No  | Yes  | Audio renderer information. If the media source contains videos, the default value of **usage** is **STREAM_USAGE_MOVIE**. Otherwise, the default value of **usage** is **STREAM_USAGE_MUSIC**. The default value of **rendererFlags** is 0. If the default value of **usage** does not meet the requirements, configure [audio.AudioRendererInfo](../apis-audio-kit/js-apis-audio.md#audiorendererinfo8).<br>This parameter can be set only when the AVPlayer is in the initialized state.<br>To take effect, this attribute must be set before [prepare()](#prepare9) is called for the first time.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
657| audioEffectMode<sup>10+</sup>                       | [audio.AudioEffectMode](../apis-audio-kit/js-apis-audio.md#audioeffectmode10)  | No  | Yes  | Audio effect mode. The audio effect mode is a dynamic attribute and is restored to the default value **EFFECT_DEFAULT** when **usage** of **audioRendererInfo** is changed. It can be set only when the AVPlayer is in the prepared, playing, paused, or completed state.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
658| state<sup>9+</sup>                                  | [AVPlayerState](#avplayerstate9)                             | Yes  | No  | AVPlayer state. It can be used as a query parameter when the AVPlayer is in any state.<br>**Atomic service API**: This API can be used in atomic services since API version 12.                 |
659| 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.|
660| 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.|
661| 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.|
662| 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.|
663
664### on('stateChange')<sup>9+</sup>
665
666on(type: 'stateChange', callback: OnAVPlayerStateChangeHandle): void
667
668Subscribes to AVPlayer state changes.
669
670**Atomic service API**: This API can be used in atomic services since API version 11.
671
672**System capability**: SystemCapability.Multimedia.Media.AVPlayer
673
674**Parameters**
675
676| Name  | Type    | Mandatory| Description                                                        |
677| -------- | -------- | ---- | ------------------------------------------------------------ |
678| type     | string   | Yes  | Event type, which is **'stateChange'** in this case. This event can be triggered by both user operations and the system.|
679| callback | [OnAVPlayerStateChangeHandle](#onavplayerstatechangehandle12) | Yes  | Callback invoked when the event is triggered.|
680
681**Example**
682
683```ts
684avPlayer.on('stateChange', async (state: string, reason: media.StateChangeReason) => {
685  switch (state) {
686    case 'idle':
687      console.info('state idle called');
688      break;
689    case 'initialized':
690      console.info('initialized prepared called');
691      break;
692    case 'prepared':
693      console.info('state prepared called');
694      break;
695    case 'playing':
696      console.info('state playing called');
697      break;
698    case 'paused':
699      console.info('state paused called');
700      break;
701    case 'completed':
702      console.info('state completed called');
703      break;
704    case 'stopped':
705      console.info('state stopped called');
706      break;
707    case 'released':
708      console.info('state released called');
709      break;
710    case 'error':
711      console.info('state error called');
712      break;
713    default:
714      console.info('unknown state :' + state);
715      break;
716  }
717})
718```
719
720### off('stateChange')<sup>9+</sup>
721
722off(type: 'stateChange', callback?: OnAVPlayerStateChangeHandle): void
723
724Unsubscribes from AVPlayer state changes.
725
726**Atomic service API**: This API can be used in atomic services since API version 11.
727
728**System capability**: SystemCapability.Multimedia.Media.AVPlayer
729
730**Parameters**
731
732| Name| Type  | Mandatory| Description                                                 |
733| ------ | ------ | ---- | ----------------------------------------------------- |
734| type   | string | Yes  | Event type, which is **'stateChange'** in this case.|
735| callback   | [OnAVPlayerStateChangeHandle](#onavplayerstatechangehandle12) | No  | Callback invoked when the event is triggered.<br>This parameter is supported since API version 12.|
736
737**Example**
738
739```ts
740avPlayer.off('stateChange')
741```
742
743### on('error')<sup>9+</sup>
744
745on(type: 'error', callback: ErrorCallback): void
746
747Subscribes to AVPlayer errors. This event is used only for error prompt and does not require the user to stop playback control. If [AVPlayerState](#avplayerstate9) is also switched to error, call [reset()](#reset9) or [release()](#release9) to exit the playback.
748
749**Atomic service API**: This API can be used in atomic services since API version 11.
750
751**System capability**: SystemCapability.Multimedia.Media.AVPlayer
752
753**Parameters**
754
755| Name  | Type    | Mandatory| Description                                                        |
756| -------- | -------- | ---- | ------------------------------------------------------------ |
757| type     | string   | Yes  | Event type, which is **'error'** in this case. This event can be triggered by both user operations and the system.|
758| callback | [ErrorCallback](../apis-basic-services-kit/js-apis-base.md#errorcallback) | Yes  | Callback used to return the error code ID and error message.|
759
760**Error codes**
761
762For details about the error codes, see [Media Error Codes](errorcode-media.md).
763
764In 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.
765
766| ID| Error Message             |
767| -------- | --------------------- |
768| 201      | Permission denied.     |
769| 401      | The parameter check failed. |
770| 801      | Capability not supported. |
771| 5400101  | No memory. |
772| 5400102  | Operation not allowed.|
773| 5400103  | I/O error.             |
774| 5400104  | Time out.              |
775| 5400105  | Service died.         |
776| 5400106  | Unsupported format.     |
777| 5411001  | IO can not find host.    |
778| 5411002  | IO connection timeout.  |
779| 5411003  | IO network abnormal.     |
780| 5411004  | IO network unavailable.  |
781| 5411005  | IO no permission.        |
782| 5411006  | IO request denied.  |
783| 5411007  | IO resource not found. |
784| 5411008  | IO SSL client cert needed.    |
785| 5411009  | IO SSL connect fail.     |
786| 5411010  | IO SSL server cert untrusted.    |
787| 5411011  | IO unsupported request.      |
788
789**Example**
790
791```ts
792import { BusinessError } from '@kit.BasicServicesKit';
793
794avPlayer.on('error', (error: BusinessError) => {
795  console.info('error happened,and error message is :' + error.message)
796  console.info('error happened,and error code is :' + error.code)
797})
798```
799
800### off('error')<sup>9+</sup>
801
802off(type: 'error', callback?: ErrorCallback): void
803
804Unsubscribes from AVPlayer errors.
805
806**Atomic service API**: This API can be used in atomic services since API version 11.
807
808**System capability**: SystemCapability.Multimedia.Media.AVPlayer
809
810**Parameters**
811
812| Name| Type  | Mandatory| Description                                     |
813| ------ | ------ | ---- | ----------------------------------------- |
814| type   | string | Yes  | Event type, which is **'error'** in this case.|
815| 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.|
816
817**Example**
818
819```ts
820avPlayer.off('error')
821```
822
823### setMediaSource<sup>12+</sup>
824
825setMediaSource(src:MediaSource, strategy?: PlaybackStrategy): Promise\<void>
826
827Sets 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.
828
829**Atomic service API**: This API can be used in atomic services since API version 12.
830
831**System capability**: SystemCapability.Multimedia.Media.AVPlayer
832
833**Parameters**
834
835| Name  | Type    | Mandatory| Description                |
836| -------- | -------- | ---- | -------------------- |
837| src | [MediaSource](#mediasource12) | Yes  | Source of the streaming media to pre-download.|
838| strategy | [PlaybackStrategy](#playbackstrategy12) | No  | strategy for playing the pre-downloaded streaming media.|
839
840**Return value**
841
842| Type          | Description                                      |
843| -------------- | ------------------------------------------ |
844| Promise\<void> | Promise that returns no value.|
845
846**Error codes**
847
848For details about the error codes, see [Media Error Codes](errorcode-media.md).
849
850| ID| Error Message                                 |
851| -------- | ----------------------------------------- |
852| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed.      |
853| 5400102  | Operation not allowed. Return by promise. |
854
855**Example**
856
857<!--code_no_check-->
858```ts
859let player = await media.createAVPlayer();
860let headers: Record<string, string> = {"User-Agent" : "User-Agent-Value"};
861let mediaSource : media.MediaSource = media.createMediaSourceWithUrl("http://xxx",  headers);
862let playStrategy : media.PlaybackStrategy = {
863  preferredWidth: 1,
864  preferredHeight: 2,
865  preferredBufferDuration: 3,
866  preferredHdr: false,
867  preferredBufferDurationForPlaying: 1,
868  thresholdForAutoQuickPlay: 5
869};
870player.setMediaSource(mediaSource, playStrategy);
871```
872
873### setPlaybackStrategy<sup>12+</sup>
874
875setPlaybackStrategy(strategy: PlaybackStrategy): Promise\<void>
876
877Sets a playback strategy. This API can be called only when the AVPlayer is in the initialized state.
878
879**Atomic service API**: This API can be used in atomic services since API version 12.
880
881**System capability**: SystemCapability.Multimedia.Media.AVPlayer
882
883**Parameters**
884
885| Name  | Type    | Mandatory| Description                |
886| -------- | -------- | ---- | -------------------- |
887| strategy | [PlaybackStrategy](#playbackstrategy12) | Yes  | Playback strategy.|
888
889**Return value**
890
891| Type          | Description                                 |
892| -------------- | ------------------------------------ |
893| Promise\<void> | Promise that returns no value.|
894
895**Error codes**
896
897For details about the error codes, see [Media Error Codes](errorcode-media.md).
898
899| ID| Error Message                                 |
900| -------- | ----------------------------------------- |
901| 401      | Parameter error. Possible causes: 1. Incorrect parameter types. 2. Parameter verification failed. |
902| 5400102  | Operation not allowed. Return by promise. |
903
904**Example**
905
906<!--code_no_check-->
907```ts
908import { common } from '@kit.AbilityKit';
909
910let player = await media.createAVPlayer();
911let context = getContext(this) as common.UIAbilityContext
912let fileDescriptor = await context.resourceManager.getRawFd('xxx.mp4')
913player.fdSrc = fileDescriptor
914let playStrategy : media.PlaybackStrategy = {
915  preferredWidth: 1,
916  preferredHeight: 2,
917  preferredBufferDuration: 3,
918  preferredHdr: false,
919  mutedMediaType: media.MediaType.MEDIA_TYPE_AUD,
920  preferredBufferDurationForPlaying: 1,
921  thresholdForAutoQuickPlay: 5
922};
923player.setPlaybackStrategy(playStrategy);
924```
925
926### setPlaybackRange<sup>18+</sup>
927
928setPlaybackRange(startTimeMs: number, endTimeMs: number, mode?: SeekMode) : Promise\<void>
929
930Sets the playback range and seeks to the start position of the range based on the specified [SeekMode](#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.
931
932**Atomic service API**: This API can be used in atomic services since API version 18.
933
934**System capability**: SystemCapability.Multimedia.Media.AVPlayer
935
936**Parameters**
937
938| Name  | Type                  | Mandatory| Description                       |
939| -------- | ---------------------- | ---- | --------------------------- |
940| 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.|
941| 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.|
942| mode | [SeekMode](#seekmode8) | No  | Seek mode, which can be **SeekMode.SEEK_PREV_SYNC** or **SeekMode.SEEK_CLOSEST**.<br>The default value is **SeekMode.SEEK_PREV_SYNC**.|
943
944**Error codes**
945
946For details about the error codes, see [Media Error Codes](errorcode-media.md).
947
948| ID| Error Message                                  |
949| -------- | ------------------------------------------ |
950| 401  | The parameter check failed. Return by promise. |
951| 5400102  | Operation not allowed. Return by promise. |
952
953**Example**
954
955```ts
956import { media } from '@kit.MediaKit';
957import { BusinessError } from '@kit.BasicServicesKit';
958
959avPlayer.setPlaybackRange(0, 6000, media.SeekMode.SEEK_CLOSEST).then(() => {
960  console.info('Succeeded setPlaybackRange');
961}).catch((err: BusinessError) => {
962  console.error('Failed to setPlaybackRange' + err.message);
963});
964```
965
966### prepare<sup>9+</sup>
967
968prepare(callback: AsyncCallback\<void>): void
969
970Prepares 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.
971
972**Atomic service API**: This API can be used in atomic services since API version 11.
973
974**System capability**: SystemCapability.Multimedia.Media.AVPlayer
975
976**Parameters**
977
978| Name  | Type    | Mandatory| Description                |
979| -------- | -------- | ---- | -------------------- |
980| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.|
981
982**Error codes**
983
984For details about the error codes, see [Media Error Codes](errorcode-media.md).
985
986| ID| Error Message                                  |
987| -------- | ------------------------------------------ |
988| 5400102  | Operation not allowed. Return by callback. |
989| 5400106  | Unsupported format. Return by callback.      |
990
991**Example**
992
993```ts
994import { BusinessError } from '@kit.BasicServicesKit';
995
996avPlayer.prepare((err: BusinessError) => {
997  if (err) {
998    console.error('Failed to prepare,error message is :' + err.message)
999  } else {
1000    console.info('Succeeded in preparing');
1001  }
1002})
1003```
1004
1005### prepare<sup>9+</sup>
1006
1007prepare(): Promise\<void>
1008
1009Prepares 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.
1010
1011**Atomic service API**: This API can be used in atomic services since API version 11.
1012
1013**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1014
1015**Return value**
1016
1017| Type          | Description                     |
1018| -------------- | ------------------------- |
1019| Promise\<void> | Promise that returns no value.|
1020
1021**Error codes**
1022
1023For details about the error codes, see [Media Error Codes](errorcode-media.md).
1024
1025| ID| Error Message                                 |
1026| -------- | ----------------------------------------- |
1027| 5400102  | Operation not allowed. Return by promise. |
1028| 5400106  | Unsupported format. Return by promise.      |
1029
1030**Example**
1031
1032```ts
1033import { BusinessError } from '@kit.BasicServicesKit';
1034
1035avPlayer.prepare().then(() => {
1036  console.info('Succeeded in preparing');
1037}, (err: BusinessError) => {
1038  console.error('Failed to prepare,error message is :' + err.message)
1039})
1040```
1041
1042### setMediaMuted<sup>12+</sup>
1043
1044setMediaMuted(mediaType: MediaType,  muted: boolean ): Promise\<void>
1045
1046Mutes or unmutes the audio. This API can be called only when the AVPlayer is in the prepared, playing, paused, or completed state. The **mediaType** parameter can be set only to the audio format.
1047
1048**Atomic service API**: This API can be used in atomic services since API version 12.
1049
1050**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1051
1052**Parameters**
1053
1054| Name  | Type    | Mandatory| Description                |
1055| -------- | -------- | ---- | -------------------- |
1056| mediaType | [MediaType](#mediatype8) | Yes  | Media type.|
1057| muted | boolean | Yes  | Whether to mute the audio.|
1058
1059**Return value**
1060
1061| Type          | Description                     |
1062| -------------- | ------------------------- |
1063| Promise\<void> | Promise that returns no value.|
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| 401 | The parameter check failed. Return by promise. |
1072| 5400102 | Operation not allowed. Return by promise. |
1073
1074**Example**
1075
1076```ts
1077import { BusinessError } from '@kit.BasicServicesKit';
1078
1079avPlayer.prepare().then(() => {
1080  console.info('Succeeded in preparing');
1081  avPlayer.setMediaMuted(media.MediaType.MEDIA_TYPE_AUD, true)
1082}, (err: BusinessError) => {
1083  console.error('Failed to prepare,error message is :' + err.message)
1084})
1085```
1086
1087### play<sup>9+</sup>
1088
1089play(callback: AsyncCallback\<void>): void
1090
1091Starts 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.
1092
1093**Atomic service API**: This API can be used in atomic services since API version 11.
1094
1095**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1096
1097**Parameters**
1098
1099| Name  | Type    | Mandatory| Description                |
1100| -------- | -------- | ---- | -------------------- |
1101| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.|
1102
1103**Error codes**
1104
1105For details about the error codes, see [Media Error Codes](errorcode-media.md).
1106
1107| ID| Error Message                                  |
1108| -------- | ------------------------------------------ |
1109| 5400102  | Operation not allowed. Return by callback. |
1110
1111**Example**
1112
1113```ts
1114import { BusinessError } from '@kit.BasicServicesKit';
1115
1116avPlayer.play((err: BusinessError) => {
1117  if (err) {
1118    console.error('Failed to play,error message is :' + err.message)
1119  } else {
1120    console.info('Succeeded in playing');
1121  }
1122})
1123```
1124
1125### play<sup>9+</sup>
1126
1127play(): Promise\<void>
1128
1129Starts 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.
1130
1131**Atomic service API**: This API can be used in atomic services since API version 11.
1132
1133**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1134
1135**Return value**
1136
1137| Type          | Description                     |
1138| -------------- | ------------------------- |
1139| Promise\<void> | Promise that returns no value.|
1140
1141**Error codes**
1142
1143For details about the error codes, see [Media Error Codes](errorcode-media.md).
1144
1145| ID| Error Message                                 |
1146| -------- | ----------------------------------------- |
1147| 5400102  | Operation not allowed. Return by promise. |
1148
1149**Example**
1150
1151```ts
1152import { BusinessError } from '@kit.BasicServicesKit';
1153
1154avPlayer.play().then(() => {
1155  console.info('Succeeded in playing');
1156}, (err: BusinessError) => {
1157  console.error('Failed to play,error message is :' + err.message)
1158})
1159```
1160
1161### pause<sup>9+</sup>
1162
1163pause(callback: AsyncCallback\<void>): void
1164
1165Pauses 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.
1166
1167**Atomic service API**: This API can be used in atomic services since API version 11.
1168
1169**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1170
1171**Parameters**
1172
1173| Name  | Type    | Mandatory| Description                |
1174| -------- | -------- | ---- | -------------------- |
1175| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.|
1176
1177**Error codes**
1178
1179For details about the error codes, see [Media Error Codes](errorcode-media.md).
1180
1181| ID| Error Message                                  |
1182| -------- | ------------------------------------------ |
1183| 5400102  | Operation not allowed. Return by callback. |
1184
1185**Example**
1186
1187```ts
1188import { BusinessError } from '@kit.BasicServicesKit';
1189
1190avPlayer.pause((err: BusinessError) => {
1191  if (err) {
1192    console.error('Failed to pause,error message is :' + err.message)
1193  } else {
1194    console.info('Succeeded in pausing');
1195  }
1196})
1197```
1198
1199### pause<sup>9+</sup>
1200
1201pause(): Promise\<void>
1202
1203Pauses 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.
1204
1205**Atomic service API**: This API can be used in atomic services since API version 11.
1206
1207**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1208
1209**Return value**
1210
1211| Type          | Description                     |
1212| -------------- | ------------------------- |
1213| Promise\<void> | Promise that returns no value.|
1214
1215**Error codes**
1216
1217For details about the error codes, see [Media Error Codes](errorcode-media.md).
1218
1219| ID| Error Message                                 |
1220| -------- | ----------------------------------------- |
1221| 5400102  | Operation not allowed. Return by promise. |
1222
1223**Example**
1224
1225```ts
1226import { BusinessError } from '@kit.BasicServicesKit';
1227
1228avPlayer.pause().then(() => {
1229  console.info('Succeeded in pausing');
1230}, (err: BusinessError) => {
1231  console.error('Failed to pause,error message is :' + err.message)
1232})
1233```
1234
1235### stop<sup>9+</sup>
1236
1237stop(callback: AsyncCallback\<void>): void
1238
1239Stops 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.
1240
1241**Atomic service API**: This API can be used in atomic services since API version 11.
1242
1243**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1244
1245**Parameters**
1246
1247| Name  | Type    | Mandatory| Description                |
1248| -------- | -------- | ---- | -------------------- |
1249| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.|
1250
1251**Error codes**
1252
1253For details about the error codes, see [Media Error Codes](errorcode-media.md).
1254
1255| ID| Error Message                                  |
1256| -------- | ------------------------------------------ |
1257| 5400102  | Operation not allowed. Return by callback. |
1258
1259**Example**
1260
1261```ts
1262import { BusinessError } from '@kit.BasicServicesKit';
1263
1264avPlayer.stop((err: BusinessError) => {
1265  if (err) {
1266    console.error('Failed to stop,error message is :' + err.message)
1267  } else {
1268    console.info('Succeeded in stopping');
1269  }
1270})
1271```
1272
1273### stop<sup>9+</sup>
1274
1275stop(): Promise\<void>
1276
1277Stops 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.
1278
1279**Atomic service API**: This API can be used in atomic services since API version 11.
1280
1281**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1282
1283**Return value**
1284
1285| Type          | Description                     |
1286| -------------- | ------------------------- |
1287| Promise\<void> | Promise that returns no value.|
1288
1289**Error codes**
1290
1291For details about the error codes, see [Media Error Codes](errorcode-media.md).
1292
1293| ID| Error Message                                 |
1294| -------- | ----------------------------------------- |
1295| 5400102  | Operation not allowed. Return by promise. |
1296
1297**Example**
1298
1299```ts
1300import { BusinessError } from '@kit.BasicServicesKit';
1301
1302avPlayer.stop().then(() => {
1303  console.info('Succeeded in stopping');
1304}, (err: BusinessError) => {
1305  console.error('Failed to stop,error message is :' + err.message)
1306})
1307```
1308
1309### reset<sup>9+</sup>
1310
1311reset(callback: AsyncCallback\<void>): void
1312
1313Resets 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.
1314
1315**Atomic service API**: This API can be used in atomic services since API version 11.
1316
1317**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1318
1319**Parameters**
1320
1321| Name  | Type    | Mandatory| Description                |
1322| -------- | -------- | ---- | -------------------- |
1323| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.|
1324
1325**Error codes**
1326
1327For details about the error codes, see [Media Error Codes](errorcode-media.md).
1328
1329| ID| Error Message                                  |
1330| -------- | ------------------------------------------ |
1331| 5400102  | Operation not allowed. Return by callback. |
1332
1333**Example**
1334
1335```ts
1336import { BusinessError } from '@kit.BasicServicesKit';
1337
1338avPlayer.reset((err: BusinessError) => {
1339  if (err) {
1340    console.error('Failed to reset,error message is :' + err.message)
1341  } else {
1342    console.info('Succeeded in resetting');
1343  }
1344})
1345```
1346
1347### reset<sup>9+</sup>
1348
1349reset(): Promise\<void>
1350
1351Resets 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.
1352
1353**Atomic service API**: This API can be used in atomic services since API version 11.
1354
1355**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1356
1357**Return value**
1358
1359| Type          | Description                     |
1360| -------------- | ------------------------- |
1361| Promise\<void> | Promise that returns no value.|
1362
1363**Error codes**
1364
1365For details about the error codes, see [Media Error Codes](errorcode-media.md).
1366
1367| ID| Error Message                                 |
1368| -------- | ----------------------------------------- |
1369| 5400102  | Operation not allowed. Return by promise. |
1370
1371**Example**
1372
1373```ts
1374import { BusinessError } from '@kit.BasicServicesKit';
1375
1376avPlayer.reset().then(() => {
1377  console.info('Succeeded in resetting');
1378}, (err: BusinessError) => {
1379  console.error('Failed to reset,error message is :' + err.message)
1380})
1381```
1382
1383### release<sup>9+</sup>
1384
1385release(callback: AsyncCallback\<void>): void
1386
1387Releases 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.
1388
1389**Atomic service API**: This API can be used in atomic services since API version 11.
1390
1391**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1392
1393**Parameters**
1394
1395| Name  | Type    | Mandatory| Description                |
1396| -------- | -------- | ---- | -------------------- |
1397| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.|
1398
1399**Error codes**
1400
1401For details about the error codes, see [Media Error Codes](errorcode-media.md).
1402
1403| ID| Error Message                                  |
1404| -------- | ------------------------------------------ |
1405| 5400102  | Operation not allowed. Return by callback. |
1406
1407**Example**
1408
1409```ts
1410import { BusinessError } from '@kit.BasicServicesKit';
1411
1412avPlayer.release((err: BusinessError) => {
1413  if (err) {
1414    console.error('Failed to release,error message is :' + err.message)
1415  } else {
1416    console.info('Succeeded in releasing');
1417  }
1418})
1419```
1420
1421### release<sup>9+</sup>
1422
1423release(): Promise\<void>
1424
1425Releases 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.
1426
1427**Atomic service API**: This API can be used in atomic services since API version 11.
1428
1429**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1430
1431**Return value**
1432
1433| Type          | Description                     |
1434| -------------- | ------------------------- |
1435| Promise\<void> | Promise that returns no value.|
1436
1437**Error codes**
1438
1439For details about the error codes, see [Media Error Codes](errorcode-media.md).
1440
1441| ID| Error Message                                 |
1442| -------- | ----------------------------------------- |
1443| 5400102  | Operation not allowed. Return by promise. |
1444
1445**Example**
1446
1447```ts
1448import { BusinessError } from '@kit.BasicServicesKit';
1449
1450avPlayer.release().then(() => {
1451  console.info('Succeeded in releasing');
1452}, (err: BusinessError) => {
1453  console.error('Failed to release,error message is :' + err.message)
1454})
1455```
1456
1457### getTrackDescription<sup>9+</sup>
1458
1459getTrackDescription(callback: AsyncCallback\<Array\<MediaDescription>>): void
1460
1461Obtains 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.
1462
1463**Atomic service API**: This API can be used in atomic services since API version 11.
1464
1465**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1466
1467**Parameters**
1468
1469| Name  | Type                                                        | Mandatory| Description                                        |
1470| -------- | ------------------------------------------------------------ | ---- | -------------------------------------------- |
1471| callback | AsyncCallback<Array<[MediaDescription](#mediadescription8)>> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the MediaDescription array obtained; otherwise, **err** is an error object.|
1472
1473**Error codes**
1474
1475For details about the error codes, see [Media Error Codes](errorcode-media.md).
1476
1477| ID| Error Message                                  |
1478| -------- | ------------------------------------------ |
1479| 5400102  | Operation not allowed. Return by callback. |
1480
1481**Example**
1482
1483```ts
1484import { BusinessError } from '@kit.BasicServicesKit';
1485
1486avPlayer.getTrackDescription((error: BusinessError, arrList: Array<media.MediaDescription>) => {
1487  if ((arrList) != null) {
1488    console.info('Succeeded in doing getTrackDescription');
1489  } else {
1490    console.error(`Failed to do getTrackDescription, error:${error}`);
1491  }
1492});
1493```
1494
1495### getTrackDescription<sup>9+</sup>
1496
1497getTrackDescription(): Promise\<Array\<MediaDescription>>
1498
1499Obtains 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.
1500
1501**Atomic service API**: This API can be used in atomic services since API version 11.
1502
1503**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1504
1505**Return value**
1506
1507| Type                                                  | Description                                             |
1508| ------------------------------------------------------ | ------------------------------------------------- |
1509| Promise<Array<[MediaDescription](#mediadescription8)>> | Promise used to return the MediaDescription array that holds the audio and video track information.|
1510
1511**Error codes**
1512
1513For details about the error codes, see [Media Error Codes](errorcode-media.md).
1514
1515| ID| Error Message                                 |
1516| -------- | ----------------------------------------- |
1517| 5400102  | Operation not allowed. Return by promise. |
1518
1519**Example**
1520
1521```ts
1522import { BusinessError } from '@kit.BasicServicesKit';
1523
1524avPlayer.getTrackDescription().then((arrList: Array<media.MediaDescription>) => {
1525  console.info('Succeeded in getting TrackDescription');
1526}).catch((error: BusinessError) => {
1527  console.error(`Failed to get TrackDescription, error:${error}`);
1528});
1529```
1530
1531### getSelectedTracks<sup>12+</sup>
1532
1533getSelectedTracks(): Promise\<Array\<number>>
1534
1535Obtains 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.
1536
1537**Atomic service API**: This API can be used in atomic services since API version 12.
1538
1539**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1540
1541**Return value**
1542
1543| Type                                                  | Description                                             |
1544| ------------------------------------------------------ | ------------------------------------------------- |
1545| Promise\<Array\<number>> | Promise used to return the index array.|
1546
1547**Error codes**
1548
1549For details about the error codes, see [Media Error Codes](errorcode-media.md).
1550
1551| ID| Error Message                                 |
1552| -------- | ----------------------------------------- |
1553| 5400102  | Operation not allowed. |
1554
1555**Example**
1556
1557```ts
1558import { BusinessError } from '@kit.BasicServicesKit';
1559
1560avPlayer.getSelectedTracks().then((arrList: Array<number>) => {
1561  console.info('Succeeded in getting SelectedTracks');
1562}).catch((error: BusinessError) => {
1563  console.error(`Failed to get SelectedTracks, error:${error}`);
1564});
1565```
1566
1567### getPlaybackInfo<sup>12+</sup>
1568
1569getPlaybackInfo(): Promise\<PlaybackInfo>
1570
1571Obtains 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.
1572
1573**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1574
1575**Return value**
1576
1577| Type                                                  | Description                                             |
1578| ------------------------------------------------------ | ------------------------------------------------- |
1579| Promise<[PlaybackInfo](#playbackinfo12)> | Promise used to return **PlaybackInfo**.|
1580
1581**Example**
1582
1583```ts
1584import { BusinessError } from '@kit.BasicServicesKit';
1585
1586let avPlayer: media.AVPlayer | undefined = undefined;
1587let playbackInfo: media.PlaybackInfo | undefined = undefined;
1588media.createAVPlayer(async (err: BusinessError, player: media.AVPlayer) => {
1589  if (player != null) {
1590    avPlayer = player;
1591    console.info(`Succeeded in creating AVPlayer`);
1592    if (avPlayer) {
1593      try {
1594        playbackInfo = await avPlayer.getPlaybackInfo();
1595        console.info(`AVPlayer getPlaybackInfo = ${JSON.stringify(playbackInfo)}`); // Print PlaybackInfo.
1596      } catch (error) {
1597        console.error(`error = ${error}`);
1598      }
1599    }
1600  } else {
1601    console.error(`Failed to create AVPlayer, error message:${err.message}`);
1602  }
1603});
1604```
1605
1606### getPlaybackPosition<sup>18+</sup>
1607
1608getPlaybackPosition(): number
1609
1610Obtains the current playback position. This API can be used in the prepared, playing, paused, or completed state.
1611
1612**Atomic service API**: This API can be used in atomic services since API version 18.
1613
1614**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1615
1616**Return value**
1617
1618| Type                                                  | Description                                             |
1619| ------------------------------------------------------ | ------------------------------------------------- |
1620| number | Current playback time, in milliseconds.|
1621
1622**Error codes**
1623
1624For details about the error codes, see [Media Error Codes](errorcode-media.md).
1625
1626| ID| Error Message                                 |
1627| -------- | ----------------------------------------- |
1628| 5400102  | Operation not allowed. |
1629
1630**Example**
1631
1632```ts
1633import { BusinessError } from '@kit.BasicServicesKit';
1634
1635avPlayer.prepare().then(() => {
1636  console.info('Succeeded in preparing')
1637  let playbackPosition: number = avPlayer.getPlaybackPosition()
1638  console.info(`AVPlayer getPlaybackPosition== ${playbackPosition}`)
1639}, (err: BusinessError) => {
1640  console.error('Failed to prepare,error message is :' + err.message)
1641})
1642```
1643
1644### selectTrack<sup>12+</sup>
1645
1646selectTrack(index: number, mode?: SwitchMode): Promise\<void>
1647
1648Selects 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.
1649
1650**Atomic service API**: This API can be used in atomic services since API version 12.
1651
1652**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1653
1654**Parameters**
1655
1656| Name  | Type    | Mandatory| Description                |
1657| -------- | -------- | ---- | -------------------- |
1658| index | number | Yes  | Index of the track. You can call [getTrackDescription](#gettrackdescription9-1) to obtain all track information [MediaDescription](#mediadescription8) of the current resource.|
1659| mode   | [SwitchMode](#switchmode12) | No  | Video track switch mode. The default mode is **SMOOTH**. This parameter takes effect only for the switch of a video track for DASH streams.|
1660
1661**Return value**
1662
1663| Type          | Description                     |
1664| -------------- | ------------------------- |
1665| Promise\<void> | Promise that returns no value.|
1666
1667**Error codes**
1668
1669For details about the error codes, see [Media Error Codes](errorcode-media.md).
1670
1671| ID| Error Message                                 |
1672| -------- | ----------------------------------------- |
1673| 401      | The parameter check failed. Return by promise.       |
1674| 5400102  | Operation not allowed. Return by promise. |
1675
1676**Example**
1677
1678<!--code_no_check-->
1679```ts
1680import { BusinessError } from '@kit.BasicServicesKit';
1681
1682let avPlayer: media.AVPlayer = await media.createAVPlayer();
1683let audioTrackIndex: Object = 0;
1684avPlayer.getTrackDescription((error: BusinessError, arrList: Array<media.MediaDescription>) => {
1685  if (arrList != null) {
1686    for (let i = 0; i < arrList.length; i++) {
1687      if (i != 0) {
1688        // Obtain the audio track list.
1689        audioTrackIndex = arrList[i][media.MediaDescriptionKey.MD_KEY_TRACK_INDEX];
1690      }
1691    }
1692  } else {
1693    console.error(`Failed to get TrackDescription, error:${error}`);
1694  }
1695});
1696
1697// Select an audio track.
1698avPlayer.selectTrack(parseInt(audioTrackIndex.toString()));
1699```
1700
1701### deselectTrack<sup>12+</sup>
1702
1703deselectTrack(index: number): Promise\<void>
1704
1705Deselects 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.
1706
1707**Atomic service API**: This API can be used in atomic services since API version 12.
1708
1709**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1710
1711**Parameters**
1712
1713| Name  | Type    | Mandatory| Description                |
1714| -------- | -------- | ---- | -------------------- |
1715| index | number | Yes  | Track index, which is obtained from [MediaDescription](#mediadescription8) by calling [getTrackDescription](#gettrackdescription9-1).|
1716
1717**Return value**
1718
1719| Type          | Description                     |
1720| -------------- | ------------------------- |
1721| Promise\<void> | Promise that returns no value.|
1722
1723**Error codes**
1724
1725For details about the error codes, see [Media Error Codes](errorcode-media.md).
1726
1727| ID| Error Message                                 |
1728| -------- | ----------------------------------------- |
1729| 401      | The parameter check failed. Return by promise.       |
1730| 5400102  | Operation not allowed. Return by promise. |
1731
1732**Example**
1733
1734<!--code_no_check-->
1735```ts
1736import { BusinessError } from '@kit.BasicServicesKit';
1737
1738let avPlayer: media.AVPlayer = await media.createAVPlayer();
1739let audioTrackIndex: Object = 0;
1740avPlayer.getTrackDescription((error: BusinessError, arrList: Array<media.MediaDescription>) => {
1741  if (arrList != null) {
1742    for (let i = 0; i < arrList.length; i++) {
1743      if (i != 0) {
1744        // Obtain the audio track list.
1745        audioTrackIndex = arrList[i][media.MediaDescriptionKey.MD_KEY_TRACK_INDEX];
1746      }
1747    }
1748  } else {
1749    console.error(`Failed to get TrackDescription, error:${error}`);
1750  }
1751});
1752
1753// Select an audio track.
1754avPlayer.selectTrack(parseInt(audioTrackIndex.toString()));
1755// Deselect the audio track and restore to the default audio track.
1756avPlayer.deselectTrack(parseInt(audioTrackIndex.toString()));
1757```
1758
1759### setDecryptionConfig<sup>11+</sup>
1760
1761setDecryptionConfig(mediaKeySession: drm.MediaKeySession, secureVideoPath: boolean): void
1762
1763Sets 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.
1764
1765**Atomic service API**: This API can be used in atomic services since API version 12.
1766
1767**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1768
1769**Parameters**
1770
1771| Name  | Type                                                        | Mandatory| Description                                        |
1772| -------- | ------------------------------------------------------------ | ---- | -------------------------------------------- |
1773| mediaKeySession | [drm.MediaKeySession](../apis-drm-kit/js-apis-drm.md#mediakeysession) | Yes  | Decryption session.|
1774| secureVideoPath | boolean | Yes| Secure video channel. The value **true** means that a secure video channel is selected, and **false** means that a non-secure video channel is selected.|
1775
1776**Error codes**
1777
1778For details about the error codes, see [Media Error Codes](errorcode-media.md).
1779
1780| ID| Error Message                                 |
1781| -------- | ----------------------------------------- |
1782| 401  | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. |
1783
1784**Example**
1785
1786For details about the DRM module, see [js-apis-drm.md](../apis-drm-kit/js-apis-drm.md).
1787```ts
1788import { drm } from '@kit.DrmKit';
1789
1790// Create a media key system.
1791let keySystem:drm.MediaKeySystem = drm.createMediaKeySystem('com.clearplay.drm');
1792// Create a media key session.
1793let keySession:drm.MediaKeySession = keySystem.createMediaKeySession(drm.ContentProtectionLevel.CONTENT_PROTECTION_LEVEL_SW_CRYPTO);
1794// Generate a media key request and set the response to the media key request.
1795// Flag indicating whether a secure video channel is used.
1796let secureVideoPath:boolean = false;
1797// Set the decryption configuration.
1798avPlayer.setDecryptionConfig(keySession, secureVideoPath);
1799```
1800
1801### getMediaKeySystemInfos<sup>11+</sup>
1802
1803getMediaKeySystemInfos(): Array\<drm.MediaKeySystemInfo>
1804
1805Obtains 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.
1806
1807**Atomic service API**: This API can be used in atomic services since API version 12.
1808
1809**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1810
1811**Return value**
1812
1813| Type                                                  | Description                                             |
1814| ------------------------------------------------------ | ------------------------------------------------- |
1815|  Array<[drm.MediaKeySystemInfo](../apis-drm-kit/js-apis-drm.md#mediakeysysteminfo)> | Array of **MediaKeySystemInfo** objects, each of which contains the **uuid** and **pssh** attributes.|
1816
1817**Example**
1818
1819```ts
1820import { drm } from '@kit.DrmKit';
1821
1822const infos = avPlayer.getMediaKeySystemInfos();
1823console.info('GetMediaKeySystemInfos count: ' + infos.length);
1824for (let i = 0; i < infos.length; i++) {
1825  console.info('GetMediaKeySystemInfos uuid: ' + infos[i]["uuid"]);
1826  console.info('GetMediaKeySystemInfos pssh: ' + infos[i]["pssh"]);
1827}
1828```
1829
1830### seek<sup>9+</sup>
1831
1832seek(timeMs: number, mode?:SeekMode): void
1833
1834Seeks 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.
1835This API is not supported in live mode.
1836
1837**Atomic service API**: This API can be used in atomic services since API version 11.
1838
1839**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1840
1841**Parameters**
1842
1843| Name| Type                  | Mandatory| Description                                                        |
1844| ------ | ---------------------- | ---- | ------------------------------------------------------------ |
1845| timeMs | number                 | Yes  | Position to seek to, in ms. The value range is [0, [duration](#attributes)]. In SEEK_CONTINUOU mode, the value **-1** can be used to indicate the end of SEEK_CONTINUOUS mode.|
1846| mode   | [SeekMode](#seekmode8) | No  | Seek mode based on the video I frame. The default value is **SEEK_PREV_SYNC**. **Set this parameter only for video playback.**|
1847
1848**Example**
1849
1850```ts
1851let seekTime: number = 1000
1852avPlayer.seek(seekTime, media.SeekMode.SEEK_PREV_SYNC)
1853```
1854
1855```ts
1856// SEEK_CONTINUOUS can be used together with the callback of seekBar/slider.
1857async onSlideMoving(position : number) : Promise<void> {
1858  // To trigger a callback when the seekBar/slider moves, call seek(position, media.SeekMode.SEEK_CONTINUOUS) to perform the seek operation.
1859  this.avPlayer.seek(position, media.SeekMode.SEEK_CONTINUOUS)
1860}
1861
1862async onSlideEnd(position : number) : Promise<void> {
1863  // To trigger a callback when the seekBar/slider movement ends, call seek(-1, media.SeekMode.SEEK_CONTINUOUS) to end the seek operation.
1864  this.avPlayer.seek(-1, media.SeekMode.SEEK_CONTINUOUS)
1865}
1866```
1867
1868### isSeekContinuousSupported<sup>18+</sup>
1869
1870isSeekContinuousSupported() : boolean
1871
1872Checks whether the media source supports [seek](#seek9) in SEEK_CONTINUOUS mode ([SeekMode](#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.
1873
1874**Atomic service API**: This API can be used in atomic services since API version 18.
1875
1876**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1877
1878**Example**
1879
1880```ts
1881let isSupported = avPlayer.isSeekContinuousSupported()
1882```
1883
1884### on('seekDone')<sup>9+</sup>
1885
1886on(type: 'seekDone', callback: Callback\<number>): void
1887
1888Subscribes to the event to check whether the seek operation takes effect.
1889
1890**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1891
1892**Atomic service API**: This API can be used in atomic services since API version 11.
1893
1894**Parameters**
1895
1896| Name  | Type    | Mandatory| Description                                                        |
1897| -------- | -------- | ---- | ------------------------------------------------------------ |
1898| 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.|
1899| callback | Callback\<number> | Yes  | Callback invoked when the event is triggered. It reports the time position requested by the user.<br>For video playback, [SeekMode](#seekmode8) may cause the actual position to be different from that requested by the user. The exact position can be obtained from the **currentTime** attribute. The time in this callback only means that the requested seek operation is complete.|
1900
1901**Example**
1902
1903```ts
1904avPlayer.on('seekDone', (seekDoneTime:number) => {
1905  console.info('seekDone called,and seek time is:' + seekDoneTime)
1906})
1907```
1908
1909### off('seekDone')<sup>9+</sup>
1910
1911off(type: 'seekDone', callback?: Callback\<number>): void
1912
1913Unsubscribes from the event that checks whether the seek operation takes effect.
1914
1915**Atomic service API**: This API can be used in atomic services since API version 11.
1916
1917**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1918
1919**Parameters**
1920
1921| Name| Type  | Mandatory| Description                                                |
1922| ------ | ------ | ---- | ---------------------------------------------------- |
1923| type   | string | Yes  | Event type, which is **'seekDone'** in this case.|
1924| callback | Callback\<number> | No  | Callback invoked when the event is triggered. It reports the time position requested by the user.<br>For video playback, [SeekMode](#seekmode8) may cause the actual position to be different from that requested by the user. The exact position can be obtained from the **currentTime** attribute. The time in this callback only means that the requested seek operation is complete.<br>This parameter is supported since API version 12.|
1925
1926**Example**
1927
1928```ts
1929avPlayer.off('seekDone')
1930```
1931
1932### setSpeed<sup>9+</sup>
1933
1934setSpeed(speed: PlaybackSpeed): void
1935
1936Sets 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.
1937This API is not supported in live mode.
1938
1939**Atomic service API**: This API can be used in atomic services since API version 12.
1940
1941**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1942
1943**Parameters**
1944
1945| Name| Type                            | Mandatory| Description              |
1946| ------ | -------------------------------- | ---- | ------------------ |
1947| speed  | [PlaybackSpeed](#playbackspeed8) | Yes  | Playback speed to set.|
1948
1949**Example**
1950
1951```ts
1952avPlayer.setSpeed(media.PlaybackSpeed.SPEED_FORWARD_2_00_X)
1953```
1954
1955### on('speedDone')<sup>9+</sup>
1956
1957on(type: 'speedDone', callback: Callback\<number>): void
1958
1959Subscribes to the event to check whether the playback speed is successfully set.
1960
1961**Atomic service API**: This API can be used in atomic services since API version 12.
1962
1963**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1964
1965**Parameters**
1966
1967| Name  | Type    | Mandatory| Description                                                        |
1968| -------- | -------- | ---- | ------------------------------------------------------------ |
1969| type     | string   | Yes  | Event type, which is **'speedDone'** in this case. This event is triggered each time **setSpeed()** is called.|
1970| callback | Callback\<number> | Yes  | Callback used to return the result. When the call of **setSpeed** is successful, the effective speed mode is reported. For details, see [PlaybackSpeed](#playbackspeed8).|
1971
1972**Example**
1973
1974```ts
1975avPlayer.on('speedDone', (speed:number) => {
1976  console.info('speedDone called,and speed value is:' + speed)
1977})
1978```
1979
1980### off('speedDone')<sup>9+</sup>
1981
1982off(type: 'speedDone', callback?: Callback\<number>): void
1983
1984Unsubscribes from the event that checks whether the playback speed is successfully set.
1985
1986**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1987
1988**Parameters**
1989
1990| Name| Type  | Mandatory| Description                                                     |
1991| ------ | ------ | ---- | --------------------------------------------------------- |
1992| type   | string | Yes  | Event type, which is **'speedDone'** in this case.|
1993| callback | Callback\<number> | No  | Callback used to return the result. When the call of **setSpeed** is successful, the effective speed mode is reported. For details, see [PlaybackSpeed](#playbackspeed8).<br>This parameter is supported since API version 12.|
1994
1995**Example**
1996
1997```ts
1998avPlayer.off('speedDone')
1999```
2000
2001### setBitrate<sup>9+</sup>
2002
2003setBitrate(bitrate: number): void
2004
2005Sets 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.
2006
2007**Atomic service API**: This API can be used in atomic services since API version 12.
2008
2009**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2010
2011**Parameters**
2012
2013| Name | Type  | Mandatory| Description                                                        |
2014| ------- | ------ | ---- | ------------------------------------------------------------ |
2015| 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.|
2016
2017**Example**
2018
2019```ts
2020let bitrate: number = 96000
2021avPlayer.setBitrate(bitrate)
2022```
2023
2024### on('bitrateDone')<sup>9+</sup>
2025
2026on(type: 'bitrateDone', callback: Callback\<number>): void
2027
2028Subscribes to the event to check whether the bit rate is successfully set.
2029
2030**Atomic service API**: This API can be used in atomic services since API version 12.
2031
2032**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2033
2034**Parameters**
2035
2036| Name  | Type    | Mandatory| Description                                                        |
2037| -------- | -------- | ---- | ------------------------------------------------------------ |
2038| type     | string   | Yes  | Event type, which is **'bitrateDone'** in this case. This event is triggered each time **setBitrate()** is called.|
2039| callback | Callback\<number> | Yes  | Callback invoked when the event is triggered. It reports the effective bit rate.            |
2040
2041**Example**
2042
2043```ts
2044avPlayer.on('bitrateDone', (bitrate:number) => {
2045  console.info('bitrateDone called,and bitrate value is:' + bitrate)
2046})
2047```
2048
2049### off('bitrateDone')<sup>9+</sup>
2050
2051off(type: 'bitrateDone', callback?: Callback\<number>): void
2052
2053Unsubscribes from the event that checks whether the bit rate is successfully set.
2054
2055**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2056
2057**Parameters**
2058
2059| Name| Type  | Mandatory| Description                                                        |
2060| ------ | ------ | ---- | ------------------------------------------------------------ |
2061| type   | string | Yes  | Event type, which is **'bitrateDone'** in this case.|
2062| 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.            |
2063
2064**Example**
2065
2066```ts
2067avPlayer.off('bitrateDone')
2068```
2069
2070### on('availableBitrates')<sup>9+</sup>
2071
2072on(type: 'availableBitrates', callback: Callback\<Array\<number>>): void
2073
2074Subscribes to available bit rates of HLS/DASH streams. This event is reported only after the AVPlayer switches to the prepared state.
2075
2076**Atomic service API**: This API can be used in atomic services since API version 12.
2077
2078**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2079
2080**Parameters**
2081
2082| Name  | Type    | Mandatory| Description                                                        |
2083| -------- | -------- | ---- | ------------------------------------------------------------ |
2084| type     | string   | Yes  | Event type, which is **'availableBitrates'** in this case. This event is triggered once after the AVPlayer switches to the prepared state.|
2085| 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.|
2086
2087**Example**
2088
2089```ts
2090avPlayer.on('availableBitrates', (bitrates: Array<number>) => {
2091  console.info('availableBitrates called,and availableBitrates length is:' + bitrates.length)
2092})
2093```
2094
2095### off('availableBitrates')<sup>9+</sup>
2096
2097off(type: 'availableBitrates', callback?: Callback\<Array\<number>>): void
2098
2099Unsubscribes from available bit rates of HLS/DASH streams. This event is reported after [prepare](#prepare9) is called.
2100
2101**Atomic service API**: This API can be used in atomic services since API version 12.
2102
2103**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2104
2105**Parameters**
2106
2107| Name| Type  | Mandatory| Description                                                        |
2108| ------ | ------ | ---- | ------------------------------------------------------------ |
2109| type   | string | Yes  | Event type, which is **'availableBitrates'** in this case.|
2110| 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.|
2111
2112**Example**
2113
2114```ts
2115avPlayer.off('availableBitrates')
2116```
2117
2118
2119### on('mediaKeySystemInfoUpdate')<sup>11+</sup>
2120
2121on(type: 'mediaKeySystemInfoUpdate', callback: Callback\<Array\<drm.MediaKeySystemInfo>>): void
2122
2123Subscribes to media key system information changes.
2124
2125**Atomic service API**: This API can be used in atomic services since API version 12.
2126
2127**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2128
2129**Parameters**
2130
2131| Name  | Type    | Mandatory| Description                                                        |
2132| -------- | -------- | ---- | ------------------------------------------------------------ |
2133| 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.|
2134| callback | Callback\<Array\<drm.[MediaKeySystemInfo](../apis-drm-kit/js-apis-drm.md#mediakeysysteminfo)>> | Yes  | Callback invoked when the event is triggered. It reports a **MediaKeySystemInfo** array.|
2135
2136**Example**
2137
2138```ts
2139import { drm } from '@kit.DrmKit';
2140
2141avPlayer.on('mediaKeySystemInfoUpdate', (mediaKeySystemInfo: Array<drm.MediaKeySystemInfo>) => {
2142    for (let i = 0; i < mediaKeySystemInfo.length; i++) {
2143      console.info('mediaKeySystemInfoUpdate happened uuid: ' + mediaKeySystemInfo[i]["uuid"]);
2144      console.info('mediaKeySystemInfoUpdate happened pssh: ' + mediaKeySystemInfo[i]["pssh"]);
2145    }
2146})
2147```
2148
2149### off('mediaKeySystemInfoUpdate')<sup>11+</sup>
2150
2151off(type: 'mediaKeySystemInfoUpdate', callback?: Callback\<Array\<drm.MediaKeySystemInfo>>): void;
2152
2153Unsubscribes from media key system information changes.
2154
2155**Atomic service API**: This API can be used in atomic services since API version 12.
2156
2157**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2158
2159**Parameters**
2160
2161| Name| Type  | Mandatory| Description                                                        |
2162| ------ | ------ | ---- | ------------------------------------------------------------ |
2163| type   | string | Yes  | Event type, which is **'mediaKeySystemInfoUpdate'** in this case.|
2164| callback | Callback\<Array\<drm.[MediaKeySystemInfo](../apis-drm-kit/js-apis-drm.md#mediakeysysteminfo)>> | No  | Callback invoked when the event is triggered. It reports a **MediaKeySystemInfo** array. If this parameter is specified, only the specified callback is unregistered. Otherwise, all callbacks associated with the specified event will be unregistered.|
2165
2166**Example**
2167
2168```ts
2169avPlayer.off('mediaKeySystemInfoUpdate')
2170```
2171
2172### setVolume<sup>9+</sup>
2173
2174setVolume(volume: number): void
2175
2176Sets 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.
2177
2178**Atomic service API**: This API can be used in atomic services since API version 12.
2179
2180**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2181
2182**Parameters**
2183
2184| Name| Type  | Mandatory| Description                                                        |
2185| ------ | ------ | ---- | ------------------------------------------------------------ |
2186| volume | number | Yes  | Relative volume. The value ranges from 0.00 to 1.00. The value **1.00** indicates the maximum volume (100%).|
2187
2188**Example**
2189
2190```ts
2191let volume: number = 1.0
2192avPlayer.setVolume(volume)
2193```
2194
2195### on('volumeChange')<sup>9+</sup>
2196
2197on(type: 'volumeChange', callback: Callback\<number>): void
2198
2199Subscribes to the event to check whether the volume is successfully set.
2200
2201**Atomic service API**: This API can be used in atomic services since API version 12.
2202
2203**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2204
2205**Parameters**
2206
2207| Name  | Type    | Mandatory| Description                                                        |
2208| -------- | -------- | ---- | ------------------------------------------------------------ |
2209| type     | string   | Yes  | Event type, which is **'volumeChange'** in this case. This event is triggered each time **setVolume()** is called.|
2210| callback | Callback\<number> | Yes  | Callback invoked when the event is triggered. It reports the effective volume.           |
2211
2212**Example**
2213
2214```ts
2215avPlayer.on('volumeChange', (vol: number) => {
2216  console.info('volumeChange called,and new volume is :' + vol)
2217})
2218```
2219
2220### off('volumeChange')<sup>9+</sup>
2221
2222off(type: 'volumeChange', callback?: Callback\<number>): void
2223
2224Unsubscribes from the event that checks whether the volume is successfully set.
2225
2226**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2227
2228**Parameters**
2229
2230| Name| Type  | Mandatory| Description                                                        |
2231| ------ | ------ | ---- | ------------------------------------------------------------ |
2232| type   | string | Yes  | Event type, which is **'volumeChange'** in this case.|
2233| 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.           |
2234
2235**Example**
2236
2237```ts
2238avPlayer.off('volumeChange')
2239```
2240
2241### on('endOfStream')<sup>9+</sup>
2242
2243on(type: 'endOfStream', callback: Callback\<void>): void
2244
2245Subscribes to the event that indicates the end of the stream being played. If **[loop](#attributes) = true** is set, the AVPlayer seeks to the beginning of the stream and plays the stream again. If **loop** is not set, the completed state is reported through the [stateChange](#onstatechange9) event.
2246
2247**Atomic service API**: This API can be used in atomic services since API version 12.
2248
2249**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2250
2251**Parameters**
2252
2253| Name  | Type    | Mandatory| Description                                                        |
2254| -------- | -------- | ---- | ------------------------------------------------------------ |
2255| type     | string   | Yes  | Event type, which is **'endOfStream'** in this case. This event is triggered when the AVPlayer finishes playing the media asset.|
2256| callback | Callback\<void> | Yes  | Callback invoked when the event is triggered.                              |
2257
2258**Example**
2259
2260```ts
2261avPlayer.on('endOfStream', () => {
2262  console.info('endOfStream called')
2263})
2264```
2265
2266### off('endOfStream')<sup>9+</sup>
2267
2268off(type: 'endOfStream', callback?: Callback\<void>): void
2269
2270Unsubscribes from the event that indicates the end of the stream being played.
2271
2272**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2273
2274**Parameters**
2275
2276| Name| Type  | Mandatory| Description                                                        |
2277| ------ | ------ | ---- | ------------------------------------------------------------ |
2278| type   | string | Yes  | Event type, which is **'endOfStream'** in this case.|
2279| callback | Callback\<void> | No  | Callback invoked when the event is triggered.<br>This parameter is supported since API version 12.                              |
2280
2281**Example**
2282
2283```ts
2284avPlayer.off('endOfStream')
2285```
2286
2287### on('timeUpdate')<sup>9+</sup>
2288
2289on(type: 'timeUpdate', callback: Callback\<number>): void
2290
2291Subscribes 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.
2292
2293The **'timeUpdate'** event is not supported in live mode.
2294
2295**Atomic service API**: This API can be used in atomic services since API version 11.
2296
2297**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2298
2299**Parameters**
2300
2301| Name  | Type    | Mandatory| Description                                          |
2302| -------- | -------- | ---- | ---------------------------------------------- |
2303| type     | string   | Yes  | Event type, which is **'timeUpdate'** in this case.|
2304| callback | Callback\<number> | Yes  | Callback used to return the current time.                                    |
2305
2306**Example**
2307
2308```ts
2309avPlayer.on('timeUpdate', (time:number) => {
2310  console.info('timeUpdate called,and new time is :' + time)
2311})
2312```
2313
2314### off('timeUpdate')<sup>9+</sup>
2315
2316off(type: 'timeUpdate', callback?: Callback\<number>): void
2317
2318Unsubscribes from playback position changes.
2319
2320**Atomic service API**: This API can be used in atomic services since API version 11.
2321
2322**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2323
2324**Parameters**
2325
2326| Name| Type  | Mandatory| Description                                              |
2327| ------ | ------ | ---- | -------------------------------------------------- |
2328| type   | string | Yes  | Event type, which is **'timeUpdate'** in this case.|
2329| callback | Callback\<number> | No  | Callback used to return the current time.<br>This parameter is supported since API version 12.            |
2330
2331**Example**
2332
2333```ts
2334avPlayer.off('timeUpdate')
2335```
2336
2337### on('durationUpdate')<sup>9+</sup>
2338
2339
2340on(type: 'durationUpdate', callback: Callback\<number>): void
2341
2342Subscribes 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.
2343The **'durationUpdate'** event is not supported in live mode.
2344
2345**Atomic service API**: This API can be used in atomic services since API version 12.
2346
2347**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2348
2349**Parameters**
2350
2351| Name  | Type    | Mandatory| Description                                              |
2352| -------- | -------- | ---- | -------------------------------------------------- |
2353| type     | string   | Yes  | Event type, which is **'durationUpdate'** in this case.|
2354| callback | Callback\<number> | Yes  | Callback used to return the resource duration.       |
2355
2356**Example**
2357
2358```ts
2359avPlayer.on('durationUpdate', (duration: number) => {
2360  console.info('durationUpdate called,new duration is :' + duration)
2361})
2362```
2363
2364### off('durationUpdate')<sup>9+</sup>
2365
2366off(type: 'durationUpdate', callback?: Callback\<number>): void
2367
2368Unsubscribes from media asset duration changes.
2369
2370**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2371
2372**Parameters**
2373
2374| Name| Type  | Mandatory| Description                                                  |
2375| ------ | ------ | ---- | ------------------------------------------------------ |
2376| type   | string | Yes  | Event type, which is **'durationUpdate'** in this case.|
2377| callback | Callback\<number> | No  | Callback used to return the resource duration.<br>This parameter is supported since API version 12.       |
2378
2379**Example**
2380
2381```ts
2382avPlayer.off('durationUpdate')
2383```
2384
2385### on('bufferingUpdate')<sup>9+</sup>
2386
2387on(type: 'bufferingUpdate', callback: OnBufferingUpdateHandler): void
2388
2389Subscribes to audio and video buffer changes. This subscription is supported only in network playback scenarios.
2390
2391**Atomic service API**: This API can be used in atomic services since API version 12.
2392
2393**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2394
2395**Parameters**
2396
2397| Name  | Type    | Mandatory| Description                                                        |
2398| -------- | -------- | ---- | ------------------------------------------------------------ |
2399| type     | string   | Yes  | Event type, which is **'bufferingUpdate'** in this case.       |
2400| callback | [OnBufferingUpdateHandler](#onbufferingupdatehandler12) | Yes  | Callback invoked when the event is triggered.|
2401
2402**Example**
2403
2404```ts
2405avPlayer.on('bufferingUpdate', (infoType: media.BufferingInfoType, value: number) => {
2406  console.info('bufferingUpdate called,and infoType value is:' + infoType + ', value is :' + value)
2407})
2408```
2409
2410### off('bufferingUpdate')<sup>9+</sup>
2411
2412off(type: 'bufferingUpdate', callback?: OnBufferingUpdateHandler): void
2413
2414Unsubscribes from audio and video buffer changes.
2415
2416**Atomic service API**: This API can be used in atomic services since API version 12.
2417
2418**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2419
2420**Parameters**
2421
2422| Name| Type  | Mandatory| Description                                                     |
2423| ------ | ------ | ---- | --------------------------------------------------------- |
2424| type   | string | Yes  | Event type, which is **'bufferingUpdate'** in this case.|
2425| callback | [OnBufferingUpdateHandler](#onbufferingupdatehandler12) | No  | Callback invoked when the event is triggered.|
2426
2427**Example**
2428
2429```ts
2430avPlayer.off('bufferingUpdate')
2431```
2432
2433### on('startRenderFrame')<sup>9+</sup>
2434
2435on(type: 'startRenderFrame', callback: Callback\<void>): void
2436
2437Subscribes 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.
2438
2439**Atomic service API**: This API can be used in atomic services since API version 12.
2440
2441**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2442
2443**Parameters**
2444
2445| Name  | Type    | Mandatory| Description                                                        |
2446| -------- | -------- | ---- | ------------------------------------------------------------ |
2447| type     | string   | Yes  | Event type, which is **'startRenderFrame'** in this case.|
2448| callback | Callback\<void> | Yes  | Callback invoked when the event is triggered.                          |
2449
2450**Example**
2451
2452```ts
2453avPlayer.on('startRenderFrame', () => {
2454  console.info('startRenderFrame called')
2455})
2456```
2457
2458### off('startRenderFrame')<sup>9+</sup>
2459
2460off(type: 'startRenderFrame', callback?: Callback\<void>): void
2461
2462Unsubscribes from the event that indicates rendering starts for the first frame.
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 **'startRenderFrame'** in this case.|
2471| callback | Callback\<void> | No  | Callback invoked when the event is triggered.<br>This parameter is supported since API version 12.                  |
2472
2473**Example**
2474
2475```ts
2476avPlayer.off('startRenderFrame')
2477```
2478
2479### on('videoSizeChange')<sup>9+</sup>
2480
2481on(type: 'videoSizeChange', callback: OnVideoSizeChangeHandler): void
2482
2483Subscribes 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.
2484
2485**Atomic service API**: This API can be used in atomic services since API version 12.
2486
2487**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2488
2489**Parameters**
2490
2491| Name  | Type    | Mandatory| Description                                                        |
2492| -------- | -------- | ---- | ------------------------------------------------------------ |
2493| type     | string   | Yes  | Event type, which is **'videoSizeChange'** in this case.|
2494| callback | [OnVideoSizeChangeHandler](#onvideosizechangehandler12) | Yes  | Callback invoked when the event is triggered.   |
2495
2496**Example**
2497
2498```ts
2499avPlayer.on('videoSizeChange', (width: number, height: number) => {
2500  console.info('videoSizeChange called,and width is:' + width + ', height is :' + height)
2501})
2502```
2503
2504### off('videoSizeChange')<sup>9+</sup>
2505
2506off(type: 'videoSizeChange', callback?: OnVideoSizeChangeHandler): void
2507
2508Unsubscribes from video size changes.
2509
2510**Atomic service API**: This API can be used in atomic services since API version 12.
2511
2512**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2513
2514**Parameters**
2515
2516| Name| Type  | Mandatory| Description                                                        |
2517| ------ | ------ | ---- | ------------------------------------------------------------ |
2518| type   | string | Yes  | Event type, which is **'videoSizeChange'** in this case.|
2519| callback | [OnVideoSizeChangeHandler](#onvideosizechangehandler12) | No  | Callback invoked when the event is triggered.<br>This parameter is supported since API version 12.   |
2520
2521**Example**
2522
2523```ts
2524avPlayer.off('videoSizeChange')
2525```
2526
2527### on('audioInterrupt')<sup>9+</sup>
2528
2529on(type: 'audioInterrupt', callback: Callback\<audio.InterruptEvent>): void
2530
2531Subscribes to the audio interruption event. When multiple audio and video assets are played at the same time, this event is triggered based on the audio interruption mode [audio.InterruptMode](../apis-audio-kit/js-apis-audio.md#interruptmode9). The application needs to perform corresponding processing based on different audio interruption events. For details, see [Handling Audio Interruption Events](../../media/audio/audio-playback-concurrency.md).
2532
2533**Atomic service API**: This API can be used in atomic services since API version 12.
2534
2535**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2536
2537**Parameters**
2538
2539| Name  | Type                                                        | Mandatory| Description                                                    |
2540| -------- | ------------------------------------------------------------ | ---- | -------------------------------------------------------- |
2541| type     | string                                                       | Yes  | Event type, which is **'audioInterrupt'** in this case.|
2542| callback | Callback\<[audio.InterruptEvent](../apis-audio-kit/js-apis-audio.md#interruptevent9)> | Yes  | Callback invoked when the event is triggered.                          |
2543
2544**Example**
2545
2546```ts
2547import { audio } from '@kit.AudioKit';
2548
2549avPlayer.on('audioInterrupt', (info: audio.InterruptEvent) => {
2550  console.info('audioInterrupt called,and InterruptEvent info is:' + info)
2551})
2552```
2553
2554### off('audioInterrupt')<sup>9+</sup>
2555
2556off(type: 'audioInterrupt', callback?: Callback<audio.InterruptEvent>): void
2557
2558Unsubscribes from the audio interruption event.
2559
2560**Atomic service API**: This API can be used in atomic services since API version 12.
2561
2562**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2563
2564**Parameters**
2565
2566| Name| Type  | Mandatory| Description                                                        |
2567| ------ | ------ | ---- | ------------------------------------------------------------ |
2568| type   | string | Yes  | Event type, which is **'audioInterrupt'** in this case.|
2569| callback | Callback\<[audio.InterruptEvent](../apis-audio-kit/js-apis-audio.md#interruptevent9)> | No  | Callback invoked when the event is triggered.<br>This parameter is supported since API version 12.            |
2570
2571**Example**
2572
2573```ts
2574avPlayer.off('audioInterrupt')
2575```
2576
2577### on('audioOutputDeviceChangeWithInfo')<sup>11+</sup>
2578
2579on(type: 'audioOutputDeviceChangeWithInfo', callback: Callback\<audio.AudioStreamDeviceChangeInfo>): void
2580
2581Subscribes to audio stream output device changes and reasons. This API uses an asynchronous callback to return the result.
2582
2583When 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).
2584
2585**Atomic service API**: This API can be used in atomic services since API version 12.
2586
2587**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2588
2589**Parameters**
2590
2591| Name  | Type                      | Mandatory| Description                                       |
2592| :------- | :------------------------- | :--- | :------------------------------------------ |
2593| type     | string                     | Yes  | Event type, which is **'outputDeviceChangeWithInfo'** in this case. The event is triggered when the output device is changed.|
2594| callback | Callback\<[audio.AudioStreamDeviceChangeInfo](../apis-audio-kit/js-apis-audio.md#audiostreamdevicechangeinfo11)> | Yes  | Callback used to return the output device descriptor of the current audio stream and the change reason.|
2595
2596**Error codes**
2597
2598| ID| Error Message                                  |
2599| -------- | ------------------------------------------ |
2600| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed.       |
2601
2602**Example**
2603
2604```ts
2605import { audio } from '@kit.AudioKit';
2606
2607avPlayer.on('audioOutputDeviceChangeWithInfo', (data: audio.AudioStreamDeviceChangeInfo) => {
2608  console.info(`${JSON.stringify(data)}`);
2609});
2610```
2611
2612### off('audioOutputDeviceChangeWithInfo')<sup>11+</sup>
2613
2614off(type: 'audioOutputDeviceChangeWithInfo', callback?: Callback\<audio.AudioStreamDeviceChangeInfo>): void
2615
2616Unsubscribes from audio stream output device changes and reasons. This API uses an asynchronous callback to return the result.
2617
2618**Atomic service API**: This API can be used in atomic services since API version 12.
2619
2620**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2621
2622**Parameters**
2623
2624| Name  | Type                      | Mandatory| Description                                       |
2625| :------- | :------------------------- | :--- | :------------------------------------------ |
2626| type     | string                     | Yes  | Event type, which is **'outputDeviceChange'** in this case. The event is triggered when the audio output device is changed.|
2627| callback | Callback\<[audio.AudioStreamDeviceChangeInfo](../apis-audio-kit/js-apis-audio.md#audiostreamdevicechangeinfo11)> | No  | Callback used to return the output device descriptor of the current audio stream and the change reason.|
2628
2629**Error codes**
2630
2631| ID| Error Message                                  |
2632| -------- | ------------------------------------------ |
2633| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed.      |
2634
2635**Example**
2636
2637```ts
2638avPlayer.off('audioOutputDeviceChangeWithInfo');
2639```
2640
2641### addSubtitleFromFd<sup>12+</sup>
2642
2643addSubtitleFromFd(fd: number, offset?: number, length?: number): Promise\<void>
2644
2645Adds 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.
2646
2647**Atomic service API**: This API can be used in atomic services since API version 12.
2648
2649**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2650
2651**Parameters**
2652
2653| Name| Type                  | Mandatory| Description                                                        |
2654| ------ | ---------------------- | ---- | ------------------------------------------------------------ |
2655| fd | number   | Yes  | Resource handle, which is obtained by calling [resourceManager.getRawFd](../apis-localization-kit/js-apis-resource-manager.md#getrawfd9).|
2656| 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.|
2657| 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.|
2658
2659**Return value**
2660
2661| Type          | Description                                      |
2662| -------------- | ------------------------------------------ |
2663| Promise\<void> | Promise that returns no value.|
2664
2665**Error codes**
2666
2667| ID| Error Message                                  |
2668| -------- | ------------------------------------------ |
2669| 401      | The parameter check failed. Return by promise. |
2670| 5400102  | Operation not allowed. Return by promise. |
2671
2672**Example**
2673
2674<!--code_no_check-->
2675```ts
2676import { common } from '@kit.AbilityKit'
2677
2678let context = getContext(this) as common.UIAbilityContext
2679let fileDescriptor = await context.resourceManager.getRawFd('xxx.srt')
2680
2681avPlayer.addSubtitleFromFd(fileDescriptor.fd, fileDescriptor.offset, fileDescriptor.length)
2682```
2683
2684### addSubtitleFromUrl<sup>12+</sup>
2685
2686addSubtitleFromUrl(url: string): Promise\<void>
2687
2688Adds 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.
2689
2690**Atomic service API**: This API can be used in atomic services since API version 12.
2691
2692**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2693
2694**Parameters**
2695
2696| Name| Type  | Mandatory| Description                                                        |
2697| ------ | ------ | ---- | ------------------------------------------------------------ |
2698| url    | string | Yes  | Address of the external subtitle file.|
2699
2700**Return value**
2701
2702| Type          | Description                                      |
2703| -------------- | ------------------------------------------ |
2704| Promise\<void> | Promise that returns no value.|
2705
2706**Error codes**
2707
2708| ID| Error Message                                  |
2709| -------- | ------------------------------------------ |
2710| 401      | The parameter check failed. Return by promise. |
2711| 5400102  | Operation not allowed. Return by promise. |
2712
2713**Example**
2714
2715<!--code_no_check-->
2716```ts
2717let fdUrl:string = 'http://xxx.xxx.xxx/xx/index.srt'
2718
2719let avPlayer: media.AVPlayer = await media.createAVPlayer()
2720avPlayer.addSubtitleFromUrl(fdUrl)
2721```
2722
2723### on('subtitleUpdate')<sup>12+</sup>
2724
2725on(type: 'subtitleUpdate', callback: Callback\<SubtitleInfo>): void
2726
2727Subscribes 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.
2728
2729**Atomic service API**: This API can be used in atomic services since API version 12.
2730
2731**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2732
2733**Parameters**
2734
2735| Name  | Type    | Mandatory| Description                                                        |
2736| -------- | -------- | ---- | ------------------------------------------------------------ |
2737| type | string | Yes  | Event type, which is **'subtitleUpdate'** in this case. The event is triggered when the external subtitle is updated.|
2738| callback | function | Yes  | Callback invoked when the subtitle is updated.|
2739
2740**Example**
2741
2742```ts
2743avPlayer.on('subtitleUpdate', async (info: media.SubtitleInfo) => {
2744  if (info) {
2745    let text = (!info.text) ? '' : info.text
2746    let startTime = (!info.startTime) ? 0 : info.startTime
2747    let duration = (!info.duration) ? 0 : info.duration
2748    console.info('subtitleUpdate info: text=' + text + ' startTime=' + startTime +' duration=' + duration)
2749  } else {
2750    console.info('subtitleUpdate info is null')
2751  }
2752})
2753```
2754
2755### off('subtitleUpdate')<sup>12+</sup>
2756
2757off(type: 'subtitleUpdate', callback?: Callback\<SubtitleInfo>): void
2758
2759Unsubscribes from subtitle update events.
2760
2761**Atomic service API**: This API can be used in atomic services since API version 12.
2762
2763**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2764
2765**Parameters**
2766
2767| Name  | Type    | Mandatory| Description                                                        |
2768| -------- | -------- | ---- | ------------------------------------------------------------ |
2769| type | string | Yes  | Event type, which is **'subtitleUpdate'** in this case. The event is triggered when the external subtitle is updated.|
2770| callback | function | No  | Callback that has been registered to listen for subtitle update events.|
2771
2772**Example**
2773
2774```ts
2775avPlayer.off('subtitleUpdate')
2776```
2777
2778### on('trackChange')<sup>12+</sup>
2779
2780on(type: 'trackChange', callback: OnTrackChangeHandler): void
2781
2782Subscribes 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.
2783
2784**Atomic service API**: This API can be used in atomic services since API version 12.
2785
2786**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2787
2788**Parameters**
2789
2790| Name  | Type    | Mandatory| Description                                                        |
2791| -------- | -------- | ---- | ------------------------------------------------------------ |
2792| type | string | Yes  | Event type, which is **'trackChange'** in this case. The event is triggered when the track changes.|
2793| callback | [OnTrackChangeHandler](#ontrackchangehandler12) | Yes  | Callback invoked when the event is triggered.|
2794
2795**Example**
2796
2797```ts
2798avPlayer.on('trackChange', (index: number, isSelect: boolean) => {
2799  console.info('trackChange info: index=' + index + ' isSelect=' + isSelect)
2800})
2801```
2802
2803### off('trackChange')<sup>12+</sup>
2804
2805off(type: 'trackChange', callback?: OnTrackChangeHandler): void
2806
2807Unsubscribes from track change events.
2808
2809**Atomic service API**: This API can be used in atomic services since API version 12.
2810
2811**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2812
2813**Parameters**
2814
2815| Name  | Type    | Mandatory| Description                                                        |
2816| -------- | -------- | ---- | ------------------------------------------------------------ |
2817| type | string | Yes  | Event type, which is **'trackChange'** in this case. The event is triggered when the track changes.|
2818| callback | [OnTrackChangeHandler](#ontrackchangehandler12) | No  | Callback that has been registered to listen for track changes.|
2819
2820**Example**
2821
2822```ts
2823avPlayer.off('trackChange')
2824```
2825
2826### on('trackInfoUpdate')<sup>12+</sup>
2827
2828on(type: 'trackInfoUpdate', callback: Callback\<Array\<MediaDescription>>): void
2829
2830Subscribes 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.
2831
2832**Atomic service API**: This API can be used in atomic services since API version 12.
2833
2834**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2835
2836**Parameters**
2837
2838| Name  | Type    | Mandatory| Description                                                        |
2839| -------- | -------- | ---- | ------------------------------------------------------------ |
2840| type | string | Yes  | Event type, which is **'trackInfoUpdate'** in this case. The event is triggered when the track information is updated.|
2841| callback | Callback\<Array\<[MediaDescription](#mediadescription8)>> | Yes  | Callback invoked when the event is triggered.|
2842
2843**Example**
2844
2845```ts
2846avPlayer.on('trackInfoUpdate', (info: Array<media.MediaDescription>) => {
2847  if (info) {
2848    for (let i = 0; i < info.length; i++) {
2849      let propertyIndex: Object = info[i][media.MediaDescriptionKey.MD_KEY_TRACK_INDEX];
2850      let propertyType: Object = info[i][media.MediaDescriptionKey.MD_KEY_TRACK_TYPE];
2851      console.info('track info: index=' + propertyIndex + ' tracktype=' + propertyType)
2852    }
2853  } else {
2854    console.info('track info is null')
2855  }
2856})
2857```
2858
2859### off('trackInfoUpdate')<sup>12+</sup>
2860
2861off(type: 'trackInfoUpdate', callback?: Callback\<Array\<MediaDescription>>): void
2862
2863Unsubscribes from track information update events.
2864
2865**Atomic service API**: This API can be used in atomic services since API version 12.
2866
2867**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2868
2869**Parameters**
2870
2871| Name  | Type    | Mandatory| Description                                                        |
2872| -------- | -------- | ---- | ------------------------------------------------------------ |
2873| type | string | Yes  | Event type, which is **'trackInfoUpdate'** in this case. The event is triggered when the track information is updated.|
2874| callback | Callback\<Array\<[MediaDescription](#mediadescription8)>> | No  | Callback that has been registered to listen for track information updates.|
2875
2876**Example**
2877
2878```ts
2879avPlayer.off('trackInfoUpdate')
2880```
2881
2882### on('amplitudeUpdate')<sup>13+</sup>
2883
2884on(type: 'amplitudeUpdate', callback: Callback\<Array\<number>>): void
2885
2886Subscribes to update events of the maximum audio level value, which is periodically reported when audio resources are played.
2887
2888**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2889
2890**Parameters**
2891
2892| Name  | Type    | Mandatory| Description                                                        |
2893| -------- | -------- | ---- | ------------------------------------------------------------ |
2894| type     | string   | Yes  | Event type, which is **'amplitudeUpdate'** in this case. The event is triggered when the amplitude changes.|
2895| callback | Callback\<Array\<number>> | Yes  | Callback invoked when the event is triggered.|
2896
2897**Example**
2898
2899```ts
2900avPlayer.on('amplitudeUpdate', (value: Array<number>) => {
2901  console.info('amplitudeUpdate called,and amplitudeUpdate = ${value}')
2902})
2903```
2904
2905### off('amplitudeUpdate')<sup>13+</sup>
2906
2907off(type: 'amplitudeUpdate', callback?: Callback\<Array\<number>>): void
2908
2909Unsubscribes from update events of the maximum amplitude.
2910
2911**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2912
2913**Parameters**
2914
2915| Name| Type  | Mandatory| Description                                                        |
2916| ------ | ------ | ---- | ------------------------------------------------------------ |
2917| type   | string | Yes  | Event type, which is **'amplitudeUpdate'** in this case. The event is triggered when the amplitude changes.|
2918| callback | Callback\<Array\<number>> | No  | Callback that has been registered to listen for amplitude updates.|
2919
2920**Example**
2921
2922```ts
2923avPlayer.off('amplitudeUpdate')
2924```
2925
2926### on('seiMessageReceived')<sup>18+</sup>
2927
2928on(type: 'seiMessageReceived', payloadTypes: Array\<number>, callback: OnSeiMessageHandle): void
2929
2930Subscribes 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.
2931
2932**Atomic service API**: This API can be used in atomic services since API version 18.
2933
2934**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2935
2936**Parameters**
2937
2938| Name  | Type    | Mandatory| Description                                                        |
2939| -------- | -------- | ---- | ------------------------------------------------------------ |
2940| type     | string | Yes| Event type, which is **'seiMessageReceived'** in this case. The event is triggered when an SEI message is received.|
2941| payloadTypes | Array\<number> | Yes| Array of subscribed-to payload types of SEI messages. Currently, only payloadType = 5 is supported.|
2942| callback | [OnSeiMessageHandle](#onseimessagehandle18) | Yes| Callback used to listen for SEI message events and receive the subscribed-to payload types.|
2943
2944**Example**
2945
2946```ts
2947import util from '@ohos.util';
2948
2949avPlayer.on('seiMessageReceived', [5], (messages: Array<media.SeiMessage>, playbackPosition?: number) =>
2950{
2951  console.info('seiMessageReceived playbackPosition ' + playbackPosition)
2952
2953  for (let key = 0; key < messages.length; key++) {
2954    console.info('seiMessageReceived messages payloadType ' + messages[key].payloadType + ' payload size ' + messages[key].payload.byteLength)
2955
2956    let textDecoder = util.TextDecoder.create("utf-8",{ignoreBOM: true})
2957    let ab = messages[key]?.payload?.slice(16, messages[key].payload.byteLength)
2958    let result: Uint8Array = new Uint8Array(ab)
2959    let retStr: string = textDecoder.decodeToString(result)
2960    console.info('seiMessageReceived messages payload ' + retStr)
2961  }
2962});
2963```
2964
2965### off('seiMessageReceived')<sup>18+</sup>
2966
2967off(type: 'seiMessageReceived', payloadTypes?: Array\<number>, callback?: OnSeiMessageHandle): void
2968
2969Unsubscribes from the events indicating that an SEI message is received.
2970
2971**Atomic service API**: This API can be used in atomic services since API version 18.
2972
2973**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2974
2975**Parameters**
2976
2977| Name| Type  | Mandatory| Description                                                        |
2978| ------ | ------ | ---- | ------------------------------------------------------------ |
2979| type     | string   | Yes  | Event type, which is **'seiMessageReceived'** in this case. The event is triggered when an SEI message is received.|
2980| payloadTypes | Array\<number> | No  | Array of subscribed-to payload types of SEI messages.|
2981| callback | [OnSeiMessageHandle](#onseimessagehandle18) | No  | Callback used to listen for SEI message events and receive the subscribed-to payload types.|
2982
2983**Example**
2984
2985```ts
2986avPlayer.off('seiMessageReceived')
2987```
2988
2989### setSuperResolution<sup>18+</sup>
2990
2991setSuperResolution(enabled: boolean) : Promise\<void>
2992
2993Enables 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.
2994
2995Before calling [prepare()](#prepare9), enable super resolution by using [PlaybackStrategy](#playbackstrategy12).
2996
2997**Atomic service API**: This API can be used in atomic services since API version 18.
2998
2999**System capability**: SystemCapability.Multimedia.Media.AVPlayer
3000
3001**Parameters**
3002
3003| Name| Type  | Mandatory| Description                                                        |
3004| ------ | ------ | ---- | ------------------------------------------------------------ |
3005| enabled    | boolean | Yes  | Whether to enable or disable super resolution. The value **true** means to enable it, and **false** means to disable it.|
3006
3007**Return value**
3008
3009| Type          | Description                                      |
3010| -------------- | ------------------------------------------ |
3011| Promise\<void> | Promise that returns no value.|
3012
3013**Error codes**
3014
3015For details about the error codes, see [Media Error Codes](errorcode-media.md).
3016
3017| ID| Error Message                                  |
3018| -------- | ------------------------------------------ |
3019| 5400102  | Operation not allowed. Return by promise. |
3020| 5410003  | Super-resolution not supported. Return by promise. |
3021| 5410004  | Missing enable super-resolution feature in [PlaybackStrategy](#playbackstrategy12). Return by promise. |
3022
3023**Example**
3024
3025```ts
3026avPlayer.setSuperResolution(true)
3027```
3028
3029### setVideoWindowSize<sup>18+</sup>
3030
3031setVideoWindowSize(width: number, height: number) : Promise\<void>
3032
3033Sets 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).
3034
3035Before calling [prepare()](#prepare9), enable super resolution by using [PlaybackStrategy](#playbackstrategy12).
3036
3037**Atomic service API**: This API can be used in atomic services since API version 18.
3038
3039**System capability**: SystemCapability.Multimedia.Media.AVPlayer
3040
3041**Parameters**
3042
3043| Name| Type  | Mandatory| Description                                                        |
3044| ------ | ------ | ---- | ------------------------------------------------------------ |
3045| width    | number | Yes  | Target width of the output video after super resolution. The value range is [320-1920], in px.|
3046| height    | number | Yes  | Target height of the output video after super resolution. The value range is [320-1080], in px.|
3047
3048**Return value**
3049
3050| Type          | Description                                      |
3051| -------------- | ------------------------------------------ |
3052| Promise\<void> | Promise that returns no value.|
3053
3054**Error codes**
3055
3056For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Media Error Codes](errorcode-media.md).
3057
3058| ID| Error Message                                  |
3059| -------- | ------------------------------------------ |
3060| 401      | Parameter error. Return by promise. |
3061| 5400102  | Operation not allowed. Return by promise. |
3062| 5410003  | Super-resolution not supported. Return by promise. |
3063| 5410004  | Missing enable super-resolution feature in [PlaybackStrategy](#playbackstrategy12). Return by promise. |
3064
3065**Example**
3066
3067```ts
3068avPlayer.setVideoWindowSize(1920, 1080)
3069```
3070
3071### on('superResolutionChanged')<sup>18+</sup>
3072
3073on(type:'superResolutionChanged', callback: OnSuperResolutionChanged): void
3074
3075Subscribes to the event indicating that super resolution is enabled or disabled.
3076
3077**Atomic service API**: This API can be used in atomic services since API version 18.
3078
3079**System capability**: SystemCapability.Multimedia.Media.AVPlayer
3080
3081**Parameters**
3082
3083| Name  | Type    | Mandatory| Description                                                        |
3084| -------- | -------- | ---- | ------------------------------------------------------------ |
3085| type     | string | Yes| Event type, which is **'superResolutionChanged'** in this case. The event is triggered when super resolution is enabled or disabled.|
3086| callback | [OnSuperResolutionChanged](#onsuperresolutionchanged-18) | Yes| Callback used to listen for super resolution status changes.|
3087
3088**Example**
3089
3090```ts
3091avPlayer.on('superResolutionChanged', (enabled: boolean) => {
3092  console.info('superResolutionChanged called, and enabled is:' + enabled)
3093})
3094```
3095
3096### off('superResolutionChanged')<sup>18+</sup>
3097
3098off(type:'superResolutionChanged', callback?: OnSuperResolutionChanged): void
3099
3100Unsubscribes from the event indicating that super resolution is enabled or disabled.
3101
3102**Atomic service API**: This API can be used in atomic services since API version 18.
3103
3104**System capability**: SystemCapability.Multimedia.Media.AVPlayer
3105
3106**Parameters**
3107
3108| Name  | Type    | Mandatory| Description                                                        |
3109| -------- | -------- | ---- | ------------------------------------------------------------ |
3110| type     | string | Yes| Event type, which is **'superResolutionChanged'** in this case. The event is triggered when super resolution is enabled or disabled.|
3111| callback | [OnSuperResolutionChanged](#onsuperresolutionchanged-18) | No| Callback used to listen for super resolution status changes.|
3112
3113**Example**
3114
3115```ts
3116avPlayer.off('superResolutionChanged')
3117```
3118
3119## AVPlayerState<sup>9+</sup>
3120
3121type AVPlayerState = 'idle' | 'initialized' | 'prepared' | 'playing' | 'paused' | 'completed' | 'stopped' | 'released' | 'error'
3122
3123Enumerates the states of the [AVPlayer](#avplayer9). Your application can proactively obtain the AVPlayer state through the **state** attribute or obtain the reported AVPlayer state by subscribing to the [stateChange](#onstatechange9) event. For details about the rules for state transition, see [Audio Playback](../../media/media/using-avplayer-for-playback.md).
3124
3125**Atomic service API**: This API can be used in atomic services since API version 11.
3126
3127**System capability**: SystemCapability.Multimedia.Media.AVPlayer
3128
3129|              Type              | Description                                                        |
3130| :-----------------------------: | :----------------------------------------------------------- |
3131|              'idle'               | The AVPlayer enters this state after [createAVPlayer()](#mediacreateavplayer9) or [reset()](#reset9) is called.<br>In case [createAVPlayer()](#mediacreateavplayer9) is used, all attributes are set to their default values.<br>In case [reset()](#reset9) is called, the **url<sup>9+</sup>**, **fdSrc<sup>9+</sup>**, or **dataSrc<sup>10+</sup>** attribute and the **loop** attribute are reset, and other attributes are retained.|
3132|           'initialized'           | The AVPlayer enters this state after **url<sup>9+</sup>** or **fdSrc<sup>9+</sup>** attribute is set in the idle state. In this case, you can configure static attributes such as the window and audio.|
3133|            'prepared'             | The AVPlayer enters this state when [prepare()](#prepare9) is called in the initialized state. In this case, the playback engine has prepared the resources.|
3134|             'playing'             | The AVPlayer enters this state when [play()](#play9) is called in the prepared, paused, or completed state.|
3135|             'paused'              | The AVPlayer enters this state when **pause()** is called in the playing state.|
3136|            'completed'            | The AVPlayer enters this state when a media asset finishes playing and loop playback is not set (no **loop = true**). In this case, if [play()](#play9) is called, the AVPlayer enters the playing state and replays the media asset; if [stop()](#stop9) is called, the AVPlayer enters the stopped state.|
3137|             'stopped'             | The AVPlayer enters this state when [stop()](#stop9) is called in the prepared, playing, paused, or completed state. In this case, the playback engine retains the attributes but releases the memory resources. You can call [prepare()](#prepare9) to prepare the resources again, call [reset()](#reset9) to reset the attributes, or call [release()](#release9) to destroy the playback engine.|
3138|            'released'             | The AVPlayer enters this state when [release()](#release9) is called. The playback engine associated with the **AVPlayer** instance is destroyed, and the playback process ends. This is the final state.|
3139| 'error' | The AVPlayer enters this state when an irreversible error occurs in the playback engine. You can call [reset()](#reset9) to reset the attributes or call [release()](#release9) to destroy the playback engine. For details about the error codes, see [Media Error Codes](errorcode-media.md).<br>**NOTE** Relationship between the error state and the [on('error')](#onerror9) event<br>1. When the AVPlayer enters the error state, the **on('error')** event is triggered. You can obtain the detailed error information through this event.<br>2. When the AVPlayer enters the error state, the playback service stops. This requires the client to design a fault tolerance mechanism to call [reset()](#reset9) or [release()](#release9).<br>3. The client receives **on('error')** event but the AVPlayer does not enter the error state. This situation occurs due to either of the following reasons:<br>Cause 1: The client calls an API in an incorrect state or passes in an incorrect parameter, and the AVPlayer intercepts the call. If this is the case, the client must correct its code logic.<br>Cause 2: A stream error is detected during playback. As a result, the container and decoding are abnormal for a short period of time, but continuous playback and playback control operations are not affected. If this is the case, the client does not need to design a fault tolerance mechanism.|
3140
3141## OnTrackChangeHandler<sup>12+</sup>
3142
3143type OnTrackChangeHandler = (index: number, isSelected: boolean) => void
3144
3145Describes the callback invoked for the track change event.
3146
3147**Atomic service API**: This API can be used in atomic services since API version 12.
3148
3149**System capability**: SystemCapability.Multimedia.Media.AVPlayer
3150
3151| Name  | Type  | Mandatory| Description                                                        |
3152| ------ | ------ | ------ | ---------------------------------------------------------- |
3153| index  | number | Yes| Index of a track.    |
3154| isSelected | boolean | Yes| Status of the track, that is, whether the track is selected.|
3155
3156## OnAVPlayerStateChangeHandle<sup>12+</sup>
3157
3158type OnAVPlayerStateChangeHandle = (state: AVPlayerState, reason: StateChangeReason) => void
3159
3160Describes the callback invoked for the AVPlayer state change event.
3161
3162**Atomic service API**: This API can be used in atomic services since API version 12.
3163
3164**System capability**: SystemCapability.Multimedia.Media.AVPlayer
3165
3166| Name  | Type  | Mandatory| Description                                                        |
3167| ------ | ------ | ------ | ---------------------------------------------------------- |
3168| state  | [AVPlayerState](#avplayerstate9) | Yes| State of the AVPlayer.    |
3169| reason | [StateChangeReason](#statechangereason9) | Yes| Reason for the state change.|
3170
3171## OnBufferingUpdateHandler<sup>12+</sup>
3172
3173type OnBufferingUpdateHandler = (infoType: BufferingInfoType, value: number) => void
3174
3175Describes the callback invoked for the buffering update event.
3176
3177**Atomic service API**: This API can be used in atomic services since API version 12.
3178
3179**System capability**: SystemCapability.Multimedia.Media.AVPlayer
3180
3181| Name  | Type  | Mandatory| Description                                                        |
3182| ------ | ------ | ------ | ------------------------------------------------------------ |
3183| infoType  | [BufferingInfoType](#bufferinginfotype8) | Yes| Buffering information type.    |
3184| value | number | Yes| The value is fixed at **0**.|
3185
3186## OnVideoSizeChangeHandler<sup>12+</sup>
3187
3188type OnVideoSizeChangeHandler = (width: number, height: number) => void
3189
3190Describes the callback invoked for the video size change event.
3191
3192**Atomic service API**: This API can be used in atomic services since API version 12.
3193
3194**System capability**: SystemCapability.Multimedia.Media.AVPlayer
3195
3196| Name  | Type  | Mandatory| Description                                                        |
3197| ------ | ------ | ------ | ------------------------------------------------------------ |
3198| width  | number | Yes| Video width, in px.|
3199| height | number | Yes| Video height, in px.|
3200
3201## OnSeiMessageHandle<sup>18+</sup>
3202
3203type OnSeiMessageHandle = (messages: Array\<SeiMessage>, playbackPosition?: number) => void
3204
3205Describes the handle used to obtain SEI messages. This is used when in subscriptions to SEI message events, and the callback returns detailed SEI information.
3206
3207**Atomic service API**: This API can be used in atomic services since API version 18.
3208
3209**System capability**: SystemCapability.Multimedia.Media.AVPlayer
3210
3211**Parameters**
3212
3213| Name  |   Type  | Mandatory| Description                                                        |
3214| ------ | ------ | ---- | ------------------------------------------------------------ |
3215| messages | Array\<[SeiMessage](#seimessage18)> | Yes | Array of SEI messages.|
3216| playbackPosition | number | No | Current playback position, in milliseconds.|
3217
3218## OnSuperResolutionChanged <sup>18+</sup>
3219
3220type OnSuperResolutionChanged = (enabled: boolean) => void
3221
3222Describes the callback used to listen for video super resolution status changes. If super resolution is enabled by using [PlaybackStrategy](#playbackstrategy12), this callback is invoked to report the super resolution status changes. It is also invoked to report the initial status when the video starts. However, this callback is not invoked when super resolution is not enabled.
3223
3224Super resolution is automatically disabled in either of the following cases:
3225* The current super resolution algorithm only works with videos that have a frame rate of 30 fps or lower. If the video frame rate exceeds 30 fps, or if the input frame rate exceeds the processing capability of the super resolution algorithm in scenarios such as fast playback, super resolution is automatically disabled.
3226* The current super resolution algorithm supports input resolutions from 320 x 320 to 1920 x 1080, in px. If the input video resolution exceeds the range during playback, super resolution is automatically disabled.
3227
3228**Atomic service API**: This API can be used in atomic services since API version 18.
3229
3230**System capability**: SystemCapability.Multimedia.Media.AVPlayer
3231
3232| Name  | Type  | Mandatory| Description                                                        |
3233| ------ | ------ | ------ | ------------------------------------------------------------ |
3234| enabled  | boolean | Yes| Whether super resolution is enabled. The value **true** means that it is enabled, and **false** means the opposite.    |
3235
3236## AVFileDescriptor<sup>9+</sup>
3237
3238Describes an audio and video file asset. It is used to specify a particular asset for playback based on its offset and length within a file.
3239
3240**Atomic service API**: This API can be used in atomic services since API version 11.
3241
3242**System capability**: SystemCapability.Multimedia.Media.Core
3243
3244| Name  | Type  | Mandatory| Description                                                        |
3245| ------ | ------ | ---- | ------------------------------------------------------------ |
3246| fd     | number | Yes  | Resource handle, which is obtained by calling [resourceManager.getRawFd](../apis-localization-kit/js-apis-resource-manager.md#getrawfd9) or [fs.open](../apis-core-file-kit/js-apis-file-fs.md#fsopen).   |
3247| offset | number | No  | Resource offset, which needs to be entered based on the preset asset information. The default value is **0**. An invalid value causes a failure to parse audio and video assets.|
3248| length | number | No  | Resource length, which needs to be entered based on the preset asset information. The default value is the remaining bytes from the offset in the file. An invalid value causes a failure to parse audio and video assets.|
3249
3250## AVDataSrcDescriptor<sup>10+</sup>
3251
3252Defines the descriptor of an audio and video file, which is used in DataSource playback mode.<br>Use scenario: An application can create a playback instance and start playback before it finishes downloading the audio and video resources.
3253
3254**Atomic service API**: This API can be used in atomic services since API version 11.
3255
3256**System capability**: SystemCapability.Multimedia.Media.AVPlayer
3257
3258| Name  | Type  | Mandatory| Description                                                        |
3259| ------ | ------ | ---- | ------------------------------------------------------------ |
3260| fileSize     | number | Yes  | Size of the file to play, in bytes. The value **-1** indicates that the size is unknown. If **fileSize** is set to **-1**, the playback mode is similar to the live mode. In this mode, the **seek** and **setSpeed** operations cannot be performed, and the **loop** attribute cannot be set, indicating that loop playback is unavailable.|
3261| callback | (buffer: ArrayBuffer, length: number, pos?: number) => number | Yes  | Callback used to fill in data.<br>- Function: callback: (buffer: ArrayBuffer, length: number, pos?:number) => number;<br>- **buffer**: memory to be filled. The value is of the ArrayBuffer type. This parameter is mandatory.<br>- **length**: maximum length of the memory to be filled. The value is of the number type. This parameter is mandatory.<br>- **pos**: position of the data to be filled in the file. The value is of the number type. This parameter is optional. When **fileSize** is set to **-1**, this parameter cannot be used.<br>- Return value: length of the data filled, which is of the number type. If **-1** is returned, the end of stream is reached. If **-2** is returned, an unrecoverable error occurs.|
3262
3263## SubtitleInfo<sup>12+</sup>
3264
3265Describes the external subtitle information. When a subtitle update event is subscribed to, the information about the external subtitle is returned through a callback.
3266
3267**Atomic service API**: This API can be used in atomic services since API version 12.
3268
3269**System capability**: SystemCapability.Multimedia.Media.Core
3270
3271| Name  | Type  | Mandatory| Description                                                        |
3272| ------ | ------ | ---- | ------------------------------------------------------------ |
3273| text | string | No | Text information of the subtitle.|
3274| startTime | number | No | Start time for displaying the subtitle, in milliseconds.|
3275| duration | number | No| Duration for displaying the subtitle, in milliseconds.|
3276
3277## SeiMessage<sup>18+</sup>
3278
3279Describes the information of an SEI message.
3280
3281**Atomic service API**: This API can be used in atomic services since API version 18.
3282
3283**System capability**: SystemCapability.Multimedia.Media.Core
3284
3285| Name  | Type  | Read-Only| Optional | Description                                                        |
3286| ------ | ------ | ---- | ---- | ------------------------------------------------------------ |
3287| payloadType | number | No | No | Payload type of the SEI message.|
3288| payload | ArrayBuffer | No | No | Payload data of the SEI message.|
3289
3290## SeekMode<sup>8+</sup>
3291
3292Enumerates the video playback seek modes, which can be passed in the **seek** API.
3293
3294**System capability**: SystemCapability.Multimedia.Media.Core
3295
3296| Name          | Value  | Description                                                        |
3297| -------------- | ---- | ------------------------------------------------------------ |
3298| SEEK_NEXT_SYNC | 0    | Seeks to the next key frame at the specified position. You are advised to use this value for the rewind operation.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
3299| SEEK_PREV_SYNC | 1    | Seeks to the previous key frame at the specified position. You are advised to use this value for the fast-forward operation.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
3300| SEEK_CLOSEST<sup>12+</sup> | 2    | Seeks to the frame closest to the specified position. You are advised to use this value for accurate seek.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
3301| SEEK_CONTINUOUS<sup>18+</sup> | 3    | Offers a smooth and fluid visual experience for seeking. Applications can use a progress bar component to continuously invoke the **seek** method, and the AVPlayer will update the video frames smoothly in response to these calls.<br>Applications can call [isSeekContinuousSupported](#isseekcontinuoussupported18) to check whether the video source supports this seeking mode.<br>If the video source does not support this mode, calling **seek** will result in an **AVERR_SEEK_CONTINUOUS_UNSUPPORTED** error (see [Media Error Codes](#averrorcode9)), and the smoothness of frame updates will be compromised.<br>This seeking mode does not trigger the [seekDone event](#onseekdone9).<br>To exit this seeking mode, applications must call **seek(-1, SeekMode.SEEK_CONTINUOUS)** to end the seeking process.<br>**Atomic service API**: This API can be used in atomic services since API version 18.|
3302
3303## SwitchMode<sup>12+</sup>
3304
3305Enumerates the track switching modes for video playback. The mode can be passed in to **selectTrack**. Currently, this enum is valid only for DASH video tracks.
3306
3307**System capability**: SystemCapability.Multimedia.Media.Core
3308
3309| Name          | Value  | Description                                                        |
3310| -------------- | ---- | ------------------------------------------------------------ |
3311| SMOOTH | 0    | Smooth playback is ensured after the switching. This mode has a delay, that is, the switching does not take effect immediately.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
3312| SEGMENT | 1    | The playback starts from the start position of the current segment after the switching. In this mode, the switching takes effect immediately and repeated playback may occur.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
3313| CLOSEST | 2    | The playback starts from the frame closest to the current playback time. In this mode, the switching takes effect immediately, and the playback is suspended for 3s to 5s and then resumed.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
3314
3315## PlaybackSpeed<sup>8+</sup>
3316
3317Enumerates the video playback speeds, which can be passed in the **setSpeed** API.
3318
3319**Atomic service API**: This API can be used in atomic services since API version 12.
3320
3321**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
3322
3323| Name                | Value  | Description                          |
3324| -------------------- | ---- | ------------------------------ |
3325| SPEED_FORWARD_0_75_X | 0    | Plays the video at 0.75 times the normal speed.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
3326| SPEED_FORWARD_1_00_X | 1    | Plays the video at the normal speed.<br>**Atomic service API**: This API can be used in atomic services since API version 12.        |
3327| SPEED_FORWARD_1_25_X | 2    | Plays the video at 1.25 times the normal speed.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
3328| SPEED_FORWARD_1_75_X | 3    | Plays the video at 1.75 times the normal speed.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
3329| SPEED_FORWARD_2_00_X | 4    | Plays the video at 2.00 times the normal speed.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
3330| SPEED_FORWARD_0_50_X<sup>12+</sup> | 5    | Plays the video at 0.50 times the normal speed.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
3331| SPEED_FORWARD_1_50_X<sup>12+</sup> | 6    | Plays the video at 1.50 times the normal speed.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
3332| SPEED_FORWARD_3_00_X<sup>13+</sup> | 7    | Plays the video at 3.00 times the normal speed.<br>**Atomic service API**: This API can be used in atomic services since API version 13.|
3333| SPEED_FORWARD_0_25_X<sup>12+</sup> | 8    | Plays the video at 0.25 times the normal speed.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
3334| SPEED_FORWARD_0_125_X<sup>12+</sup> | 9    | Plays the video at 0.125 times the normal speed.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
3335
3336## VideoScaleType<sup>9+</sup>
3337
3338Enumerates the video scale modes.
3339
3340**Atomic service API**: This API can be used in atomic services since API version 12.
3341
3342**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
3343
3344| Name                     | Value  | Description                                            |
3345| ------------------------- | ---- | ------------------------------------------------ |
3346| VIDEO_SCALE_TYPE_FIT      | 0    | Default mode. The video will be stretched to fit the window.             |
3347| VIDEO_SCALE_TYPE_FIT_CROP | 1    | The video will be stretched to fit the window, without changing its aspect ratio. The content may be cropped.|
3348
3349## MediaDescription<sup>8+</sup>
3350
3351Defines media information in key-value mode.
3352
3353**Atomic service API**: This API can be used in atomic services since API version 11.
3354
3355**System capability**: SystemCapability.Multimedia.Media.Core
3356
3357| Name         | Type  | Mandatory| Description                                                        |
3358| ------------- | ------ | ---- | ------------------------------------------------------------ |
3359| [key: string] | Object | Yes  | For details about the key range supported and the object type and range of each key, see [MediaDescriptionKey](#mediadescriptionkey8).|
3360
3361**Example**
3362
3363```ts
3364import { BusinessError } from '@kit.BasicServicesKit';
3365
3366function printfItemDescription(obj: media.MediaDescription, key: string) {
3367  let property: Object = obj[key];
3368  console.info('audio key is ' + key); // Specify a key. For details about the keys, see [MediaDescriptionKey].
3369  console.info('audio value is ' + property); // Obtain the value of the key. The value can be any type. For details about the types, see [MediaDescriptionKey].
3370}
3371
3372let avPlayer: media.AVPlayer | undefined = undefined;
3373media.createAVPlayer((err: BusinessError, player: media.AVPlayer) => {
3374  if(player != null) {
3375    avPlayer = player;
3376    console.info(`Succeeded in creating AVPlayer`);
3377    avPlayer.getTrackDescription((error: BusinessError, arrList: Array<media.MediaDescription>) => {
3378      if (arrList != null) {
3379        for (let i = 0; i < arrList.length; i++) {
3380          printfItemDescription(arrList[i], media.MediaDescriptionKey.MD_KEY_TRACK_TYPE);  // Print the MD_KEY_TRACK_TYPE value of each track.
3381        }
3382      } else {
3383        console.error(`Failed to get TrackDescription, error:${error}`);
3384      }
3385    });
3386  } else {
3387    console.error(`Failed to create AVPlayer, error message:${err.message}`);
3388  }
3389});
3390```
3391
3392## PlaybackInfo<sup>12+</sup>
3393
3394Defines the playback information in key-value pairs.
3395
3396**System capability**: SystemCapability.Multimedia.Media.Core
3397
3398| Name         | Type  | Mandatory| Description                                                        |
3399| ------------- | ------ | ---- | ------------------------------------------------------------ |
3400| [key: string] | Object | Yes  | For details about the key range supported and the object type and range of each key, see [PlaybackInfoKey](#playbackinfokey12).|
3401
3402**Example**
3403
3404```ts
3405import { BusinessError } from '@kit.BasicServicesKit';
3406
3407function printfPlaybackInfo(obj: media.PlaybackInfo, key: string) {
3408  let property: Object = obj[key];
3409  console.info('key is ' + key); // // Specify a key. For details about the keys, see [PlaybackInfoKey].
3410  console.info('value is ' + property); // Obtain the value of the key. The value can be any type. For details about the types, see [PlaybackInfoKey].
3411}
3412
3413let avPlayer: media.AVPlayer | undefined = undefined;
3414let playbackInfo: media.PlaybackInfo | undefined = undefined;
3415media.createAVPlayer(async (err: BusinessError, player: media.AVPlayer) => {
3416  if (player != null) {
3417    avPlayer = player;
3418    console.info(`Succeeded in creating AVPlayer`);
3419    if (avPlayer) {
3420      try {
3421        playbackInfo = await avPlayer.getPlaybackInfo();
3422        console.info(`AVPlayer getPlaybackInfo = ${JSON.stringify(playbackInfo)}`); // Print PlaybackInfo.
3423        printfPlaybackInfo(playbackInfo, media.PlaybackInfoKey.SERVER_IP_ADDRESS); // Print the IP address.
3424      } catch (error) {
3425        console.error(`error = ${error}`);
3426      }
3427    }
3428  } else {
3429    console.error(`Failed to create AVPlayer, error message:${err.message}`);
3430  }
3431});
3432```
3433
3434## AVRecorder<sup>9+</sup>
3435
3436A recording management class that provides APIs to record media assets. Before calling any API in **AVRecorder**, you must use [createAVRecorder()](#mediacreateavrecorder9) to create an **AVRecorder** instance.
3437
3438For details about the audio and video recording demo, see [Audio Recording](../../media/media/using-avrecorder-for-recording.md) and [Video Recording](../../media/media/video-recording.md).
3439
3440> **NOTE**
3441>
3442> To use the camera to record videos, the camera module is required. For details about how to use the APIs provided by the camera module, see [Camera Management](../apis-camera-kit/js-apis-camera.md).
3443
3444### Attributes
3445
3446**System capability**: SystemCapability.Multimedia.Media.AVRecorder
3447
3448| Name   | Type                                | Read-Only| Optional| Description              |
3449| ------- | ------------------------------------ | ---- | ---- | ------------------ |
3450| state9+ | [AVRecorderState](#avrecorderstate9) | Yes  | No  | AVRecorder state.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
3451
3452### prepare<sup>9+</sup>
3453
3454prepare(config: AVRecorderConfig, callback: AsyncCallback\<void>): void
3455
3456Sets audio and video recording parameters. This API uses an asynchronous callback to return the result.
3457
3458**Required permissions:** ohos.permission.MICROPHONE
3459
3460This permission is required only if audio recording is involved.
3461
3462To use the camera to record videos, the camera module is required. For details about how to use the APIs provided by the camera module, see [Camera Management](../apis-camera-kit/js-apis-camera.md).
3463
3464**System capability**: SystemCapability.Multimedia.Media.AVRecorder
3465
3466**Parameters**
3467
3468| Name  | Type                                  | Mandatory| Description                                 |
3469| -------- | -------------------------------------- | ---- | ------------------------------------- |
3470| config   | [AVRecorderConfig](#avrecorderconfig9) | Yes  | Audio and video recording parameters to set.           |
3471| callback | AsyncCallback\<void>                   | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
3472
3473**Error codes**
3474
3475For details about the error codes, see [Media Error Codes](errorcode-media.md).
3476
3477| ID| Error Message                               |
3478| -------- | --------------------------------------- |
3479| 201      | Permission denied. Return by callback.  |
3480| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed.    |
3481| 5400102  | Operate not permit. Return by callback. |
3482| 5400105  | Service died. Return by callback.       |
3483
3484**Example**
3485
3486```ts
3487import { BusinessError } from '@kit.BasicServicesKit';
3488
3489// Configure the parameters based on those supported by the hardware device.
3490let avRecorderProfile: media.AVRecorderProfile = {
3491  audioBitrate : 48000,
3492  audioChannels : 2,
3493  audioCodec : media.CodecMimeType.AUDIO_AAC,
3494  audioSampleRate : 48000,
3495  fileFormat : media.ContainerFormatType.CFT_MPEG_4,
3496  videoBitrate : 2000000,
3497  videoCodec : media.CodecMimeType.VIDEO_AVC,
3498  videoFrameWidth : 640,
3499  videoFrameHeight : 480,
3500  videoFrameRate : 30
3501}
3502let avRecorderConfig: media.AVRecorderConfig = {
3503  audioSourceType : media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC,
3504  videoSourceType : media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV,
3505  profile : avRecorderProfile,
3506  url : 'fd://', // Before passing in an FD to this parameter, the file must be created by the caller and granted with the read and write permissions. Example value: fd://45.
3507  rotation: 0, // The value can be 0, 90, 180, or 270. If any other value is used, prepare() reports an error.
3508  location : { latitude : 30, longitude : 130 }
3509}
3510
3511avRecorder.prepare(avRecorderConfig, (err: BusinessError) => {
3512  if (err) {
3513    console.error('Failed to prepare and error is ' + err.message);
3514  } else {
3515    console.info('Succeeded in preparing');
3516  }
3517})
3518```
3519
3520### prepare<sup>9+</sup>
3521
3522prepare(config: AVRecorderConfig): Promise\<void>
3523
3524Sets audio and video recording parameters. This API uses a promise to return the result.
3525
3526**Required permissions:** ohos.permission.MICROPHONE
3527
3528This permission is required only if audio recording is involved.
3529
3530To use the camera to record videos, the camera module is required. For details about how to use the APIs provided by the camera module, see [Camera Management](../apis-camera-kit/js-apis-camera.md).
3531
3532**Atomic service API**: This API can be used in atomic services since API version 12.
3533
3534**System capability**: SystemCapability.Multimedia.Media.AVRecorder
3535
3536**Parameters**
3537
3538| Name| Type                                  | Mandatory| Description                      |
3539| ------ | -------------------------------------- | ---- | -------------------------- |
3540| config | [AVRecorderConfig](#avrecorderconfig9) | Yes  | Audio and video recording parameters to set.|
3541
3542**Return value**
3543
3544| Type          | Description                                      |
3545| -------------- | ------------------------------------------ |
3546| Promise\<void> | Promise that returns no value.|
3547
3548**Error codes**
3549
3550For details about the error codes, see [Media Error Codes](errorcode-media.md).
3551
3552| ID| Error Message                              |
3553| -------- | -------------------------------------- |
3554| 201      | Permission denied. Return by promise.  |
3555| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed.    |
3556| 5400102  | Operate not permit. Return by promise. |
3557| 5400105  | Service died. Return by promise.       |
3558
3559**Example**
3560
3561```ts
3562import { BusinessError } from '@kit.BasicServicesKit';
3563
3564// Configure the parameters based on those supported by the hardware device.
3565let avRecorderProfile: media.AVRecorderProfile = {
3566  audioBitrate : 48000,
3567  audioChannels : 2,
3568  audioCodec : media.CodecMimeType.AUDIO_AAC,
3569  audioSampleRate : 48000,
3570  fileFormat : media.ContainerFormatType.CFT_MPEG_4,
3571  videoBitrate : 2000000,
3572  videoCodec : media.CodecMimeType.VIDEO_AVC,
3573  videoFrameWidth : 640,
3574  videoFrameHeight : 480,
3575  videoFrameRate : 30
3576}
3577let avRecorderConfig: media.AVRecorderConfig = {
3578  audioSourceType : media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC,
3579  videoSourceType : media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV,
3580  profile : avRecorderProfile,
3581  url : 'fd://', // Before passing in an FD to this parameter, the file must be created by the caller and granted with the read and write permissions. Example value: fd://45.
3582  rotation: 0, // The value can be 0, 90, 180, or 270. If any other value is used, prepare() reports an error.
3583  location : { latitude : 30, longitude : 130 }
3584}
3585
3586avRecorder.prepare(avRecorderConfig).then(() => {
3587  console.info('Succeeded in preparing');
3588}).catch((err: BusinessError) => {
3589  console.error('Failed to prepare and catch error is ' + err.message);
3590});
3591```
3592
3593### getInputSurface<sup>9+</sup>
3594
3595getInputSurface(callback: AsyncCallback\<string>): void
3596
3597Obtains the surface required for recording. This API uses an asynchronous callback to return the result. The caller obtains the **surfaceBuffer** from this surface and fills in the corresponding video data.
3598
3599Note that the video data must carry the timestamp (in ns) and buffer size, and the start time of the timestamp must be based on the system startup time.
3600
3601This API can be called only after the [prepare()](#prepare9-2) API is called.
3602
3603**System capability**: SystemCapability.Multimedia.Media.AVRecorder
3604
3605**Parameters**
3606
3607| Name  | Type                  | Mandatory| Description                       |
3608| -------- | ---------------------- | ---- | --------------------------- |
3609| callback | AsyncCallback\<string> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the surface ID obtained; otherwise, **err** is an error object.|
3610
3611**Error codes**
3612
3613For details about the error codes, see [Media Error Codes](errorcode-media.md).
3614
3615| ID| Error Message                               |
3616| -------- | --------------------------------------- |
3617| 5400102  | Operate not permit. Return by callback. |
3618| 5400103  | IO error. Return by callback.           |
3619| 5400105  | Service died. Return by callback.       |
3620
3621**Example**
3622
3623```ts
3624import { BusinessError } from '@kit.BasicServicesKit';
3625let surfaceID: string; // The surfaceID is transferred to the camera API to create a videoOutput instance.
3626
3627avRecorder.getInputSurface((err: BusinessError, surfaceId: string) => {
3628  if (err) {
3629    console.error('Failed to do getInputSurface and error is ' + err.message);
3630  } else {
3631    console.info('Succeeded in doing getInputSurface');
3632    surfaceID = surfaceId;
3633  }
3634});
3635
3636```
3637
3638### getInputSurface<sup>9+</sup>
3639
3640getInputSurface(): Promise\<string>
3641
3642Obtains the surface required for recording. This API uses a promise to return the result. The caller obtains the **surfaceBuffer** from this surface and fills in the corresponding video data.
3643
3644Note that the video data must carry the timestamp (in ns) and buffer size, and the start time of the timestamp must be based on the system startup time.
3645
3646This API can be called only after the [prepare()](#prepare9-3) API is called.
3647
3648**System capability**: SystemCapability.Multimedia.Media.AVRecorder
3649
3650**Return value**
3651
3652| Type            | Description                            |
3653| ---------------- | -------------------------------- |
3654| Promise\<string> | Promise used to return the result.|
3655
3656**Error codes**
3657
3658For details about the error codes, see [Media Error Codes](errorcode-media.md).
3659
3660| ID| Error Message                              |
3661| -------- | -------------------------------------- |
3662| 5400102  | Operate not permit. Return by promise. |
3663| 5400103  | IO error. Return by promise.           |
3664| 5400105  | Service died. Return by promise.       |
3665
3666**Example**
3667
3668```ts
3669import { BusinessError } from '@kit.BasicServicesKit';
3670let surfaceID: string; // The surfaceID is transferred to the camera API to create a videoOutput instance.
3671
3672avRecorder.getInputSurface().then((surfaceId: string) => {
3673  console.info('Succeeded in getting InputSurface');
3674  surfaceID = surfaceId;
3675}).catch((err: BusinessError) => {
3676  console.error('Failed to get InputSurface and catch error is ' + err.message);
3677});
3678```
3679
3680### updateRotation<sup>12+</sup>
3681
3682updateRotation(rotation: number): Promise\<void>
3683
3684Updates the video rotation angle. This API uses a promise to return the result.
3685
3686This API can be called only after the [prepare()](#prepare9-3) event is triggered and before the [start()](#start9) API is called.
3687
3688**System capability**: SystemCapability.Multimedia.Media.AVRecorder
3689
3690**Parameters**
3691
3692| Name  | Type                | Mandatory| Description                       |
3693| -------- | -------------------- | ---- | --------------------------- |
3694| rotation | number | Yes  | Rotation angle, which can only be 0, 90, 180, or 270 degrees.|
3695
3696**Return value**
3697
3698| Type            | Description                            |
3699| ---------------- | -------------------------------- |
3700| Promise\<void> | Promise that returns no value.|
3701
3702**Error codes**
3703
3704For details about the error codes, see [Media Error Codes](errorcode-media.md).
3705
3706| ID| Error Message                              |
3707| -------- | -------------------------------------- |
3708|   401    | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed.   |
3709| 5400102  | Operation not allowed. Return by promise. |
3710| 5400103  | IO error. Return by promise.           |
3711| 5400105  | Service died. Return by promise.       |
3712
3713**Example**
3714
3715```ts
3716import { BusinessError } from '@kit.BasicServicesKit';
3717
3718let rotation = 90
3719
3720avRecorder.updateRotation(rotation).then(() => {
3721  console.info('Succeeded in updateRotation');
3722}).catch((err: BusinessError) => {
3723  console.error('Failed to updateRotation and catch error is ' + err.message);
3724});
3725```
3726
3727### start<sup>9+</sup>
3728
3729start(callback: AsyncCallback\<void>): void
3730
3731Starts recording. This API uses an asynchronous callback to return the result.
3732
3733For audio-only recording, this API can be called only after the [prepare()](#prepare9-2) API is called. For video-only recording, this API can be called only after the [getInputSurface()](#getinputsurface9) API is called.
3734
3735**System capability**: SystemCapability.Multimedia.Media.AVRecorder
3736
3737**Parameters**
3738
3739| Name  | Type                | Mandatory| Description                        |
3740| -------- | -------------------- | ---- | ---------------------------- |
3741| callback | AsyncCallback\<void> | Yes  |Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
3742
3743**Error codes**
3744
3745For details about the error codes, see [Media Error Codes](errorcode-media.md).
3746
3747| ID| Error Message                               |
3748| -------- | --------------------------------------- |
3749| 5400102  | Operate not permit. Return by callback. |
3750| 5400103  | IO error. Return by callback.           |
3751| 5400105  | Service died. Return by callback.       |
3752
3753**Example**
3754
3755```ts
3756import { BusinessError } from '@kit.BasicServicesKit';
3757
3758avRecorder.start((err: BusinessError) => {
3759  if (err) {
3760    console.error('Failed to start AVRecorder and error is ' + err.message);
3761  } else {
3762    console.info('Succeeded in starting AVRecorder');
3763  }
3764});
3765```
3766
3767### start<sup>9+</sup>
3768
3769start(): Promise\<void>
3770
3771Starts recording. This API uses a promise to return the result.
3772
3773For audio-only recording, this API can be called only after the [prepare()](#prepare9-3) API is called. For video-only recording, this API can be called only after the [getInputSurface()](#getinputsurface9-1) API is called.
3774
3775**Atomic service API**: This API can be used in atomic services since API version 12.
3776
3777**System capability**: SystemCapability.Multimedia.Media.AVRecorder
3778
3779**Return value**
3780
3781| Type          | Description                                 |
3782| -------------- | ------------------------------------- |
3783| Promise\<void> | Promise that returns no value.|
3784
3785**Error codes**
3786
3787For details about the error codes, see [Media Error Codes](errorcode-media.md).
3788
3789| ID| Error Message                              |
3790| -------- | -------------------------------------- |
3791| 5400102  | Operate not permit. Return by promise. |
3792| 5400103  | IO error. Return by promise.           |
3793| 5400105  | Service died. Return by promise.       |
3794
3795**Example**
3796
3797```ts
3798import { BusinessError } from '@kit.BasicServicesKit';
3799
3800avRecorder.start().then(() => {
3801  console.info('Succeeded in starting AVRecorder');
3802}).catch((err: BusinessError) => {
3803  console.error('Failed to start AVRecorder and catch error is ' + err.message);
3804});
3805```
3806
3807### pause<sup>9+</sup>
3808
3809pause(callback: AsyncCallback\<void>): void
3810
3811Pauses recording. This API uses an asynchronous callback to return the result.
3812
3813This API can be called only after the [start()](#start9) API is called. You can call [resume()](#resume9) to resume recording.
3814
3815**System capability**: SystemCapability.Multimedia.Media.AVRecorder
3816
3817**Parameters**
3818
3819| Name  | Type                | Mandatory| Description                       |
3820| -------- | -------------------- | ---- | --------------------------- |
3821| callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
3822
3823**Error codes**
3824
3825For details about the error codes, see [Media Error Codes](errorcode-media.md).
3826
3827| ID| Error Message                               |
3828| -------- | --------------------------------------- |
3829| 5400102  | Operate not permit. Return by callback. |
3830| 5400103  | IO error. Return by callback.           |
3831| 5400105  | Service died. Return by callback.       |
3832
3833**Example**
3834
3835```ts
3836import { BusinessError } from '@kit.BasicServicesKit';
3837
3838avRecorder.pause((err: BusinessError) => {
3839  if (err) {
3840    console.error('Failed to pause AVRecorder and error is ' + err.message);
3841  } else {
3842    console.info('Succeeded in pausing');
3843  }
3844});
3845```
3846
3847### pause<sup>9+</sup>
3848
3849pause(): Promise\<void>
3850
3851Pauses recording. This API uses a promise to return the result.
3852
3853This API can be called only after the [start()](#start9-1) API is called. You can call [resume()](#resume9-1) to resume recording.
3854
3855**Atomic service API**: This API can be used in atomic services since API version 12.
3856
3857**System capability**: SystemCapability.Multimedia.Media.AVRecorder
3858
3859**Return value**
3860
3861| Type          | Description                                 |
3862| -------------- | ------------------------------------- |
3863| Promise\<void> | Promise that returns no value.|
3864
3865**Error codes**
3866
3867For details about the error codes, see [Media Error Codes](errorcode-media.md).
3868
3869| ID| Error Message                              |
3870| -------- | -------------------------------------- |
3871| 5400102  | Operate not permit. Return by promise. |
3872| 5400103  | IO error. Return by promise.           |
3873| 5400105  | Service died. Return by promise.       |
3874
3875**Example**
3876
3877```ts
3878import { BusinessError } from '@kit.BasicServicesKit';
3879
3880avRecorder.pause().then(() => {
3881  console.info('Succeeded in pausing');
3882}).catch((err: BusinessError) => {
3883  console.error('Failed to pause AVRecorder and catch error is ' + err.message);
3884});
3885```
3886
3887### resume<sup>9+</sup>
3888
3889resume(callback: AsyncCallback\<void>): void
3890
3891Resumes recording. This API uses an asynchronous callback to return the result.
3892
3893This API can be called only after the [pause()](#pause9-2) API is called.
3894
3895**System capability**: SystemCapability.Multimedia.Media.AVRecorder
3896
3897**Parameters**
3898
3899| Name  | Type                | Mandatory| Description                        |
3900| -------- | -------------------- | ---- | ---------------------------- |
3901| callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
3902
3903**Error codes**
3904
3905For details about the error codes, see [Media Error Codes](errorcode-media.md).
3906
3907| ID| Error Message                               |
3908| -------- | --------------------------------------- |
3909| 5400102  | Operate not permit. Return by callback. |
3910| 5400103  | IO error. Return by callback.           |
3911| 5400105  | Service died. Return by callback.       |
3912
3913**Example**
3914
3915```ts
3916import { BusinessError } from '@kit.BasicServicesKit';
3917
3918avRecorder.resume((err: BusinessError) => {
3919  if (err) {
3920    console.error('Failed to resume AVRecorder and error is ' + err.message);
3921  } else {
3922    console.info('Succeeded in resuming AVRecorder');
3923  }
3924});
3925```
3926
3927### resume<sup>9+</sup>
3928
3929resume(): Promise\<void>
3930
3931Resumes recording. This API uses a promise to return the result.
3932
3933This API can be called only after the [pause()](#pause9-3) API is called.
3934
3935**Atomic service API**: This API can be used in atomic services since API version 12.
3936
3937**System capability**: SystemCapability.Multimedia.Media.AVRecorder
3938
3939**Return value**
3940
3941| Type          | Description                                 |
3942| -------------- | ------------------------------------- |
3943| Promise\<void> | Promise that returns no value.|
3944
3945**Error codes**
3946
3947For details about the error codes, see [Media Error Codes](errorcode-media.md).
3948
3949| ID| Error Message                              |
3950| -------- | -------------------------------------- |
3951| 5400102  | Operate not permit. Return by promise. |
3952| 5400103  | IO error. Return by promise.           |
3953| 5400105  | Service died. Return by promise.       |
3954
3955**Example**
3956
3957```ts
3958import { BusinessError } from '@kit.BasicServicesKit';
3959
3960avRecorder.resume().then(() => {
3961  console.info('Succeeded in resuming AVRecorder');
3962}).catch((err: BusinessError) => {
3963  console.error('Failed to resume  AVRecorder failed and catch error is ' + err.message);
3964});
3965```
3966
3967### stop<sup>9+</sup>
3968
3969stop(callback: AsyncCallback\<void>): void
3970
3971Stops recording. This API uses an asynchronous callback to return the result.
3972
3973This API can be called only after the [start()](#start9) or [pause()](#pause9-2) API is called.
3974
3975For audio-only recording, you can call [prepare()](#prepare9-2) again for re-recording. For video-only recording or audio and video recording, you can call [prepare()](#prepare9-2) and [getInputSurface()](#getinputsurface9) again for re-recording.
3976
3977**System capability**: SystemCapability.Multimedia.Media.AVRecorder
3978
3979**Parameters**
3980
3981| Name  | Type                | Mandatory| Description                        |
3982| -------- | -------------------- | ---- | ---------------------------- |
3983| callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
3984
3985**Error codes**
3986
3987For details about the error codes, see [Media Error Codes](errorcode-media.md).
3988
3989| ID| Error Message                               |
3990| -------- | --------------------------------------- |
3991| 5400102  | Operate not permit. Return by callback. |
3992| 5400103  | IO error. Return by callback.           |
3993| 5400105  | Service died. Return by callback.       |
3994
3995**Example**
3996
3997```ts
3998import { BusinessError } from '@kit.BasicServicesKit';
3999
4000avRecorder.stop((err: BusinessError) => {
4001  if (err) {
4002    console.error('Failed to stop AVRecorder and error is ' + err.message);
4003  } else {
4004    console.info('Succeeded in stopping AVRecorder');
4005  }
4006});
4007```
4008
4009### stop<sup>9+</sup>
4010
4011stop(): Promise\<void>
4012
4013Stops recording. This API uses a promise to return the result.
4014
4015This API can be called only after the [start()](#start9-1) or [pause()](#pause9-3) API is called.
4016
4017For audio-only recording, you can call [prepare()](#prepare9-3) again for re-recording. For video-only recording or audio and video recording, you can call [prepare()](#prepare9-3) and [getInputSurface()](#getinputsurface9-1) again for re-recording.
4018
4019**Atomic service API**: This API can be used in atomic services since API version 12.
4020
4021**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4022
4023**Return value**
4024
4025| Type          | Description                                 |
4026| -------------- | ------------------------------------- |
4027| Promise\<void> | Promise that returns no value.|
4028
4029**Error codes**
4030
4031For details about the error codes, see [Media Error Codes](errorcode-media.md).
4032
4033| ID| Error Message                              |
4034| -------- | -------------------------------------- |
4035| 5400102  | Operate not permit. Return by promise. |
4036| 5400103  | IO error. Return by promise.           |
4037| 5400105  | Service died. Return by promise.       |
4038
4039**Example**
4040
4041```ts
4042import { BusinessError } from '@kit.BasicServicesKit';
4043
4044avRecorder.stop().then(() => {
4045  console.info('Succeeded in stopping AVRecorder');
4046}).catch((err: BusinessError) => {
4047  console.error('Failed to stop AVRecorder and catch error is ' + err.message);
4048});
4049```
4050
4051### reset<sup>9+</sup>
4052
4053reset(callback: AsyncCallback\<void>): void
4054
4055Resets audio and video recording. This API uses an asynchronous callback to return the result.
4056
4057For audio-only recording, you can call [prepare()](#prepare9-2) again for re-recording. For video-only recording or audio and video recording, you can call [prepare()](#prepare9-2) and [getInputSurface()](#getinputsurface9) again for re-recording.
4058
4059**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4060
4061**Parameters**
4062
4063| Name  | Type                | Mandatory| Description                          |
4064| -------- | -------------------- | ---- | ------------------------------ |
4065| callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
4066
4067**Error codes**
4068
4069For details about the error codes, see [Media Error Codes](errorcode-media.md).
4070
4071| ID| Error Message                         |
4072| -------- | --------------------------------- |
4073| 5400103  | IO error. Return by callback.     |
4074| 5400105  | Service died. Return by callback. |
4075
4076**Example**
4077
4078```ts
4079import { BusinessError } from '@kit.BasicServicesKit';
4080
4081avRecorder.reset((err: BusinessError) => {
4082  if (err) {
4083    console.error('Failed to reset AVRecorder and error is ' + err.message);
4084  } else {
4085    console.info('Succeeded in resetting AVRecorder');
4086  }
4087});
4088```
4089
4090### reset<sup>9+</sup>
4091
4092reset(): Promise\<void>
4093
4094Resets audio and video recording. This API uses a promise to return the result.
4095
4096For audio-only recording, you can call [prepare()](#prepare9-3) again for re-recording. For video-only recording or audio and video recording, you can call [prepare()](#prepare9-3) and [getInputSurface()](#getinputsurface9-1) again for re-recording.
4097
4098**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4099
4100**Return value**
4101
4102| Type          | Description                                   |
4103| -------------- | --------------------------------------- |
4104| Promise\<void> | Promise that returns no value.|
4105
4106**Error codes**
4107
4108For details about the error codes, see [Media Error Codes](errorcode-media.md).
4109
4110| ID| Error Message                        |
4111| -------- | -------------------------------- |
4112| 5400103  | IO error. Return by promise.     |
4113| 5400105  | Service died. Return by promise. |
4114
4115**Example**
4116
4117```ts
4118import { BusinessError } from '@kit.BasicServicesKit';
4119
4120avRecorder.reset().then(() => {
4121  console.info('Succeeded in resetting AVRecorder');
4122}).catch((err: BusinessError) => {
4123  console.error('Failed to reset and catch error is ' + err.message);
4124});
4125```
4126
4127### release<sup>9+</sup>
4128
4129release(callback: AsyncCallback\<void>): void
4130
4131Releases the audio and video recording resources. This API uses an asynchronous callback to return the result.
4132
4133After the resources are released, you can no longer perform any operation on the **AVRecorder** instance.
4134
4135**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4136
4137**Parameters**
4138
4139| Name  | Type                | Mandatory| Description                              |
4140| -------- | -------------------- | ---- | ---------------------------------- |
4141| callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
4142
4143**Error codes**
4144
4145For details about the error codes, see [Media Error Codes](errorcode-media.md).
4146
4147| ID| Error Message                         |
4148| -------- | --------------------------------- |
4149| 5400105  | Service died. Return by callback. |
4150
4151**Example**
4152
4153```ts
4154import { BusinessError } from '@kit.BasicServicesKit';
4155
4156avRecorder.release((err: BusinessError) => {
4157  if (err) {
4158    console.error('Failed to release AVRecorder and error is ' + err.message);
4159  } else {
4160    console.info('Succeeded in releasing AVRecorder');
4161  }
4162});
4163```
4164
4165### release<sup>9+</sup>
4166
4167release(): Promise\<void>
4168
4169Releases the audio and video recording resources. This API uses a promise to return the result.
4170
4171After the resources are released, you can no longer perform any operation on the **AVRecorder** instance.
4172
4173**Atomic service API**: This API can be used in atomic services since API version 12.
4174
4175**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4176
4177**Return value**
4178
4179| Type          | Description                                       |
4180| -------------- | ------------------------------------------- |
4181| Promise\<void> | Promise that returns no value.|
4182
4183**Error codes**
4184
4185For details about the error codes, see [Media Error Codes](errorcode-media.md).
4186
4187| ID| Error Message                         |
4188| -------- | --------------------------------- |
4189| 5400105  | Service died. Return by callback. |
4190
4191**Example**
4192
4193```ts
4194import { BusinessError } from '@kit.BasicServicesKit';
4195
4196avRecorder.release().then(() => {
4197  console.info('Succeeded in releasing AVRecorder');
4198}).catch((err: BusinessError) => {
4199  console.error('Failed to release AVRecorder and catch error is ' + err.message);
4200});
4201```
4202
4203### getCurrentAudioCapturerInfo<sup>11+</sup>
4204
4205getCurrentAudioCapturerInfo(callback: AsyncCallback\<audio.AudioCapturerChangeInfo>): void
4206
4207Obtains the information about the current audio capturer. This API uses an asynchronous callback to return the result.
4208
4209This API can be called only after the **prepare()** API is called. If this API is called after **stop()** is successfully called, an error is reported.
4210
4211**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4212
4213**Parameters**
4214
4215| Name  | Type                                                        | Mandatory| Description                                |
4216| -------- | ------------------------------------------------------------ | ---- | ------------------------------------ |
4217| callback | AsyncCallback\<[audio.AudioCapturerChangeInfo](../apis-audio-kit/js-apis-audio.md#audiocapturerchangeinfo9)> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the **audio.AudioCapturerChangeInfo** object obtained; otherwise, **err** is an error object.|
4218
4219**Error codes**
4220
4221For details about the error codes, see [Media Error Codes](errorcode-media.md).
4222
4223| ID| Error Message                                  |
4224| -------- | ------------------------------------------ |
4225| 5400102  | Operation not allowed. |
4226| 5400103  | I/O error.             |
4227| 5400105  | Service died. Return by callback.          |
4228
4229**Example**
4230
4231```ts
4232import { audio } from '@kit.AudioKit';
4233
4234let currentCapturerInfo: audio.AudioCapturerChangeInfo;
4235
4236avRecorder.getCurrentAudioCapturerInfo((err: BusinessError, capturerInfo: audio.AudioCapturerChangeInfo) => {
4237  if (err) {
4238    console.error('Failed to get CurrentAudioCapturerInfo and error is ' + err.message);
4239  } else {
4240    console.info('Succeeded in getting CurrentAudioCapturerInfo');
4241    currentCapturerInfo = capturerInfo;
4242  }
4243});
4244```
4245
4246### getCurrentAudioCapturerInfo<sup>11+</sup>
4247
4248getCurrentAudioCapturerInfo(): Promise\<audio.AudioCapturerChangeInfo>
4249
4250Obtains the information about the current audio capturer. This API uses a promise to return the result.
4251
4252This API can be called only after the **prepare()** API is called. If this API is called after **stop()** is successfully called, an error is reported.
4253
4254**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4255
4256**Return value**
4257
4258| Type                                                        | Description                                             |
4259| ------------------------------------------------------------ | ------------------------------------------------- |
4260| Promise\<[audio.AudioCapturerChangeInfo](../apis-audio-kit/js-apis-audio.md#audiocapturerchangeinfo9)> | Promise used to return the audio capturer information.|
4261
4262**Error codes**
4263
4264For details about the error codes, see [Media Error Codes](errorcode-media.md).
4265
4266| ID| Error Message                        |
4267| -------- | -------------------------------- |
4268| 5400102  | Operation not allowed.           |
4269| 5400103  | I/O error.                       |
4270| 5400105  | Service died. Return by promise. |
4271
4272**Example**
4273
4274```ts
4275import { audio } from '@kit.AudioKit';
4276
4277let currentCapturerInfo: audio.AudioCapturerChangeInfo;
4278
4279avRecorder.getCurrentAudioCapturerInfo().then((capturerInfo: audio.AudioCapturerChangeInfo) => {
4280  console.info('Succeeded in getting CurrentAudioCapturerInfo');
4281  currentCapturerInfo = capturerInfo;
4282}).catch((err: BusinessError) => {
4283  console.error('Failed to get CurrentAudioCapturerInfo and catch error is ' + err.message);
4284});
4285```
4286
4287### getAudioCapturerMaxAmplitude<sup>11+</sup>
4288
4289getAudioCapturerMaxAmplitude(callback: AsyncCallback\<number>): void
4290
4291Obtains the maximum amplitude of the current audio capturer. This API uses an asynchronous callback to return the result.
4292
4293This API can be called only after the **prepare()** API is called. If this API is called after **stop()** is successfully called, an error is reported.
4294
4295The return value is the maximum amplitude within the duration from the time the maximum amplitude is obtained last time to the current time. For example, if you have obtained the maximum amplitude at 1s and you call this API again at 2s, then the return value is the maximum amplitude within the duration from 1s to 2s.
4296
4297**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4298
4299**Parameters**
4300
4301| Name  | Type                  | Mandatory| Description                                |
4302| -------- | ---------------------- | ---- | ------------------------------------ |
4303| callback | AsyncCallback\<number> | Yes  |  Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the maximum amplitude obtained; otherwise, **err** is an error object.|
4304
4305**Error codes**
4306
4307For details about the error codes, see [Media Error Codes](errorcode-media.md).
4308
4309| ID| Error Message                                  |
4310| -------- | ------------------------------------------ |
4311| 5400102  | Operation not allowed. |
4312| 5400105  | Service died. Return by callback.          |
4313
4314**Example**
4315
4316```ts
4317let maxAmplitude: number;
4318
4319avRecorder.getAudioCapturerMaxAmplitude((err: BusinessError, amplitude: number) => {
4320  if (err) {
4321    console.error('Failed to get AudioCapturerMaxAmplitude and error is ' + err.message);
4322  } else {
4323    console.info('Succeeded in getting AudioCapturerMaxAmplitude');
4324    maxAmplitude = amplitude;
4325  }
4326});
4327```
4328
4329### getAudioCapturerMaxAmplitude<sup>11+</sup>
4330
4331getAudioCapturerMaxAmplitude(): Promise\<number>
4332
4333Obtains the maximum amplitude of the current audio capturer. This API uses a promise to return the result.
4334
4335This API can be called only after the **prepare()** API is called. If this API is called after **stop()** is successfully called, an error is reported.
4336
4337The return value is the maximum amplitude within the duration from the time the maximum amplitude is obtained last time to the current time. For example, if you have obtained the maximum amplitude at 1s and you call this API again at 2s, then the return value is the maximum amplitude within the duration from 1s to 2s.
4338
4339**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4340
4341**Return value**
4342
4343| Type            | Description                                             |
4344| ---------------- | ------------------------------------------------- |
4345| Promise\<number>| Promise used to return the maximum amplitude obtained.|
4346
4347**Error codes**
4348
4349For details about the error codes, see [Media Error Codes](errorcode-media.md).
4350
4351| ID| Error Message                        |
4352| -------- | -------------------------------- |
4353| 5400102  | Operation not allowed.           |
4354| 5400105  | Service died. Return by promise. |
4355
4356**Example**
4357
4358```ts
4359let maxAmplitude: number;
4360
4361avRecorder.getAudioCapturerMaxAmplitude().then((amplitude: number) => {
4362  console.info('Succeeded in getting AudioCapturerMaxAmplitude');
4363  maxAmplitude = amplitude;
4364}).catch((err: BusinessError) => {
4365  console.error('Failed to get AudioCapturerMaxAmplitude and catch error is ' + err.message);
4366});
4367```
4368
4369### getAvailableEncoder<sup>11+</sup>
4370
4371getAvailableEncoder(callback: AsyncCallback\<Array\<EncoderInfo>>): void
4372
4373Obtains available encoders. This API uses an asynchronous callback to return the result.
4374
4375**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4376
4377**Parameters**
4378
4379| Name  | Type                                                 | Mandatory| Description                                |
4380| -------- | ----------------------------------------------------- | ---- | ------------------------------------ |
4381| callback | AsyncCallback\<Array\<[EncoderInfo](#encoderinfo11)>> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the available encoders obtained; otherwise, **err** is an error object.|
4382
4383**Error codes**
4384
4385For details about the error codes, see [Media Error Codes](errorcode-media.md).
4386
4387| ID| Error Message                                  |
4388| -------- | ------------------------------------------ |
4389| 5400102  | Operation not allowed. |
4390| 5400105  | Service died. Return by callback.          |
4391
4392**Example**
4393
4394```ts
4395let encoderInfo: media.EncoderInfo;
4396
4397avRecorder.getAvailableEncoder((err: BusinessError, info: media.EncoderInfo[]) => {
4398  if (err) {
4399    console.error('Failed to get AvailableEncoder and error is ' + err.message);
4400  } else {
4401    console.info('Succeeded in getting AvailableEncoder');
4402    encoderInfo = info[0];
4403  }
4404});
4405```
4406
4407### getAvailableEncoder<sup>11+</sup>
4408
4409getAvailableEncoder(): Promise\<Array\<EncoderInfo>>
4410
4411Obtains available encoders. This API uses an asynchronous callback to return the result.
4412
4413**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4414
4415**Return value**
4416
4417| Type                                           | Description                                           |
4418| ----------------------------------------------- | ----------------------------------------------- |
4419| Promise\<Array\<[EncoderInfo](#encoderinfo11)>> | Promise used to return the information about the available encoders.|
4420
4421**Error codes**
4422
4423For details about the error codes, see [Media Error Codes](errorcode-media.md).
4424
4425| ID| Error Message                        |
4426| -------- | -------------------------------- |
4427| 5400102  | Operation not allowed.           |
4428| 5400105  | Service died. Return by promise. |
4429
4430**Example**
4431
4432```ts
4433let encoderInfo: media.EncoderInfo;
4434
4435avRecorder.getAvailableEncoder().then((info: media.EncoderInfo[]) => {
4436  console.info('Succeeded in getting AvailableEncoder');
4437  encoderInfo = info[0];
4438}).catch((err: BusinessError) => {
4439  console.error('Failed to get AvailableEncoder and catch error is ' + err.message);
4440});
4441```
4442
4443### getAVRecorderConfig<sup>11+</sup>
4444
4445getAVRecorderConfig(callback: AsyncCallback\<AVRecorderConfig>): void
4446
4447Obtains the real-time configuration of this AVRecorder. This API uses an asynchronous callback to return the result.
4448
4449This API can be called only after [prepare()](#prepare9-2) is called.
4450
4451**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4452
4453**Parameters**
4454
4455| Name  | Type                  | Mandatory| Description                       |
4456| -------- | ---------------------- | ---- | --------------------------- |
4457| callback | AsyncCallback\<[AVRecorderConfig](#avrecorderconfig9)> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the real-time configuration obtained; otherwise, **err** is an error object.|
4458
4459**Error codes**
4460
4461For details about the error codes, see [Media Error Codes](errorcode-media.md).
4462
4463| ID| Error Message                                  |
4464| -------- | ------------------------------------------ |
4465| 5400102  | Operate not permit. Return by callback. |
4466| 5400103  | IO error. Return by callback.             |
4467| 5400105  | Service died. Return by callback.          |
4468
4469**Example**
4470
4471```ts
4472import { BusinessError } from '@kit.BasicServicesKit';
4473
4474let avConfig: media.AVRecorderConfig;
4475
4476avRecorder.getAVRecorderConfig((err: BusinessError, config: media.AVRecorderConfig) => {
4477  if (err) {
4478    console.error('Failed to get avConfig and error is ' + err.message);
4479  } else {
4480    console.info('Succeeded in getting AVRecorderConfig');
4481    avConfig = config;
4482  }
4483});
4484```
4485
4486### getAVRecorderConfig<sup>11+</sup>
4487
4488getAVRecorderConfig(): Promise\<AVRecorderConfig>;
4489
4490Obtains the real-time configuration of this AVRecorder. This API uses a promise to return the result.
4491
4492This API can be called only after [prepare()](#prepare9-3) is called.
4493
4494**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4495
4496**Return value**
4497
4498| Type            | Description                            |
4499| ---------------- | -------------------------------- |
4500| Promise\<[AVRecorderConfig](#avrecorderconfig9)> | Promise used to return the real-time configuration.|
4501
4502**Error codes**
4503
4504For details about the error codes, see [Media Error Codes](errorcode-media.md).
4505
4506| ID| Error Message                                 |
4507| -------- | ----------------------------------------- |
4508| 5400102  | Operate not permit. Return by promise. |
4509| 5400103  | IO error. Return by promise.             |
4510| 5400105  | Service died. Return by promise.          |
4511
4512**Example**
4513
4514```ts
4515import { BusinessError } from '@kit.BasicServicesKit';
4516
4517let avConfig: media.AVRecorderConfig;
4518
4519avRecorder.getAVRecorderConfig().then((config: media.AVRecorderConfig) => {
4520  console.info('Succeeded in getting AVRecorderConfig');
4521  avConfig = config;
4522}).catch((err: BusinessError) => {
4523  console.error('Failed to get AVRecorderConfig and catch error is ' + err.message);
4524});
4525```
4526
4527### on('stateChange')<sup>9+</sup>
4528
4529on(type: 'stateChange', callback: OnAVRecorderStateChangeHandler): void
4530
4531Subscribes to AVRecorder state changes. An application can subscribe to only one AVRecorder state change event. When the application initiates multiple subscriptions to this event, the last subscription is applied.
4532
4533**Atomic service API**: This API can be used in atomic services since API version 12.
4534
4535**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4536
4537**Parameters**
4538
4539| Name  | Type    | Mandatory| Description                                                        |
4540| -------- | -------- | ---- | ------------------------------------------------------------ |
4541| type     | string   | Yes  | Event type, which is **'stateChange'** in this case. This event can be triggered by both user operations and the system.|
4542| callback | [OnAVRecorderStateChangeHandler](#onavrecorderstatechangehandler12) | Yes  | Callback invoked when the event is triggered.|
4543
4544**Error codes**
4545
4546For details about the error codes, see [Media Error Codes](errorcode-media.md).
4547
4548| ID| Error Message                         |
4549| -------- | --------------------------------- |
4550| 5400103  | IO error. Return by callback.     |
4551| 5400105  | Service died. Return by callback. |
4552
4553**Example**
4554
4555```ts
4556avRecorder.on('stateChange', async (state: media.AVRecorderState, reason: media.StateChangeReason) => {
4557  console.info('case state has changed, new state is :' + state + ',and new reason is : ' + reason);
4558});
4559```
4560
4561### off('stateChange')<sup>9+</sup>
4562
4563off(type: 'stateChange', callback?: OnAVRecorderStateChangeHandler): void
4564
4565Unsubscribes from AVRecorder state changes.
4566
4567**Atomic service API**: This API can be used in atomic services since API version 12.
4568
4569**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4570
4571**Parameters**
4572
4573| Name| Type  | Mandatory| Description                                                        |
4574| ------ | ------ | ---- | ------------------------------------------------------------ |
4575| type   | string | Yes  | Event type, which is **'stateChange'** in this case. This event can be triggered by both user operations and the system.|
4576| callback | [OnAVRecorderStateChangeHandler](#onavrecorderstatechangehandler12) | No  | Callback invoked when the event is triggered.<br>This parameter is supported since API version 12.|
4577
4578**Example**
4579
4580```ts
4581avRecorder.off('stateChange');
4582```
4583
4584### on('error')<sup>9+</sup>
4585
4586on(type: 'error', callback: ErrorCallback): void
4587
4588Subscribes to AVRecorder errors. This event is used only for error prompt and does not require the user to stop recording control. If the [AVRecorderState](#avrecorderstate9) is also switched to error, call [reset()](#reset9-2) or [release()][release()](#release9-2) to exit the recording.
4589
4590An application can subscribe to only one AVRecorder error event. When the application initiates multiple subscriptions to this event, the last subscription is applied.
4591
4592**Atomic service API**: This API can be used in atomic services since API version 12.
4593
4594**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4595
4596**Parameters**
4597
4598| Name  | Type         | Mandatory| Description                                                        |
4599| -------- | ------------- | ---- | ------------------------------------------------------------ |
4600| type     | string        | Yes  | Event type, which is **'error'** in this case.<br>This event is triggered when an error occurs during recording.|
4601| callback | [ErrorCallback](../apis-basic-services-kit/js-apis-base.md#errorcallback) | Yes  | Callback invoked when the event is triggered.                                      |
4602
4603**Error codes**
4604
4605For details about the error codes, see [Media Error Codes](errorcode-media.md).
4606
4607| ID| Error Message                                  |
4608| -------- | ------------------------------------------ |
4609| 201      | Permission denied.     |
4610| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. |
4611| 801      | Capability not supported. |
4612| 5400101  | No memory.             |
4613| 5400102  | Operation not allowed. |
4614| 5400103  | I/O error.             |
4615| 5400104  | Time out.              |
4616| 5400105  | Service died.          |
4617| 5400106  | Unsupported format.    |
4618| 5400107  | Audio interrupted.     |
4619
4620**Example**
4621
4622```ts
4623import { BusinessError } from '@kit.BasicServicesKit';
4624
4625avRecorder.on('error', (err: BusinessError) => {
4626  console.info('case avRecorder.on(error) called, errMessage is ' + err.message);
4627});
4628```
4629
4630### off('error')<sup>9+</sup>
4631
4632off(type: 'error', callback?: ErrorCallback): void
4633
4634Unsubscribes from AVRecorder errors. After the unsubscription, your application can no longer receive AVRecorder errors.
4635
4636**Atomic service API**: This API can be used in atomic services since API version 12.
4637
4638**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4639
4640**Parameters**
4641
4642| Name| Type  | Mandatory| Description                                                        |
4643| ------ | ------ | ---- | ------------------------------------------------------------ |
4644| type   | string | Yes  | Event type, which is **'error'** in this case.<br>This event is triggered when an error occurs during recording.|
4645| callback | [ErrorCallback](../apis-basic-services-kit/js-apis-base.md#errorcallback) | No  | Callback invoked when the event is triggered.<br>This parameter is supported since API version 12.                  |
4646
4647**Example**
4648
4649```ts
4650avRecorder.off('error');
4651```
4652
4653### on('audioCapturerChange')<sup>11+</sup>
4654
4655on(type: 'audioCapturerChange', callback: Callback<audio.AudioCapturerChangeInfo>): void
4656
4657Subscribes to audio capturer configuration changes. Any configuration change triggers the callback that returns the entire configuration information.
4658
4659When the application initiates multiple subscriptions to this event, the last subscription is applied.
4660
4661**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4662
4663**Parameters**
4664
4665| Name  | Type    | Mandatory| Description                                                        |
4666| -------- | -------- | ---- | ------------------------------------------------------------ |
4667| type     | string   | Yes  |Event type, which is **'audioCapturerChange'** in this case.|
4668| callback | Callback<[audio.AudioCapturerChangeInfo](../apis-audio-kit/js-apis-audio.md#audiocapturerchangeinfo9)> | Yes| Callback used to return the entire configuration information about the audio capturer.|
4669
4670**Error codes**
4671
4672| ID| Error Message                                  |
4673| -------- | ------------------------------------------ |
4674| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed.      |
4675
4676**Example**
4677
4678```ts
4679import { audio } from '@kit.AudioKit'
4680
4681let capturerChangeInfo: audio.AudioCapturerChangeInfo;
4682
4683avRecorder.on('audioCapturerChange',  (audioCapturerChangeInfo: audio.AudioCapturerChangeInfo) => {
4684  console.info('audioCapturerChange called');
4685  capturerChangeInfo = audioCapturerChangeInfo;
4686});
4687```
4688
4689### off('audioCapturerChange')<sup>11+</sup>
4690
4691off(type: 'audioCapturerChange', callback?: Callback<audio.AudioCapturerChangeInfo>): void
4692
4693Subscribes to audio capturer configuration changes.
4694
4695**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4696
4697**Parameters**
4698
4699| Name| Type  | Mandatory| Description                                                        |
4700| ------ | ------ | ---- | ------------------------------------------------------------ |
4701| type   | string | Yes  | Event type, which is **'audioCapturerChange'** in this case.|
4702| callback | Callback<[audio.AudioCapturerChangeInfo](../apis-audio-kit/js-apis-audio.md#audiocapturerchangeinfo9)> | No| Callback used to return the entire configuration information about the audio capturer.<br>This parameter is supported since API version 12.|
4703
4704**Example**
4705
4706```ts
4707avRecorder.off('audioCapturerChange');
4708```
4709
4710### on('photoAssetAvailable')<sup>12+</sup>
4711
4712on(type: 'photoAssetAvailable', callback: Callback\<photoAccessHelper.PhotoAsset>): void
4713
4714Subscribes to media asset callback events. When [FileGenerationMode](#filegenerationmode12) is used during media file creation, the [PhotoAsset](../apis-media-library-kit/js-apis-photoAccessHelper.md#photoasset) object is called back to the application after the [stop](#stop9-2) operation is complete.
4715
4716When the application initiates multiple subscriptions to this event, the last subscription is applied.
4717
4718**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4719
4720**Parameters**
4721
4722| Name  | Type    | Mandatory| Description                                                        |
4723| -------- | -------- | ---- | ------------------------------------------------------------ |
4724| type     | string   | Yes  |Event type, which is **'photoAssetAvailable'** in this case. The event is triggered when a photo asset is available.|
4725| callback | Callback<[photoAccessHelper.PhotoAsset](../apis-media-library-kit/js-apis-photoAccessHelper.md#photoasset)> | Yes| Callback used to return the **PhotoAsset** object corresponding to the resource file created by the system.|
4726
4727**Error codes**
4728
4729| ID| Error Message                                  |
4730| -------- | ------------------------------------------ |
4731| 5400103  | IO error. Return by callback.             |
4732| 5400105  | Service died. Return by callback.          |
4733
4734**Example**
4735
4736<!--code_no_check-->
4737```ts
4738import { photoAccessHelper } from '@kit.MediaLibraryKit';
4739import { common } from '@kit.AbilityKit'
4740let photoAsset: photoAccessHelper.PhotoAsset;
4741let context = getContext(this) as common.UIAbilityContext
4742
4743// Example: Process the photoAsset callback and save the video.
4744async function saveVideo(asset: photoAccessHelper.PhotoAsset) {
4745  console.info("saveVideo called");
4746  try {
4747    let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);
4748    let assetChangeRequest: photoAccessHelper.MediaAssetChangeRequest = new photoAccessHelper.MediaAssetChangeRequest(asset);
4749    assetChangeRequest.saveCameraPhoto();
4750    await phAccessHelper.applyChanges(assetChangeRequest);
4751    console.info('apply saveVideo successfully');
4752  } catch (err) {
4753    console.error(`apply saveVideo failed with error: ${err.code}, ${err.message}`);
4754  }
4755}
4756// Subscribe to the photoAsset event.
4757avRecorder.on('photoAssetAvailable',  (asset: photoAccessHelper.PhotoAsset) => {
4758  console.info('photoAssetAvailable called');
4759  if (asset != undefined) {
4760    photoAsset = asset;
4761    // Process the photoAsset callback.
4762    // Example: this.saveVideo (asset);
4763  } else {
4764    console.error('photoAsset is undefined');
4765  }
4766});
4767```
4768
4769### off('photoAssetAvailable')<sup>12+</sup>
4770
4771off(type: 'photoAssetAvailable', callback?: Callback<photoAccessHelper.PhotoAsset>): void
4772
4773Unsubscribes from media asset callback events.
4774
4775**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4776
4777**Parameters**
4778
4779| Name| Type  | Mandatory| Description                                                        |
4780| ------ | ------ | ---- | ------------------------------------------------------------ |
4781| type   | string | Yes  | Event type, which is **'photoAssetAvailable'** in this case.|
4782| callback | Callback<[photoAccessHelper.PhotoAsset](../apis-media-library-kit/js-apis-photoAccessHelper.md#photoasset)> | No| Callback used to return the **PhotoAsset** object corresponding to the resource file created by the system.|
4783
4784**Example**
4785
4786```ts
4787avRecorder.off('photoAssetAvailable');
4788```
4789
4790## AVRecorderState<sup>9+</sup>
4791
4792type AVRecorderState = 'idle' | 'prepared' | 'started' | 'paused' | 'stopped' | 'released' | 'error'
4793
4794Enumerates the AVRecorder states. You can obtain the state through the **state** attribute.
4795
4796**Atomic service API**: This API can be used in atomic services since API version 12.
4797
4798**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4799
4800| Type    | Description                                                        |
4801| -------- | ------------------------------------------------------------ |
4802| 'idle'     | The AVRecorder enters this state after it is just created or the [AVRecorder.reset()](#reset9-2) API is called when the AVRecorder is in any state except released. In this state, you can call [AVRecorder.prepare()](#prepare9-2) to set recording parameters.  |
4803| 'prepared' | The AVRecorder enters this state when the parameters are set. In this state, you can call [AVRecorder.start()](#start9) to start recording.|
4804| 'started'  | The AVRecorder enters this state when the recording starts. In this state, you can call [AVRecorder.pause()](#pause9-2) to pause recording or call [AVRecorder.stop()](#stop9-2) to stop recording.|
4805| 'paused'   | The AVRecorder enters this state when the recording is paused. In this state, you can call [AVRecorder.resume()](#resume9) to continue recording or call [AVRecorder.stop()](#stop9-2) to stop recording.|
4806| 'stopped'  | The AVRecorder enters this state when the recording stops. In this state, you can call [AVRecorder.prepare()](#prepare9-2) to set recording parameters so that the AVRecorder enters the prepared state again.|
4807| 'released' | The AVRecorder enters this state when the recording resources are released. In this state, no operation can be performed. In any other state, you can call [AVRecorder.release()](#release9-2) to enter the released state.|
4808| 'error'    | The AVRecorder enters this state when an irreversible error occurs in the **AVRecorder** instance. In this state, the [AVRecorder.on('error') event](#onerror9-1) is reported, with the detailed error cause. In the error state, you must call [AVRecorder.reset()](#reset9-2) to reset the **AVRecorder** instance or call [AVRecorder.release()](#release9-2) to release the resources.|
4809
4810## OnAVRecorderStateChangeHandler<sup>12+</sup>
4811
4812type OnAVRecorderStateChangeHandler = (state: AVRecorderState, reason: StateChangeReason) => void
4813
4814Describes the callback invoked for the AVRecorder state change event.
4815
4816**Atomic service API**: This API can be used in atomic services since API version 12.
4817
4818**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4819
4820| Name  | Type  | Mandatory| Description                                                        |
4821| ------ | ------ | ------ | ------------------------------------------------------------ |
4822| state  | [AVRecorderState](#avrecorderstate9) | Mandatory| AVRecorder state.    |
4823| reason | [StateChangeReason](#statechangereason9) | Mandatory| Reason for the state change.|
4824
4825## AVRecorderConfig<sup>9+</sup>
4826
4827Describes the audio and video recording parameters.
4828
4829The **audioSourceType** and **videoSourceType** parameters are used to distinguish audio-only recording, video-only recording, and audio and video recording. For audio-only recording, set only **audioSourceType**. For video-only recording, set only **videoSourceType**. For audio and video recording, set both **audioSourceType** and **videoSourceType**.
4830
4831**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4832
4833| Name           | Type                                    | Mandatory| Description                                                        |
4834| --------------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
4835| audioSourceType | [AudioSourceType](#audiosourcetype9)     | No  | Type of the audio source to record. This parameter is mandatory for audio recording.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
4836| videoSourceType | [VideoSourceType](#videosourcetype9)     | No  | Type of the video source to record. This parameter is mandatory for video recording.                  |
4837| profile         | [AVRecorderProfile](#avrecorderprofile9) | Yes  | Recording profile. This parameter is mandatory.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
4838| url             | string                                   | Yes  | Recording output URL: fd://xx (fd number).<br>![img](figures/en-us_image_url.png)<br>This parameter is mandatory.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
4839|fileGenerationMode<sup>12+</sup> | [FileGenerationMode](#filegenerationmode12)  | No  |  Mode for creating the file, which is used together with [on('photoAssetAvailable')](#onphotoassetavailable12).|
4840| rotation<sup>(deprecated)</sup>        | number                                   | No  | Rotation angle of the recorded video. The value can be 0 (default), 90, 180, or 270 for MP4 videos.<br>This API is supported since API version 6 and deprecated since API version 12. You are advised to use **[AVMetadata](#avmetadata11).videoOrientation** instead. If both parameters are set, **[AVMetadata](#avmetadata11).videoOrientation** is used.    |
4841| location<sup>(deprecated)</sup>        | [Location](#location)                    | No  | Geographical location of the recorded video. By default, the geographical location information is not recorded.<br>This API is supported since API version 6 and deprecated since API version 12. You are advised to use **[AVMetadata](#avmetadata11).location** instead. If both parameters are set, **[AVMetadata](#avmetadata11).location** is used.|
4842| metadata<sup>12+</sup>        | [AVMetadata](#avmetadata11)              | No  | Metadata. For details, see [AVMetadata](#avmetadata11).                 |
4843| maxDuration<sup>18+</sup>        | number             | No  | Maximum recording duration, in seconds. The value range is [1, 2^31-1]. If an invalid value is provided, it is reset to the maximum allowed duration. Once the recording reaches the specified duration, it stops automatically and notifies via the **stateChange** callback that the recording has stopped: [AVRecorderState](#avrecorderstate9) = 'stopped', [StateChangeReason](#statechangereason9) = BACKGROUND.|
4844
4845## AVRecorderProfile<sup>9+</sup>
4846
4847Describes the audio and video recording profile.
4848
4849> **NOTE**
4850> The following table lists the audio parameters. For details about each parameter, see the field description below.
4851>
4852> | Encoding Format | Container Format | Sampling Rate | Bit Rate | Audio Channel Count |
4853> |----|----|----|----|----|
4854> |AUDIO_AAC|MP4,M4A|[8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000, 64000, 88200, 96000]|[32000-500000]|[1-8]|
4855> |AUDIO_MP3|MP3|[8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000]|<br>- When the sampling rate is lower than 16000, the bit rate range is [8000 - 64000].<br>- When the sampling rate ranges from 16000 to 32000, the bit rate range is [8000 - 160000].<br>- When the sampling rate is greater than 32000, the bit rate range is [32000 - 320000].|[1-2]|
4856> |AUDIO_G711MU|WAV|[8000]|[64000]|[1]|
4857> |AUDIO_AMR_NB<sup>18+</sup> |AMR|[8000]|[4750, 5150, 5900, 6700, 7400, 7950, 10200, 12200]|[1]|
4858> |AUDIO_AMR_WB<sup>18+</sup> |AMR|[16000]|[6600, 8850, 12650, 14250, 15850, 18250, 19850, 23050, 23850]|[1]|
4859
4860**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4861
4862| Name            | Type                                        | Mandatory| Description                                                        |
4863| ---------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ |
4864| audioBitrate     | number                                       | No  | Audio encoding bit rate. This parameter is mandatory for audio recording.<br>Supported bit rate ranges:<br>- Range [32000 - 500000] for the AAC encoding format.<br>- Range [64000] for the G.711 μ-law encoding format.<br>- Range [8000, 16000, 32000, 40000, 48000, 56000, 64000, 80000, 96000, 112000, 128000, 160000, 192000, 224000, 256000, 320000] for the MP3 encoding format.<br>When the MP3 encoding format is used, the mapping between the sampling rate and bit rate is as follows:<br>- When the sampling rate is lower than 16 kHZ, the bit rate range is [8000 - 64000].<br>- When the sampling rate ranges from 16 kHz to 32 kHz, the bit rate range is [8000 - 160000].<br>- When the sampling rate is greater than 32 kHz, the bit rate range is [32000 - 320000].<br>- Range [4750, 5150, 5900, 6700, 7400, 7950, 10200, 12200] for the AMR-NB encoding format.<br>- Range [6600, 8850, 12650, 14250, 15850, 18250, 19850, 23050, 23850] for the AMR-WB encoding format.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
4865| audioChannels    | number                                       | No  | Number of audio channels. This parameter is mandatory for audio recording.<br>- Range [1 - 8] for the AAC encoding format.<br>- Range [1] for the G.711 μ-law encoding format.<br>- Range [1 - 2] for the MP3 encoding format.<br>- Range [1] for the AMR-NB and AMR-WB encoding formats.<br>**Atomic service API**: This API can be used in atomic services since API version 12.      |
4866| audioCodec       | [CodecMimeType](#codecmimetype8)             | No  | Audio encoding format. This parameter is mandatory for audio recording. Currently, AUDIO_AAC, AUDIO_MP3, AUDIO_G711MU, AUDIO_AMR_NB, and AUDIO_AMR_WB are supported.<br>**Atomic service API**: This API can be used in atomic services since API version 12.    |
4867| audioSampleRate  | number                                       | No  | Audio sampling rate. This parameter is mandatory for audio recording.<br>Supported sampling rate ranges:<br>- Range [8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000, 64000, 88200, 96000] for the AAC encoding format.<br>- Range [8000] for the G.711 μ-law encoding format.<br>- Range [8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000] for the MP3 encoding format.<br>- Range [8000] for the AMR-NB encoding format.<br>- Range [16000] for the AMR-WB encoding format.<br>Variable bit rate. The bit rate is for reference only.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
4868| fileFormat       | [ContainerFormatType](#containerformattype8) | Yes  | Container format of a file. This parameter is mandatory. Currently, the MP4, M4A, MP3, WAV, and AMR container formats are supported. The AUDIO_MP3 encoding format cannot be used in the MP4 container format.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
4869| videoBitrate     | number                                       | No  | Video encoding bit rate. This parameter is mandatory for video recording. The value range is [10000 - 100000000]. |
4870| videoCodec       | [CodecMimeType](#codecmimetype8)             | No  | Video encoding format. This parameter is mandatory for video recording. Currently, VIDEO_AVC is supported.|
4871| videoFrameWidth  | number                                       | No  | Width of a video frame. This parameter is mandatory for video recording. The value range is [176 - 4096].        |
4872| videoFrameHeight | number                                       | No  | Height of a video frame. This parameter is mandatory for video recording. The value range is [144 - 4096].        |
4873| videoFrameRate   | number                                       | No  | Video frame rate. This parameter is mandatory for video recording. The value range is [1 - 60].            |
4874| isHdr<sup>11+</sup>            | boolean                        | No  | HDR encoding. This parameter is optional for video recording. The default value is **false**, and there is no requirement on the encoding format. When **isHdr** is set to **true**, the encoding format must be **video/hevc**.|
4875| enableTemporalScale<sup>12+</sup>            | boolean                        | No  | Whether temporal layered encoding is supported. This parameter is optional for video recording. The default value is **false**. If this parameter is set to **true**, some frames in the video output streams can be skipped without being encoded.|
4876| enableStableQualityMode<sup>18+</sup>            | boolean                        | No  | Whether to enable stable quality mode for video recording. This parameter is optional for video recording. The default value is **false**. If this parameter is set to **true**, the system will use a video encoding strategy designed to maintain stable quality.|
4877
4878## AudioSourceType<sup>9+</sup>
4879
4880Enumerates the audio source types for video recording.
4881
4882**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4883
4884| Name                     | Value  | Description                  |
4885| ------------------------- | ---- | ---------------------- |
4886| AUDIO_SOURCE_TYPE_DEFAULT | 0    | Default audio input source.|
4887| AUDIO_SOURCE_TYPE_MIC     | 1    | Microphone audio input source.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
4888| AUDIO_SOURCE_TYPE_VOICE_RECOGNITION<sup>12+</sup> | 2    | Audio source in speech recognition scenarios.|
4889| AUDIO_SOURCE_TYPE_VOICE_COMMUNICATION<sup>12+</sup>     | 7    | Voice communication source.|
4890| AUDIO_SOURCE_TYPE_VOICE_MESSAGE<sup>12+</sup> | 10    | Voice message source.|
4891| AUDIO_SOURCE_TYPE_CAMCORDER<sup>12+</sup>     | 13    | Audio source in camera recording scenarios.|
4892
4893## VideoSourceType<sup>9+</sup>
4894
4895Enumerates the video source types for video recording.
4896
4897**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4898
4899| Name                         | Value  | Description                           |
4900| ----------------------------- | ---- | ------------------------------- |
4901| VIDEO_SOURCE_TYPE_SURFACE_YUV | 0    | The input surface carries raw data.|
4902| VIDEO_SOURCE_TYPE_SURFACE_ES  | 1    | The input surface carries ES data. |
4903
4904## ContainerFormatType<sup>8+</sup>
4905
4906Enumerates the container format types (CFTs).
4907
4908**System capability**: SystemCapability.Multimedia.Media.Core
4909
4910| Name       | Value   | Description                 |
4911| ----------- | ----- | --------------------- |
4912| CFT_MPEG_4  | 'mp4' | Video container format MP4.|
4913| CFT_MPEG_4A | 'm4a' | Audio container format M4A.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
4914| CFT_MP3<sup>12+</sup>  | 'mp3' | Audio container format MP3.|
4915| CFT_WAV<sup>12+</sup>  | 'wav' | Audio container format WAV.|
4916| CFT_AMR<sup>18+</sup>  | 'amr' | Audio container format AMR.|
4917
4918## Location
4919
4920Describes the geographical location of the recorded video.
4921
4922**System capability**: SystemCapability.Multimedia.Media.Core
4923
4924| Name     | Type  | Mandatory| Description            |
4925| --------- | ------ | ---- | ---------------- |
4926| latitude  | number | Yes  | Latitude of the geographical location. The value range is [-90, 90].|
4927| longitude | number | Yes  | Longitude of the geographical location. The value range is [-180, 180].|
4928
4929## EncoderInfo<sup>11+</sup>
4930
4931Describes the information about an encoder.
4932
4933**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4934
4935| Name      | Type                            | Readable| Writable| Description                                                        |
4936| ---------- | -------------------------------- | ---- | ---- | ------------------------------------------------------------ |
4937| mimeType   | [CodecMimeType](#codecmimetype8) | Yes  | No  | MIME type of the encoder.                                          |
4938| type       | string                           | Yes  | No  | Encoder type. The value **audio** means an audio encoder, and **video** means a video encoder.        |
4939| bitRate    | [Range](#range11)                | Yes  | No  | Bit rate range of the encoder, with the minimum and maximum bit rates specified.                          |
4940| frameRate  | [Range](#range11)                | Yes  | No  | Video frame rate range, with the minimum and maximum frame rates specified. This parameter is available only for video encoders.         |
4941| width      | [Range](#range11)                | Yes  | No  | Video frame width range, with the minimum and maximum widths specified. This parameter is available only for video encoders.      |
4942| height     | [Range](#range11)                | Yes  | No  | Video frame height range, with the minimum and maximum heights specified. This parameter is available only for video encoders.      |
4943| channels   | [Range](#range11)                | Yes  | No  | Number of audio channels for the audio capturer, with the minimum and maximum numbers of audio channels specified. This parameter is available only for audio encoders.  |
4944| sampleRate | Array\<number>                    | Yes  | No  | Audio sampling rate, including all available audio sampling rates. The value depends on the encoder type, and this parameter is available only for audio encoders.|
4945
4946## Range<sup>11+</sup>
4947
4948Describes a range.
4949
4950**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4951
4952| Name| Type  | Readable| Writable| Description        |
4953| ---- | ------ | ---- | ---- | ------------ |
4954| min  | number | Yes  | No  | Minimum value.|
4955| max  | number | Yes  | No  | Maximum value.|
4956
4957## FileGenerationMode<sup>12+</sup>
4958
4959Enumerates the modes for creating media files.
4960
4961**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4962
4963| Name                         | Value  | Description                           |
4964| ----------------------------- | ---- | ------------------------------- |
4965| APP_CREATE  | 0    | The application creates a media file in the sandbox.|
4966| AUTO_CREATE_CAMERA_SCENE  | 1    | The system creates a media file. Currently, this mode takes effect only in camera recording scenarios. The URL set by the application is ignored.|
4967
4968## AVTranscoder<sup>12+</sup>
4969
4970A transcoding management class that provides APIs to transcode videos. Before calling any API in **AVTranscoder**, you must use **createAVTranscoder()** to create an **AVTranscoder** instance.
4971
4972For details about the AVTranscoder demo, see [Using AVTranscoder for Transcoding](../../media/media/using-avtranscoder-for-transcodering.md).
4973
4974### Attributes
4975
4976**System capability**: SystemCapability.Multimedia.Media.AVTranscoder
4977
4978| Name   | Type                                | Read-Only| Optional| Description              |
4979| ------- | ------------------------------------ | ---- | ---- | ------------------ |
4980| fdSrc<sup>12+</sup>                                  | [AVFileDescriptor](#avfiledescriptor9)                       |  No | No  | Source media file descriptor, which specifies the data source.<br>**Example:**<br>There is a media file that stores continuous assets, the address offset is 0, and the byte length is 100. Its file descriptor is **AVFileDescriptor { fd = resourceHandle; offset = 0; length = 100; }**.<br>**NOTE**<br> - After the resource handle (FD) is transferred to an **AVTranscoder** instance, do not use the resource handle to perform other read and write operations, including but not limited to transferring this handle to other **AVPlayer**, **AVMetadataExtractor**, **AVImageGenerator**, or **AVTranscoder** instance. Competition occurs when multiple AVTranscoders use the same resource handle to read and write files at the same time, resulting in errors in obtaining data.|
4981| fdDst<sup>12+</sup>                               | number                 |  No | No  | Destination media file descriptor, which specifies the data source. After creating an **AVTranscoder** instance, you must set both **fdSrc** and **fdDst**.<br>**NOTE**<br> - After the resource handle (FD) is transferred to an **AVTranscoder** instance, do not use the resource handle to perform other read and write operations, including but not limited to transferring this handle to other **AVPlayer**, **AVMetadataExtractor**, **AVImageGenerator**, or **AVTranscoder** instance. Competition occurs when multiple AVTranscoders use the same resource handle to read and write files at the same time, resulting in errors in obtaining data.|
4982
4983### prepare<sup>12+</sup>
4984
4985prepare(config: AVTranscoderConfig): Promise\<void>
4986
4987Sets video transcoding parameters. This API uses a promise to return the result.
4988
4989**System capability**: SystemCapability.Multimedia.Media.AVTranscoder
4990
4991**Parameters**
4992
4993| Name| Type                                  | Mandatory| Description                      |
4994| ------ | -------------------------------------- | ---- | -------------------------- |
4995| config | [AVTranscoderConfig](#avtranscoderconfig12) | Yes  | Video transcoding parameters to set.|
4996
4997**Return value**
4998
4999| Type          | Description                                      |
5000| -------------- | ------------------------------------------ |
5001| Promise\<void> | Promise that returns no value.|
5002
5003**Error codes**
5004
5005For details about the error codes, see [Media Error Codes](errorcode-media.md).
5006
5007| ID| Error Message                              |
5008| -------- | -------------------------------------- |
5009| 401  | The parameter check failed. Return by promise. |
5010| 5400102  | Operation not allowed. Return by promise. |
5011| 5400105  | Service died. Return by promise.       |
5012| 5400106  | Unsupported format. Returned by promise.  |
5013
5014**Example**
5015
5016```ts
5017import { BusinessError } from '@kit.BasicServicesKit';
5018
5019// Configure the parameters based on those supported by the hardware device.
5020let avTranscoderConfig: media.AVTranscoderConfig = {
5021  audioBitrate : 200000,
5022  audioCodec : media.CodecMimeType.AUDIO_AAC,
5023  fileFormat : media.ContainerFormatType.CFT_MPEG_4,
5024  videoBitrate : 3000000,
5025  videoCodec : media.CodecMimeType.VIDEO_AVC,
5026  videoFrameWidth : 1280,
5027  videoFrameHeight : 720,
5028}
5029
5030avTranscoder.prepare(avTranscoderConfig).then(() => {
5031  console.info('prepare success');
5032}).catch((err: BusinessError) => {
5033  console.error('prepare failed and catch error is ' + err.message);
5034});
5035```
5036
5037### start<sup>12+</sup>
5038
5039start(): Promise\<void>
5040
5041Starts transcoding. This API uses a promise to return the result.
5042
5043This API can be called only after the [prepare()](#prepare12) API is called.
5044
5045**System capability**: SystemCapability.Multimedia.Media.AVTranscoder
5046
5047**Return value**
5048
5049| Type          | Description                                 |
5050| -------------- | ------------------------------------- |
5051| Promise\<void> | Promise that returns no value.|
5052
5053**Error codes**
5054
5055For details about the error codes, see [Media Error Codes](errorcode-media.md).
5056
5057| ID| Error Message                              |
5058| -------- | -------------------------------------- |
5059| 5400102  | Operation not allowed. Return by promise. |
5060| 5400103  | IO error. Return by promise.           |
5061| 5400105  | Service died. Return by promise.       |
5062
5063**Example**
5064
5065```ts
5066import { BusinessError } from '@kit.BasicServicesKit';
5067
5068avTranscoder.start().then(() => {
5069  console.info('start AVTranscoder success');
5070}).catch((err: BusinessError) => {
5071  console.error('start AVTranscoder failed and catch error is ' + err.message);
5072});
5073```
5074
5075### pause<sup>12+</sup>
5076
5077pause(): Promise\<void>
5078
5079Pauses transcoding. This API uses a promise to return the result.
5080
5081This API can be called only after the [start()](#start12) API is called. You can call [resume()](#resume12) to resume transcoding.
5082
5083**System capability**: SystemCapability.Multimedia.Media.AVTranscoder
5084
5085**Return value**
5086
5087| Type          | Description                                 |
5088| -------------- | ------------------------------------- |
5089| Promise\<void> | Promise that returns no value.|
5090
5091**Error codes**
5092
5093For details about the error codes, see [Media Error Codes](errorcode-media.md).
5094
5095| ID| Error Message                              |
5096| -------- | -------------------------------------- |
5097| 5400102  | Operation not allowed. Return by promise. |
5098| 5400103  | IO error. Return by promise.           |
5099| 5400105  | Service died. Return by promise.       |
5100
5101**Example**
5102
5103```ts
5104import { BusinessError } from '@kit.BasicServicesKit';
5105
5106avTranscoder.pause().then(() => {
5107  console.info('pause AVTranscoder success');
5108}).catch((err: BusinessError) => {
5109  console.error('pause AVTranscoder failed and catch error is ' + err.message);
5110});
5111```
5112
5113### resume<sup>12+</sup>
5114
5115resume(): Promise\<void>
5116
5117Resumes transcoding. This API uses a promise to return the result.
5118
5119This API can be called only after the [pause()](#pause12) API is called.
5120
5121**System capability**: SystemCapability.Multimedia.Media.AVTranscoder
5122
5123**Return value**
5124
5125| Type          | Description                                 |
5126| -------------- | ------------------------------------- |
5127| Promise\<void> | Promise that returns no value.|
5128
5129**Error codes**
5130
5131For details about the error codes, see [Media Error Codes](errorcode-media.md).
5132
5133| ID| Error Message                              |
5134| -------- | -------------------------------------- |
5135| 5400102  | Operation not allowed. Return by promise. |
5136| 5400103  | IO error. Return by promise.           |
5137| 5400105  | Service died. Return by promise.       |
5138
5139**Example**
5140
5141```ts
5142import { BusinessError } from '@kit.BasicServicesKit';
5143
5144avTranscoder.resume().then(() => {
5145  console.info('resume AVTranscoder success');
5146}).catch((err: BusinessError) => {
5147  console.error('resume AVTranscoder failed and catch error is ' + err.message);
5148});
5149```
5150
5151### cancel<sup>12+</sup>
5152
5153cancel(): Promise\<void>
5154
5155Cancels transcoding. This API uses a promise to return the result.
5156
5157This API can be called only after the [prepare()](#prepare12), [start()](#start12), [pause()](#pause12), or [resume()](#resume12) API is called.
5158
5159**System capability**: SystemCapability.Multimedia.Media.AVTranscoder
5160
5161**Return value**
5162
5163| Type          | Description                                 |
5164| -------------- | ------------------------------------- |
5165| Promise\<void> | Promise that returns no value.|
5166
5167**Error codes**
5168
5169For details about the error codes, see [Media Error Codes](errorcode-media.md).
5170
5171| ID| Error Message                              |
5172| -------- | -------------------------------------- |
5173| 5400102  | Operation not allowed. Return by promise. |
5174| 5400103  | IO error. Return by promise.           |
5175| 5400105  | Service died. Return by promise.       |
5176
5177**Example**
5178
5179```ts
5180import { BusinessError } from '@kit.BasicServicesKit';
5181
5182avTranscoder.cancel().then(() => {
5183  console.info('cancel AVTranscoder success');
5184}).catch((err: BusinessError) => {
5185  console.error('cancel AVTranscoder failed and catch error is ' + err.message);
5186});
5187```
5188
5189### release<sup>12+</sup>
5190
5191release(): Promise\<void>
5192
5193Releases the video transcoding resources. This API uses a promise to return the result.
5194
5195After the resources are released, you can no longer perform any operation on the **AVTranscoder** instance.
5196
5197**System capability**: SystemCapability.Multimedia.Media.AVTranscoder
5198
5199**Return value**
5200
5201| Type          | Description                                       |
5202| -------------- | ------------------------------------------- |
5203| Promise\<void> | Promise that returns no value.|
5204
5205**Error codes**
5206
5207For details about the error codes, see [Media Error Codes](errorcode-media.md).
5208
5209| ID| Error Message                         |
5210| -------- | --------------------------------- |
5211| 5400102  | Operation not allowed. Return by promise. |
5212| 5400105  | Service died. Return by promise. |
5213
5214**Example**
5215
5216```ts
5217import { BusinessError } from '@kit.BasicServicesKit';
5218
5219avTranscoder.release().then(() => {
5220  console.info('release AVTranscoder success');
5221}).catch((err: BusinessError) => {
5222  console.error('release AVTranscoder failed and catch error is ' + err.message);
5223});
5224```
5225
5226### on('progressUpdate')<sup>12+</sup>
5227
5228on(type: 'progressUpdate', callback: Callback\<number>): void
5229
5230Subscribes to transcoding progress updates. An application can subscribe to only one transcoding progress update event. When the application initiates multiple subscriptions to this event, the last subscription is applied.
5231
5232**System capability**: SystemCapability.Multimedia.Media.AVTranscoder
5233
5234**Parameters**
5235
5236| Name  | Type    | Mandatory| Description                                                        |
5237| -------- | -------- | ---- | ------------------------------------------------------------ |
5238| type     | string   | Yes  | Event type, which is **'progressUpdate'** in this case. This event is triggered by the system during transcoding.|
5239| callback | [Callback\<number>](../apis-basic-services-kit/js-apis-base.md#callback) | Yes  | Callback invoked when the event is triggered. **progress** is a number that indicates the current transcoding progress.|
5240
5241**Example**
5242
5243```ts
5244avTranscoder.on('progressUpdate', (progress: number) => {
5245  console.info('avTranscoder progressUpdate = ' + progress);
5246});
5247```
5248
5249### off('progressUpdate')<sup>12+</sup>
5250
5251off(type:'progressUpdate', callback?: Callback\<number>): void
5252
5253Unsubscribes from transcoding progress updates.
5254
5255**System capability**: SystemCapability.Multimedia.Media.AVTranscoder
5256
5257**Parameters**
5258
5259| Name| Type  | Mandatory| Description                                                        |
5260| ------ | ------ | ---- | ------------------------------------------------------------ |
5261| type   | string | Yes  | Event type, which is **'progressUpdate'** in this case. This event can be triggered by both user operations and the system.|
5262| callback | [Callback\<number>](../apis-basic-services-kit/js-apis-base.md#callback) | No  | Called that has been registered to listen for progress updates. You are advised to use the default value because only the last registered callback is retained in the current callback mechanism.|
5263
5264**Example**
5265
5266```ts
5267avTranscoder.off('progressUpdate');
5268```
5269
5270### on('error')<sup>12+</sup>
5271
5272on(type: 'error', callback: ErrorCallback): void
5273
5274Subscribes to AVTranscoder errors. If this event is reported, call [release()](#release12) to exit the transcoding.
5275
5276An application can subscribe to only one AVTranscoder error event. When the application initiates multiple subscriptions to this event, the last subscription is applied.
5277
5278**System capability**: SystemCapability.Multimedia.Media.AVTranscoder
5279
5280**Parameters**
5281
5282| Name  | Type         | Mandatory| Description                                                        |
5283| -------- | ------------- | ---- | ------------------------------------------------------------ |
5284| type     | string        | Yes  | Event type, which is **'error'** in this case.<br>This event is triggered when an error occurs during recording.|
5285| callback | [ErrorCallback](../apis-basic-services-kit/js-apis-base.md#errorcallback) | Yes  | Callback invoked when the event is triggered.                                      |
5286
5287**Error codes**
5288
5289For details about the error codes, see [Media Error Codes](errorcode-media.md).
5290
5291| ID| Error Message                                  |
5292| -------- | ------------------------------------------ |
5293| 401      | The parameter check failed. |
5294| 801      | Capability not supported. |
5295| 5400101  | No memory.            |
5296| 5400102  | Operation not allowed. |
5297| 5400103  | I/O error.              |
5298| 5400104  | Time out.            |
5299| 5400105  | Service died.           |
5300| 5400106  | Unsupported format.      |
5301
5302**Example**
5303
5304```ts
5305import { BusinessError } from '@kit.BasicServicesKit';
5306
5307avTranscoder.on('error', (err: BusinessError) => {
5308  console.info('case avTranscoder.on(error) called, errMessage is ' + err.message);
5309});
5310```
5311
5312### off('error')<sup>12+</sup>
5313
5314off(type:'error', callback?: ErrorCallback): void
5315
5316Unsubscribes from AVTranscoder errors. After the unsubscription, your application can no longer receive AVTranscoder errors.
5317
5318**System capability**: SystemCapability.Multimedia.Media.AVTranscoder
5319
5320**Parameters**
5321
5322| Name| Type  | Mandatory| Description                                                        |
5323| ------ | ------ | ---- | ------------------------------------------------------------ |
5324| type   | string | Yes  | Event type, which is **'error'** in this case.<br>This event is triggered when an error occurs during transcoding.|
5325| callback | [ErrorCallback](../apis-basic-services-kit/js-apis-base.md#errorcallback) | No  | Callback that has been registered to listen for AVTranscoder errors.|
5326
5327**Example**
5328
5329```ts
5330avTranscoder.off('error');
5331```
5332
5333### on('complete')<sup>12+</sup>
5334
5335on(type: 'complete', callback: Callback\<void>): void
5336
5337Subscribes to the event indicating that transcoding is complete. An application can subscribe to only one transcoding completion event. When the application initiates multiple subscriptions to this event, the last subscription is applied.
5338
5339When this event is reported, the current transcoding operation is complete. You need to call [release()](#release12) to exit the transcoding.
5340
5341**System capability**: SystemCapability.Multimedia.Media.AVTranscoder
5342
5343**Parameters**
5344
5345| Name  | Type    | Mandatory| Description                                                        |
5346| -------- | -------- | ---- | ------------------------------------------------------------ |
5347| type     | string   | Yes  | Event type, which is **'complete'** in this case. This event is triggered by the system during transcoding.|
5348| callback | [Callback\<void>](../apis-basic-services-kit/js-apis-base.md#callback) | Yes  | Callback that has been registered to listen for transcoding completion events.|
5349
5350**Example**
5351
5352```ts
5353avTranscoder.on('complete', async () => {
5354  console.info('avTranscoder complete');
5355  // Listen for transcoding completion events.
5356  // Wait until avTranscoder.release() is complete and then forward, upload, or save the transcoded file.
5357  await avTranscoder.release();
5358  avTranscoder = undefined;
5359});
5360```
5361
5362### off('complete')<sup>12+</sup>
5363
5364off(type:'complete', callback?: Callback\<void>): void
5365
5366Unsubscribes from the event indicating that transcoding is complete.
5367
5368**System capability**: SystemCapability.Multimedia.Media.AVTranscoder
5369
5370**Parameters**
5371
5372| Name| Type  | Mandatory| Description                                                        |
5373| ------ | ------ | ---- | ------------------------------------------------------------ |
5374| type   | string | Yes  | Event type, which is **'complete'** in this case. This event can be triggered by both user operations and the system.|
5375| callback | [Callback\<void>](../apis-basic-services-kit/js-apis-base.md#callback) | No  | Callback that has been registered to listen for transcoding completion events.|
5376
5377**Example**
5378
5379```ts
5380avTranscoder.off('complete');
5381```
5382
5383## AVTranscoderConfig<sup>12+</sup>
5384
5385Describes the video transcoding parameters.
5386
5387**System capability**: SystemCapability.Multimedia.Media.AVTranscoder
5388
5389| Name           | Type                                   | Read-Only| Optional| Description                                                        |
5390| --------------- | ---------------------------------------- |---- | ---- | ------------------------------------------------------------ |
5391| audioBitrate | number     | No| Yes| Bit rate of the output audio, in bit/s. The value range is [1-500000]. The default value is 48 kbit/s. |
5392| audioCodec | [CodecMimeType](#codecmimetype8)     | No| Yes | Encoding format of the output audio. Currently, only AAC is supported. The default value is **AAC**.                  |
5393| fileFormat         | [ContainerFormatType](#containerformattype8) | No| No  | Container format of the output video file. Currently, only MP4 is supported.|
5394| videoBitrate         | number | No|  Yes | Bit rate of the output video, in bit/s. The default bit rate depends on the resolution of the output video. The default bit rate is 1 Mbit/s for the resolution in the range [240p, 480P], 2 Mbit/s for the range (480P,720P], 4 Mbit/s for the range (720P,1080P], and 8 Mbit/s for 1080p or higher.|
5395| videoCodec        | [CodecMimeType](#codecmimetype8) | No| Yes  | Encoding format of the output video. Currently, only AVC and HEVC are supported. If the source video is in HEVC format, the default value is **HEVC**. Otherwise, the default value is **AVC**.|
5396| videoFrameWidth        | number | No|  Yes  | Width of the output video frame, in px. The value range is [240 - 3840]. The default value is the width of the source video frame.|
5397| videoFrameHeight        | number | No|  Yes  | Height of the output video frame, in px. The value range is [240 - 2160]. The default value is the height of the source video frame.|
5398
5399
5400
5401## AVMetadataExtractor<sup>11+</sup>
5402
5403Provides APIs to obtain metadata from media resources. Before calling any API of **AVMetadataExtractor**, you must use [createAVMetadataExtractor()](#mediacreateavmetadataextractor11) to create an **AVMetadataExtractor** instance.
5404
5405For details about the demo for obtaining audio or video metadata, see [Obtaining Audio/Video Metadata](../../media/media/avmetadataextractor.md).
5406
5407### Attributes
5408
5409**System capability**: SystemCapability.Multimedia.Media.AVMetadataExtractor
5410
5411| Name                                               | Type                                                        | Readable| Writable| Description                                                        |
5412| --------------------------------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ |
5413| fdSrc<sup>11+</sup>                                  | [AVFileDescriptor](#avfiledescriptor9)                       | Yes  | Yes  | Media file descriptor, which specifies the data source. Before obtaining metadata, you must set the data source through either **fdSrc** or **dataSrc**.<br>**Example:**<br>There is a media file that stores continuous assets, the address offset is 0, and the byte length is 100. Its file descriptor is **AVFileDescriptor { fd = resourceHandle; offset = 0; length = 100; }**.<br>**NOTE**<br> - After the resource handle (FD) is transferred to an **AVMetadataExtractor** instance, do not use the resource handle to perform other read and write operations, including but not limited to transferring this handle to other **AVPlayer**, **AVMetadataExtractor**, **AVImageGenerator**, or **AVTranscoder** instance. Competition occurs when multiple AVMetadataExtractor use the same resource handle to read and write files at the same time, resulting in errors in obtaining data.|
5414| dataSrc<sup>11+</sup>                               | [AVDataSrcDescriptor](#avdatasrcdescriptor10)                | Yes  | Yes  | Streaming media resource descriptor, which specifies the data source. Before obtaining metadata, you must set the data source through either **fdSrc** or **dataSrc**.<br> When an application obtains a media file from the remote, you can set **dataSrc** to obtain the metadata before the application finishes the downloading.|
5415
5416### fetchMetadata<sup>11+</sup>
5417
5418fetchMetadata(callback: AsyncCallback\<AVMetadata>): void
5419
5420Obtains media metadata. This API uses an asynchronous callback to return the result.
5421
5422**System capability**: SystemCapability.Multimedia.Media.AVMetadataExtractor
5423
5424**Parameters**
5425
5426| Name  | Type                                        | Mandatory| Description                               |
5427| -------- | -------------------------------------------- | ---- | ----------------------------------- |
5428| callback | AsyncCallback\<[AVMetadata](#avmetadata11)>       | Yes  | Callback used to return the result, which is an **AVMetadata** instance.|
5429
5430**Error codes**
5431
5432For details about the error codes, see [Media Error Codes](errorcode-media.md).
5433
5434| ID| Error Message                                  |
5435| -------- | ------------------------------------------ |
5436| 5400102  | Operation not allowed. Returned by callback. |
5437| 5400106  | Unsupported format. Returned by callback.  |
5438
5439**Example**
5440
5441```ts
5442import { BusinessError } from '@kit.BasicServicesKit';
5443
5444avMetadataExtractor.fetchMetadata((error: BusinessError, metadata: media.AVMetadata) => {
5445  if (error) {
5446    console.error(`Failed to fetch Metadata, err = ${JSON.stringify(error)}`);
5447    return;
5448  }
5449  console.info(`Succeeded in fetching Metadata, genre: ${metadata.genre}`);
5450});
5451```
5452
5453### fetchMetadata<sup>11+</sup>
5454
5455fetchMetadata(): Promise\<AVMetadata>
5456
5457Obtains media metadata. This API uses a promise to return the result.
5458
5459**System capability**: SystemCapability.Multimedia.Media.AVMetadataExtractor
5460
5461**Return value**
5462
5463| Type          | Description                                    |
5464| -------------- | ---------------------------------------- |
5465| Promise\<[AVMetadata](#avmetadata11)>  | Promise used to return the result, which is an **AVMetadata** instance.|
5466
5467**Error codes**
5468
5469For details about the error codes, see [Media Error Codes](errorcode-media.md).
5470
5471| ID| Error Message                                 |
5472| -------- | ----------------------------------------- |
5473| 5400102  | Operation not allowed. Returned by promise. |
5474| 5400106  | Unsupported format. Returned by promise.  |
5475
5476**Example**
5477
5478```ts
5479import { BusinessError } from '@kit.BasicServicesKit';
5480
5481avMetadataExtractor.fetchMetadata().then((metadata: media.AVMetadata) => {
5482  console.info(`Succeeded in fetching Metadata, genre: ${metadata.genre}`)
5483}).catch((error: BusinessError) => {
5484  console.error(`Failed to fetch Metadata, error message:${error.message}`);
5485});
5486```
5487
5488### fetchAlbumCover<sup>11+</sup>
5489
5490fetchAlbumCover(callback: AsyncCallback\<image.PixelMap>): void
5491
5492Obtains the cover of the audio album. This API uses an asynchronous callback to return the result.
5493
5494**System capability**: SystemCapability.Multimedia.Media.AVMetadataExtractor
5495
5496**Parameters**
5497
5498| Name  | Type                                        | Mandatory| Description                               |
5499| -------- | -------------------------------------------- | ---- | ----------------------------------- |
5500| callback | AsyncCallback\<[image.PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)>    | Yes  | Callback used to return the album cover.|
5501
5502**Error codes**
5503
5504For details about the error codes, see [Media Error Codes](errorcode-media.md).
5505
5506| ID| Error Message                                  |
5507| -------- | ------------------------------------------ |
5508| 5400102  | Operation not allowed. Return by callback. |
5509| 5400106  | Unsupported format. Returned by callback.  |
5510
5511**Example**
5512
5513```ts
5514import { BusinessError } from '@kit.BasicServicesKit';
5515import { image } from '@kit.ImageKit';
5516
5517let pixel_map : image.PixelMap | undefined = undefined;
5518
5519avMetadataExtractor.fetchAlbumCover((error: BusinessError, pixelMap: image.PixelMap) => {
5520  if (error) {
5521    console.error(`Failed to fetch AlbumCover, error = ${JSON.stringify(error)}`);
5522    return;
5523  }
5524  pixel_map = pixelMap;
5525});
5526```
5527
5528### fetchAlbumCover<sup>11+</sup>
5529
5530fetchAlbumCover(): Promise\<image.PixelMap>
5531
5532Obtains the cover of the audio album. This API uses a promise to return the result.
5533
5534**System capability**: SystemCapability.Multimedia.Media.AVMetadataExtractor
5535
5536**Return value**
5537
5538| Type          | Description                                    |
5539| -------------- | ---------------------------------------- |
5540| Promise\<[image.PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)> |  Promise used to return the album cover.|
5541
5542**Error codes**
5543
5544For details about the error codes, see [Media Error Codes](errorcode-media.md).
5545
5546| ID| Error Message                                 |
5547| -------- | ----------------------------------------- |
5548| 5400102  | Operation not allowed. Returned by promise. |
5549| 5400106  | Unsupported format. Returned by promise.  |
5550
5551**Example**
5552
5553```ts
5554import { BusinessError } from '@kit.BasicServicesKit';
5555import { image } from '@kit.ImageKit';
5556
5557let pixel_map : image.PixelMap | undefined = undefined;
5558
5559avMetadataExtractor.fetchAlbumCover().then((pixelMap: image.PixelMap) => {
5560  pixel_map = pixelMap;
5561}).catch((error: BusinessError) => {
5562  console.error(`Failed to fetch AlbumCover, error message:${error.message}`);
5563});
5564```
5565
5566### release<sup>11+</sup>
5567
5568release(callback: AsyncCallback\<void>): void
5569
5570Releases this **AVMetadataExtractor** instance. This API uses an asynchronous callback to return the result.
5571
5572**System capability**: SystemCapability.Multimedia.Media.AVMetadataExtractor
5573
5574**Parameters**
5575
5576| Name  | Type                                        | Mandatory| Description                               |
5577| -------- | -------------------------------------------- | ---- | ----------------------------------- |
5578| callback | AsyncCallback\<void>                   | Yes  |Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
5579
5580**Error codes**
5581
5582For details about the error codes, see [Media Error Codes](errorcode-media.md).
5583
5584| ID| Error Message                                  |
5585| -------- | ------------------------------------------ |
5586| 5400102  | Operation not allowed. Returned by callback. |
5587
5588**Example**
5589
5590```ts
5591import { BusinessError } from '@kit.BasicServicesKit';
5592
5593avMetadataExtractor.release((error: BusinessError) => {
5594  if (error) {
5595    console.error(`Failed to release, err = ${JSON.stringify(error)}`);
5596    return;
5597  }
5598  console.info(`Succeeded in releasing.`);
5599});
5600```
5601
5602### release<sup>11+</sup>
5603
5604release(): Promise\<void>
5605
5606Releases this **AVMetadataExtractor** instance. This API uses a promise to return the result.
5607
5608**System capability**: SystemCapability.Multimedia.Media.AVMetadataExtractor
5609
5610**Return value**
5611
5612| Type          | Description                                    |
5613| -------------- | ---------------------------------------- |
5614| Promise\<void> | Promise that returns no value.|
5615
5616**Error codes**
5617
5618For details about the error codes, see [Media Error Codes](errorcode-media.md).
5619
5620| ID| Error Message                                 |
5621| -------- | ----------------------------------------- |
5622| 5400102  | Operation not allowed. Returned by promise. |
5623
5624**Example**
5625
5626```ts
5627import { BusinessError } from '@kit.BasicServicesKit';
5628
5629avMetadataExtractor.release().then(() => {
5630  console.info(`Succeeded in releasing.`);
5631}).catch((error: BusinessError) => {
5632  console.error(`Failed to release, error message:${error.message}`);
5633});
5634```
5635
5636## AVMetadata<sup>11+</sup>
5637
5638Defines the audio and video metadata. Parameters that are not declared as read-only in [AVRecorderConfig](#avrecorderconfig9) can be used as input parameters for recording of [AVRecorder](#avrecorder9).
5639
5640**System capability**: SystemCapability.Multimedia.Media.AVMetadataExtractor
5641
5642| Name  | Type  | Mandatory| Description                                                        |
5643| ------ | ------ | ---- | ------------------------------------------------------------ |
5644| album     | string | No  | Title of the album. This parameter is read-only in the current version.    |
5645| albumArtist | string | No  | Artist of the album. This parameter is read-only in the current version.|
5646| artist | string | No  | Artist of the media asset. This parameter is read-only in the current version.|
5647| author | string | No  | Author of the media asset. This parameter is read-only in the current version.|
5648| dateTime | string | No  | Time when the media asset is created. This parameter is read-only in the current version.|
5649| dateTimeFormat | string | No  | Time when the media asset is created. The value is in the YYYY-MM-DD HH:mm:ss format. This parameter is read-only in the current version.|
5650| composer | string | No  | Composer of the media asset. This parameter is read-only in the current version.|
5651| duration | string | No  | Duration of the media asset. This parameter is read-only in the current version.|
5652| genre | string | No  | Type or genre of the media asset.|
5653| hasAudio | string | No  | Whether the media asset contains audio. This parameter is read-only in the current version.|
5654| hasVideo | string | No  | Whether the media asset contains a video. This parameter is read-only in the current version.|
5655| mimeType | string | No  | MIME type of the media asset. This parameter is read-only in the current version.|
5656| trackCount | string | No  | Number of tracks of the media asset. This parameter is read-only in the current version.|
5657| sampleRate | string | No  | Audio sampling rate, in Hz. This parameter is read-only in the current version.|
5658| title | string | No  | Title of the media asset. This parameter is read-only in the current version. This parameter is read-only in the current version.|
5659| videoHeight | string | No  | Video height, in px. This parameter is read-only in the current version.|
5660| videoWidth | string | No  | Video width, in px. This parameter is read-only in the current version.|
5661| videoOrientation | string | No  | Video rotation direction, in degrees.|
5662| hdrType<sup>12+</sup> | [HdrType](#hdrtype12) | No  | HDR type of the media asset. This parameter is read-only in the current version.|
5663| location<sup>12+</sup> | [Location](#location) | No| Geographical location of the media asset.|
5664| customInfo<sup>12+</sup> | Record<string, string> | No| Custom key-value mappings obtained from **moov.meta.list**.|
5665
5666## HdrType<sup>12+</sup>
5667
5668Enumerates the HDR types.
5669
5670**System capability**: SystemCapability.Multimedia.Media.Core
5671
5672| Name                     | Value  | Description                  |
5673| ------------------------- | ---- | ---------------------- |
5674| AV_HDR_TYPE_NONE          | 0    | No HDR.|
5675| AV_HDR_TYPE_VIVID         | 1    | HDR VIVID.|
5676
5677## media.createAudioPlayer<sup>(deprecated)</sup>
5678
5679createAudioPlayer(): AudioPlayer
5680
5681Creates an **AudioPlayer** instance in synchronous mode.
5682
5683> **NOTE**
5684>
5685> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [createAVPlayer](#mediacreateavplayer9) instead.
5686
5687**System capability**: SystemCapability.Multimedia.Media.AudioPlayer
5688
5689**Return value**
5690
5691| Type                       | Description                                                        |
5692| --------------------------- | ------------------------------------------------------------ |
5693| [AudioPlayer](#audioplayerdeprecated) | If the operation is successful, an **AudioPlayer** instance is returned; otherwise, **null** is returned. After the instance is created, you can start, pause, or stop audio playback.|
5694
5695**Example**
5696
5697```ts
5698let audioPlayer: media.AudioPlayer = media.createAudioPlayer();
5699```
5700
5701## media.createVideoPlayer<sup>(deprecated)</sup>
5702
5703createVideoPlayer(callback: AsyncCallback\<VideoPlayer>): void
5704
5705Creates a **VideoPlayer** instance. This API uses an asynchronous callback to return the result.
5706
5707> **NOTE**
5708>
5709> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [createAVPlayer](#mediacreateavplayer9) instead.
5710
5711**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
5712
5713**Parameters**
5714
5715| Name  | Type                                      | Mandatory| Description                                                        |
5716| -------- | ------------------------------------------ | ---- | ------------------------------------------------------------ |
5717| callback | AsyncCallback<[VideoPlayer](#videoplayerdeprecated)> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the **VideoPlayer** instance created; otherwise, **err** is an error object.|
5718
5719**Example**
5720
5721```ts
5722import { BusinessError } from '@kit.BasicServicesKit';
5723
5724let videoPlayer: media.VideoPlayer;
5725media.createVideoPlayer((error: BusinessError, video: media.VideoPlayer) => {
5726  if (video != null) {
5727    videoPlayer = video;
5728    console.info('Succeeded in creating VideoPlayer');
5729  } else {
5730    console.error(`Failed to create VideoPlayer, error:${error}`);
5731  }
5732});
5733```
5734
5735## media.createVideoPlayer<sup>(deprecated)</sup>
5736
5737createVideoPlayer(): Promise\<VideoPlayer>
5738
5739Creates a **VideoPlayer** instance. This API uses a promise to return the result.
5740
5741> **NOTE**
5742>
5743> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [createAVPlayer](#mediacreateavplayer9-1) instead.
5744
5745**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
5746
5747**Return value**
5748
5749| Type                                | Description                                                        |
5750| ------------------------------------ | ------------------------------------------------------------ |
5751| Promise<[VideoPlayer](#videoplayerdeprecated)> | Promise used to return the result. If the operation is successful, a **VideoPlayer** instance is returned; otherwise, **null** is returned. The instance can be used to manage and play video.|
5752
5753**Example**
5754
5755```ts
5756import { BusinessError } from '@kit.BasicServicesKit';
5757
5758let videoPlayer: media.VideoPlayer;
5759media.createVideoPlayer().then((video: media.VideoPlayer) => {
5760  if (video != null) {
5761    videoPlayer = video;
5762    console.info('Succeeded in creating VideoPlayer');
5763  } else {
5764    console.error('Failed to create VideoPlayer');
5765  }
5766}).catch((error: BusinessError) => {
5767  console.error(`Failed to create VideoPlayer, error:${error}`);
5768});
5769```
5770
5771## media.createAudioRecorder<sup>(deprecated)</sup>
5772
5773createAudioRecorder(): AudioRecorder
5774
5775Creates an **AudioRecorder** instance to control audio recording.
5776Only one **AudioRecorder** instance can be created per device.
5777
5778> **NOTE**
5779>
5780> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [createAVRecorder](#mediacreateavrecorder9) instead.
5781
5782**System capability**: SystemCapability.Multimedia.Media.AudioRecorder
5783
5784**Return value**
5785
5786| Type                           | Description                                                        |
5787| ------------------------------- | ------------------------------------------------------------ |
5788| [AudioRecorder](#audiorecorderdeprecated) | If the operation is successful, an **AudioRecorder** instance is returned; otherwise, **null** is returned. The instance can be used to record audio.|
5789
5790**Example**
5791
5792```ts
5793let audioRecorder: media.AudioRecorder = media.createAudioRecorder();
5794```
5795
5796## MediaErrorCode<sup>(deprecated)</sup>
5797
5798Enumerates the media error codes.
5799
5800> **NOTE**
5801>
5802> This enum is supported since API version 8 and deprecated since API version 11. You are advised to use [Media Error Codes](#averrorcode9) instead.
5803
5804**System capability**: SystemCapability.Multimedia.Media.Core
5805
5806| Name                      | Value  | Description                                  |
5807| -------------------------- | ---- | -------------------------------------- |
5808| MSERR_OK                   | 0    | The operation is successful.                        |
5809| MSERR_NO_MEMORY            | 1    | Failed to allocate memory. The system may have no available memory.|
5810| MSERR_OPERATION_NOT_PERMIT | 2    | No permission to perform the operation.                |
5811| MSERR_INVALID_VAL          | 3    | Invalid input parameter.                    |
5812| MSERR_IO                   | 4    | An I/O error occurs.                      |
5813| MSERR_TIMEOUT              | 5    | The operation times out.                        |
5814| MSERR_UNKNOWN              | 6    | An unknown error occurs.                        |
5815| MSERR_SERVICE_DIED         | 7    | Invalid server.                      |
5816| MSERR_INVALID_STATE        | 8    | The operation is not allowed in the current state.  |
5817| MSERR_UNSUPPORTED          | 9    | The operation is not supported in the current version.      |
5818
5819## AudioPlayer<sup>(deprecated)</sup>
5820
5821> **NOTE**
5822>
5823> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayer](#avplayer9) instead.
5824
5825Provides APIs to manage and play audio. Before calling any API in **AudioPlayer**, you must use [createAudioPlayer()](#mediacreateaudioplayerdeprecated) to create an **AudioPlayer** instance.
5826
5827### Attributes<sup>(deprecated)</sup>
5828
5829**System capability**: SystemCapability.Multimedia.Media.AudioPlayer
5830
5831| Name                           | Type                                                  | Read-Only| Optional| Description                                                        |
5832| ------------------------------- | ------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ |
5833| src                             | string                                                 | No  | No  | Audio file URI. The mainstream audio formats (M4A, AAC, MP3, OGG, WAV, and AMR) are supported.<br>**Example of supported URLs**:<br>1. FD: fd://xx<br>![](figures/en-us_image_url.png)<br>2. HTTP: http\://xx<br>3. HTTPS: https\://xx<br>4. HLS: http\://xx or https\://xx<br>**Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.INTERNET|
5834| fdSrc<sup>9+</sup>              | [AVFileDescriptor](#avfiledescriptor9)                 | No  | No  | Description of the audio file. This attribute is required when audio assets of an application are continuously stored in a file.<br>**Example:**<br>Assume that a music file that stores continuous music assets consists of the following:<br>Music 1 (address offset: 0, byte length: 100)<br>Music 2 (address offset: 101; byte length: 50)<br>Music 3 (address offset: 151, byte length: 150)<br>1. To play music 1: AVFileDescriptor { fd = resource handle; offset = 0; length = 100; }<br>2. To play music 2: AVFileDescriptor { fd = resource handle; offset = 101; length = 50; }<br>3. To play music 3: AVFileDescriptor { fd = resource handle; offset = 151; length = 150; }<br>To play an independent music file, use **src=fd://xx**.<br>|
5835| loop                            | boolean                                                | No  | No | Whether to loop audio playback. The value **true** means to loop audio playback, and **false** means the opposite.                |
5836| audioInterruptMode<sup>9+</sup> | [audio.InterruptMode](../apis-audio-kit/js-apis-audio.md#interruptmode9) | Yes  | Yes  | Audio interruption mode.                                              |
5837| currentTime                     | number                                                 | Yes  | No  | Current audio playback position, in ms.                      |
5838| duration                        | number                                                 | Yes  | No  | Audio duration, in ms.                                |
5839| state                           | [AudioState](#audiostatedeprecated)                              | Yes  | No  | Audio playback state. This state cannot be used as the condition for triggering the call of **play()**, **pause()**, or **stop()**.|
5840
5841### play<sup>(deprecated)</sup>
5842
5843play(): void
5844
5845Starts to play an audio asset. This API can be called only after the **'dataLoad'** event is triggered.
5846
5847> **NOTE**
5848>
5849> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayer.play](#play9) instead.
5850
5851**System capability**: SystemCapability.Multimedia.Media.AudioPlayer
5852
5853**Example**
5854
5855```ts
5856audioPlayer.on('play', () => {    // Set the 'play' event callback.
5857  console.info('audio play called');
5858});
5859audioPlayer.play();
5860```
5861
5862### pause<sup>(deprecated)</sup>
5863
5864pause(): void
5865
5866Pauses audio playback.
5867
5868> **NOTE**
5869>
5870> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayer.pause](#pause9) instead.
5871
5872**System capability**: SystemCapability.Multimedia.Media.AudioPlayer
5873
5874**Example**
5875
5876```ts
5877audioPlayer.on('pause', () => {    // Set the 'pause' event callback.
5878  console.info('audio pause called');
5879});
5880audioPlayer.pause();
5881```
5882
5883### stop<sup>(deprecated)</sup>
5884
5885stop(): void
5886
5887Stops audio playback.
5888
5889> **NOTE**
5890>
5891> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayer.stop](#stop9) instead.
5892
5893**System capability**: SystemCapability.Multimedia.Media.AudioPlayer
5894
5895**Example**
5896
5897```ts
5898audioPlayer.on('stop', () => {    // Set the 'stop' event callback.
5899  console.info('audio stop called');
5900});
5901audioPlayer.stop();
5902```
5903
5904### reset<sup>(deprecated)</sup>
5905
5906reset(): void
5907
5908Resets the audio asset to be played.
5909
5910> **NOTE**
5911>
5912> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [AVPlayer.reset](#reset9) instead.
5913
5914**System capability**: SystemCapability.Multimedia.Media.AudioPlayer
5915
5916**Example**
5917
5918```ts
5919audioPlayer.on('reset', () => {    // Set the 'reset' event callback.
5920  console.info('audio reset called');
5921});
5922audioPlayer.reset();
5923```
5924
5925### seek<sup>(deprecated)</sup>
5926
5927seek(timeMs: number): void
5928
5929Seeks to the specified playback position.
5930
5931> **NOTE**
5932>
5933> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayer.seek](#seek9) instead.
5934
5935**System capability**: SystemCapability.Multimedia.Media.AudioPlayer
5936
5937**Parameters**
5938
5939| Name| Type  | Mandatory| Description                                                       |
5940| ------ | ------ | ---- | ----------------------------------------------------------- |
5941| timeMs | number | Yes  | Position to seek to, in ms. The value range is [0, duration].|
5942
5943**Example**
5944
5945```ts
5946audioPlayer.on('timeUpdate', (seekDoneTime: number) => {    // Set the 'timeUpdate' event callback.
5947  if (seekDoneTime == null) {
5948    console.error('Failed to seek');
5949    return;
5950  }
5951  console.info('Succeeded in seek. seekDoneTime: ' + seekDoneTime);
5952});
5953audioPlayer.seek(30000); // Seek to 30000 ms.
5954```
5955
5956### setVolume<sup>(deprecated)</sup>
5957
5958setVolume(vol: number): void
5959
5960Sets the volume.
5961
5962> **NOTE**
5963>
5964> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayer.setVolume](#setvolume9) instead.
5965
5966**System capability**: SystemCapability.Multimedia.Media.AudioPlayer
5967
5968**Parameters**
5969
5970| Name| Type  | Mandatory| Description                                                        |
5971| ------ | ------ | ---- | ------------------------------------------------------------ |
5972| vol    | number | Yes  | Relative volume. The value ranges from 0.00 to 1.00. The value **1.00** indicates the maximum volume (100%).|
5973
5974**Example**
5975
5976```ts
5977audioPlayer.on('volumeChange', () => {    // Set the 'volumeChange' event callback.
5978  console.info('audio volumeChange called');
5979});
5980audioPlayer.setVolume(1);    // Set the volume to 100%.
5981```
5982
5983### release<sup>(deprecated)</sup>
5984
5985release(): void
5986
5987Releases the audio playback resources.
5988
5989> **NOTE**
5990>
5991> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayer.release](#release9) instead.
5992
5993**System capability**: SystemCapability.Multimedia.Media.AudioPlayer
5994
5995**Example**
5996
5997```ts
5998audioPlayer.release();
5999audioPlayer = undefined;
6000```
6001
6002### getTrackDescription<sup>(deprecated)</sup>
6003
6004getTrackDescription(callback: AsyncCallback\<Array\<MediaDescription>>): void
6005
6006Obtains the audio track information. It can be called only after the **'dataLoad'** event is triggered. This API uses an asynchronous callback to return the result.
6007
6008> **NOTE**
6009>
6010> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.getTrackDescription](#gettrackdescription9) instead.
6011
6012**System capability**: SystemCapability.Multimedia.Media.AudioPlayer
6013
6014**Parameters**
6015
6016| Name  | Type                                                        | Mandatory| Description                                      |
6017| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------ |
6018| callback | AsyncCallback\<Array\<[MediaDescription](#mediadescription8)>> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the MediaDescription array obtained; otherwise, **err** is an error object.|
6019
6020**Example**
6021
6022```ts
6023import { BusinessError } from '@kit.BasicServicesKit';
6024
6025audioPlayer.getTrackDescription((error: BusinessError, arrList: Array<media.MediaDescription>) => {
6026  if (arrList != null) {
6027    console.info('Succeeded in getting TrackDescription');
6028  } else {
6029    console.error(`Failed to get TrackDescription, error:${error}`);
6030  }
6031});
6032```
6033
6034### getTrackDescription<sup>(deprecated)</sup>
6035
6036getTrackDescription(): Promise\<Array\<MediaDescription>>
6037
6038Obtains the audio track information. It can be called only after the **'dataLoad'** event is triggered. This API uses a promise to return the result.
6039
6040> **NOTE**
6041>
6042> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.getTrackDescription](#gettrackdescription9-1) instead.
6043
6044**System capability**: SystemCapability.Multimedia.Media.AudioPlayer
6045
6046**Return value**
6047
6048| Type                                                  | Description                                           |
6049| ------------------------------------------------------ | ----------------------------------------------- |
6050| Promise<Array<[MediaDescription](#mediadescription8)>> | Promise used to return a **MediaDescription** array, which records the audio track information.|
6051
6052**Example**
6053
6054```ts
6055import { BusinessError } from '@kit.BasicServicesKit';
6056
6057audioPlayer.getTrackDescription().then((arrList: Array<media.MediaDescription>) => {
6058  console.info('Succeeded in getting TrackDescription');
6059}).catch((error: BusinessError) => {
6060  console.error(`Failed to get TrackDescription, error:${error}`);
6061});
6062```
6063
6064### on('bufferingUpdate')<sup>(deprecated)</sup>
6065
6066on(type: 'bufferingUpdate', callback: (infoType: BufferingInfoType, value: number) => void): void
6067
6068Subscribes to the audio buffering update event. This API works only under online playback.
6069
6070> **NOTE**
6071>
6072> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.on('bufferingUpdate')](#onbufferingupdate9) instead.
6073
6074**System capability**: SystemCapability.Multimedia.Media.AudioPlayer
6075
6076**Parameters**
6077
6078| Name  | Type    | Mandatory| Description                                                        |
6079| -------- | -------- | ---- | ------------------------------------------------------------ |
6080| type     | string   | Yes  | Event type, which is **'bufferingUpdate'** in this case.       |
6081| callback | function | Yes  | Callback invoked when the event is triggered.<br>The value of [BufferingInfoType](#bufferinginfotype8) is fixed at **0**.|
6082
6083**Example**
6084
6085```ts
6086audioPlayer.on('bufferingUpdate', (infoType: media.BufferingInfoType, value: number) => {
6087  console.info('audio bufferingInfo type: ' + infoType);
6088  console.info('audio bufferingInfo value: ' + value);
6089});
6090```
6091
6092### on('play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange')<sup>(deprecated)</sup>
6093
6094on(type: 'play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange', callback: () => void): void
6095
6096Subscribes to the audio playback events.
6097
6098> **NOTE**
6099>
6100> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayer.on('stateChange')](#onstatechange9) instead.
6101
6102**System capability**: SystemCapability.Multimedia.Media.AudioPlayer
6103
6104**Parameters**
6105
6106| Name  | Type      | Mandatory| Description                                                        |
6107| -------- | ---------- | ---- | ------------------------------------------------------------ |
6108| type     | string     | Yes  | Event type. The following events are supported:<br>- 'play': triggered when the [play()](#playdeprecated) API is called and audio playback starts.<br>- 'pause': triggered when the [pause()](#pausedeprecated) API is called and audio playback is paused.<br>- 'stop': triggered when the [stop()](#stopdeprecated) API is called and audio playback stops.<br>- 'reset': triggered when the [reset()](#resetdeprecated) API is called and audio playback is reset.<br>- 'dataLoad': triggered when the audio data is loaded, that is, when the **src** attribute is configured.<br>- 'finish': triggered when the audio playback is finished.<br>- 'volumeChange': triggered when the [setVolume()](#setvolumedeprecated) API is called and the playback volume is changed.|
6109| callback | () => void | Yes  | Callback invoked when the event is triggered.                                          |
6110
6111**Example**
6112
6113```ts
6114import { fileIo as fs } from '@kit.CoreFileKit';
6115import { BusinessError } from '@kit.BasicServicesKit';
6116
6117let audioPlayer: media.AudioPlayer = media.createAudioPlayer();  // Create an AudioPlayer instance.
6118audioPlayer.on('dataLoad', () => {            // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
6119  console.info('audio set source called');
6120  audioPlayer.play();                       // Start the playback and trigger the 'play' event callback.
6121});
6122audioPlayer.on('play', () => {                // Set the 'play' event callback.
6123  console.info('audio play called');
6124  audioPlayer.seek(30000);                  // Call the seek() API and trigger the 'timeUpdate' event callback.
6125});
6126audioPlayer.on('pause', () => {               // Set the 'pause' event callback.
6127  console.info('audio pause called');
6128  audioPlayer.stop();                       // Stop the playback and trigger the 'stop' event callback.
6129});
6130audioPlayer.on('reset', () => {               // Set the 'reset' event callback.
6131  console.info('audio reset called');
6132  audioPlayer.release();                    // Release the AudioPlayer instance.
6133  audioPlayer = undefined;
6134});
6135audioPlayer.on('timeUpdate', (seekDoneTime: number) => {  // Set the 'timeUpdate' event callback.
6136  if (seekDoneTime == null) {
6137    console.error('Failed to seek');
6138    return;
6139  }
6140  console.info('Succeeded in seek, and seek time is ' + seekDoneTime);
6141  audioPlayer.setVolume(0.5);                // Set the volume to 50% and trigger the 'volumeChange' event callback.
6142});
6143audioPlayer.on('volumeChange', () => {         // Set the 'volumeChange' event callback.
6144  console.info('audio volumeChange called');
6145  audioPlayer.pause();                       // Pause the playback and trigger the 'pause' event callback.
6146});
6147audioPlayer.on('finish', () => {               // Set the 'finish' event callback.
6148  console.info('audio play finish');
6149  audioPlayer.stop();                        // Stop the playback and trigger the 'stop' event callback.
6150});
6151audioPlayer.on('error', (error: BusinessError) => {  // Set the 'error' event callback.
6152  console.error(`audio error called, error: ${error}`);
6153});
6154
6155// Set the FD (local playback) of the audio file selected by the user.
6156let fdPath = 'fd://';
6157// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/accounts/account_0/appdata" command.
6158let path = '/data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3';
6159fs.open(path).then((file) => {
6160  fdPath = fdPath + '' + file.fd;
6161  console.info('Succeeded in opening fd, fd is' + fdPath);
6162  audioPlayer.src = fdPath;  // Set the src attribute and trigger the 'dataLoad' event callback.
6163}, (err: BusinessError) => {
6164  console.error('Failed to open fd, err is' + err);
6165}).catch((err: BusinessError) => {
6166  console.error('Failed to open fd, err is' + err);
6167});
6168```
6169
6170### on('timeUpdate')<sup>(deprecated)</sup>
6171
6172on(type: 'timeUpdate', callback: Callback\<number>): void
6173
6174Subscribes to the **'timeUpdate'** event. This event is reported every second when the audio playback is in progress.
6175
6176> **NOTE**
6177>
6178> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayer.on('timeUpdate')](#ontimeupdate9) instead.
6179
6180**System capability**: SystemCapability.Multimedia.Media.AudioPlayer
6181
6182**Parameters**
6183
6184| Name  | Type             | Mandatory| Description                                                        |
6185| -------- | ----------------- | ---- | ------------------------------------------------------------ |
6186| type     | string            | Yes  | Event type, which is **'timeUpdate'** in this case.<br>The **'timeUpdate'** event is triggered when the audio playback starts after an audio playback timestamp update.|
6187| callback | Callback\<number> | Yes  | Callback invoked when the event is triggered. The input parameter is the updated timestamp.            |
6188
6189**Example**
6190
6191```ts
6192audioPlayer.on('timeUpdate', (newTime: number) => {    // Set the 'timeUpdate' event callback.
6193  if (newTime == null) {
6194    console.error('Failed to do timeUpadate');
6195    return;
6196  }
6197  console.info('Succeeded in doing timeUpadate. seekDoneTime: ' + newTime);
6198});
6199audioPlayer.play();    // The 'timeUpdate' event is triggered when the playback starts.
6200```
6201
6202### on('audioInterrupt')<sup>(deprecated)</sup>
6203
6204on(type: 'audioInterrupt', callback: (info: audio.InterruptEvent) => void): void
6205
6206Subscribes to the audio interruption event. For details, see [audio.InterruptEvent](../apis-audio-kit/js-apis-audio.md#interruptevent9).
6207
6208> **NOTE**
6209>
6210> This API is supported in API version 9 and deprecated since API version 9. You are advised to use [AVPlayer.on('audioInterrupt')](#onaudiointerrupt9) instead.
6211
6212**System capability**: SystemCapability.Multimedia.Media.AudioPlayer
6213
6214**Parameters**
6215
6216| Name  | Type                                                        | Mandatory| Description                                                    |
6217| -------- | ------------------------------------------------------------ | ---- | -------------------------------------------------------- |
6218| type     | string                                                       | Yes  | Event type, which is **'audioInterrupt'** in this case.|
6219| callback | function  | Yes  | Callback invoked when the event is triggered.                              |
6220
6221**Example**
6222
6223```ts
6224import { audio } from '@kit.AudioKit';
6225
6226audioPlayer.on('audioInterrupt', (info: audio.InterruptEvent) => {
6227  console.info('audioInterrupt called,and InterruptEvent info is:' + info)
6228})
6229```
6230
6231### on('error')<sup>(deprecated)</sup>
6232
6233on(type: 'error', callback: ErrorCallback): void
6234
6235Subscribes to audio playback error events. After an error event is reported, you must handle the event and exit the playback.
6236
6237> **NOTE**
6238>
6239> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayer.on('error')](#onerror9) instead.
6240
6241**System capability**: SystemCapability.Multimedia.Media.AudioPlayer
6242
6243**Parameters**
6244
6245| Name  | Type         | Mandatory| Description                                                        |
6246| -------- | ------------- | ---- | ------------------------------------------------------------ |
6247| type     | string        | Yes  | Event type, which is **'error'** in this case.<br>This event is triggered when an error occurs during audio playback.|
6248| callback | [ErrorCallback](../apis-basic-services-kit/js-apis-base.md#errorcallback) | Yes  | Callback invoked when the event is triggered.                                      |
6249
6250**Example**
6251
6252```ts
6253import { BusinessError } from '@kit.BasicServicesKit';
6254
6255audioPlayer.on('error', (error: BusinessError) => {  // Set the 'error' event callback.
6256  console.error(`audio error called, error: ${error}`);
6257});
6258audioPlayer.setVolume(3); // Set volume to an invalid value to trigger the 'error' event.
6259```
6260
6261## AudioState<sup>(deprecated)</sup>
6262
6263type AudioState = 'idle' | 'playing' | 'paused' | 'stopped' | 'error'
6264
6265Enumerates the audio playback states. You can obtain the state through the **state** attribute.
6266
6267> **NOTE**
6268>
6269> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayerState](#avplayerstate9) instead.
6270
6271**System capability**: SystemCapability.Multimedia.Media.AudioPlayer
6272
6273| Type   | Description                                          |
6274| ------- | ---------------------------------------------- |
6275| 'idle'    | No audio playback is in progress. The audio player is in this state after the **'dataload'** or **'reset'** event is triggered.|
6276| 'playing' | Audio playback is in progress. The audio player is in this state after the **'play'** event is triggered.          |
6277| 'paused'  | Audio playback is paused. The audio player is in this state after the **'pause'** event is triggered.         |
6278| 'stopped' | Audio playback is stopped. The audio player is in this state after the **'stop'** event is triggered.     |
6279| 'error'   | Audio playback is in the error state.                                    |
6280
6281## VideoPlayer<sup>(deprecated)</sup>
6282
6283> **NOTE**
6284>
6285> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer](#avplayer9) instead.
6286
6287Provides APIs to manage and play video. Before calling any API of **VideoPlayer**, you must use [createVideoPlayer()](#mediacreatevideoplayerdeprecated) to create a **VideoPlayer** instance.
6288
6289### Attributes
6290
6291**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
6292
6293| Name                           | Type                                                  | Read-Only| Optional| Description                                                        |
6294| ------------------------------- | ------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ |
6295| url<sup>8+</sup>                | string                                                 | No  | No  | Video URL. The video formats MP4, MPEG-TS, and MKV are supported.<br>**Example of supported URLs**:<br>1. FD: fd://xx<br>![](figures/en-us_image_url.png)<br>2. HTTP: http\://xx<br>3. HTTPS: https\://xx<br>4. HLS: http\://xx or https\://xx<br>5. File type: file\://xx<br>**NOTE**<br>WebM is no longer supported since API version 11.|
6296| fdSrc<sup>9+</sup>              | [AVFileDescriptor](#avfiledescriptor9)                 | No  | No  | Description of a video file. This attribute is required when video assets of an application are continuously stored in a file.<br>**Example:**<br>Assume that a music file that stores continuous music assets consists of the following:<br>Video 1 (address offset: 0, byte length: 100)<br>Video 2 (address offset: 101; byte length: 50)<br>Video 3 (address offset: 151, byte length: 150)<br>1. To play video 1: AVFileDescriptor { fd = resource handle; offset = 0; length = 100; }<br>2. To play video 2: AVFileDescriptor { fd = resource handle; offset = 101; length = 50; }<br>3. To play video 3: AVFileDescriptor { fd = resource handle; offset = 151; length = 150; }<br>To play an independent video file, use **src=fd://xx**.<br>|
6297| loop<sup>8+</sup>               | boolean                                                | No  | No  | Whether to loop video playback. The value **true** means to loop video playback, and **false** means the opposite.                |
6298| videoScaleType<sup>9+</sup>     | [VideoScaleType](#videoscaletype9)                     | No  | Yes  | Video scale type. The default value is **VIDEO_SCALE_TYPE_FIT**.                                              |
6299| audioInterruptMode<sup>9+</sup> | [audio.InterruptMode](../apis-audio-kit/js-apis-audio.md#interruptmode9) | No  | Yes  | Audio interruption mode.                                              |
6300| currentTime<sup>8+</sup>        | number                                                 | Yes  | No  | Current video playback position, in ms.                      |
6301| duration<sup>8+</sup>           | number                                                 | Yes  | No  | Video duration, in ms. The value **-1** indicates the live mode.            |
6302| state<sup>8+</sup>              | [VideoPlayState](#videoplaystatedeprecated)                    | Yes  | No  | Video playback state.                                            |
6303| width<sup>8+</sup>              | number                                                 | Yes  | No  | Video width, in px.                                  |
6304| height<sup>8+</sup>             | number                                                 | Yes  | No  | Video height, in px.                                  |
6305
6306### setDisplaySurface<sup>(deprecated)</sup>
6307
6308setDisplaySurface(surfaceId: string, callback: AsyncCallback\<void>): void
6309
6310Sets a surface ID. This API uses an asynchronous callback to return the result.
6311
6312*Note: **SetDisplaySurface** must be called between the URL setting and the calling of **prepare**. A surface must be set for video streams without audio. Otherwise, the calling of **prepare** fails.
6313
6314> **NOTE**
6315>
6316> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.surfaceId](#attributes) instead.
6317
6318**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
6319
6320**Parameters**
6321
6322| Name   | Type                | Mandatory| Description                     |
6323| --------- | -------------------- | ---- | ------------------------- |
6324| surfaceId | string               | Yes  | Surface ID.                 |
6325| callback  | AsyncCallback\<void> | Yes  | Callback used to return the result. If the setting is successful, **err** is **undefined**. Otherwise, **err** is an error object.|
6326
6327**Example**
6328
6329```ts
6330import { BusinessError } from '@kit.BasicServicesKit';
6331
6332let surfaceId: string = '';
6333videoPlayer.setDisplaySurface(surfaceId, (err: BusinessError) => {
6334  if (err) {
6335    console.error('Failed to set DisplaySurface!');
6336  } else {
6337    console.info('Succeeded in setting DisplaySurface!');
6338  }
6339});
6340```
6341
6342### setDisplaySurface<sup>(deprecated)</sup>
6343
6344setDisplaySurface(surfaceId: string): Promise\<void>
6345
6346Sets a surface ID. This API uses a promise to return the result.
6347
6348*Note: **SetDisplaySurface** must be called between the URL setting and the calling of **prepare**. A surface must be set for video streams without audio. Otherwise, the calling of **prepare** fails.
6349
6350> **NOTE**
6351>
6352> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.surfaceId](#attributes) instead.
6353
6354**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
6355
6356**Parameters**
6357
6358| Name   | Type  | Mandatory| Description     |
6359| --------- | ------ | ---- | --------- |
6360| surfaceId | string | Yes  | Surface ID. |
6361
6362**Return value**
6363
6364| Type          | Description                          |
6365| -------------- | ------------------------------ |
6366| Promise\<void> | Promise that returns no value.|
6367
6368**Example**
6369
6370```ts
6371import { BusinessError } from '@kit.BasicServicesKit';
6372
6373let surfaceId: string = '';
6374videoPlayer.setDisplaySurface(surfaceId).then(() => {
6375  console.info('Succeeded in setting DisplaySurface');
6376}).catch((error: BusinessError) => {
6377  console.error(`video catchCallback, error:${error}`);
6378});
6379```
6380
6381### prepare<sup>(deprecated)</sup>
6382
6383prepare(callback: AsyncCallback\<void>): void
6384
6385Prepares for video playback. This API uses an asynchronous callback to return the result.
6386
6387> **NOTE**
6388>
6389> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.prepare](#prepare9) instead.
6390
6391**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
6392
6393**Parameters**
6394
6395| Name  | Type                | Mandatory| Description                    |
6396| -------- | -------------------- | ---- | ------------------------ |
6397| callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
6398
6399**Example**
6400
6401```ts
6402import { BusinessError } from '@kit.BasicServicesKit';
6403
6404videoPlayer.prepare((err: BusinessError) => {
6405  if (err) {
6406    console.error('Failed to prepare!');
6407  } else {
6408    console.info('Succeeded in preparing!');
6409  }
6410});
6411```
6412
6413### prepare<sup>(deprecated)</sup>
6414
6415prepare(): Promise\<void>
6416
6417Prepares for video playback. This API uses a promise to return the result.
6418
6419> **NOTE**
6420>
6421> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.prepare](#prepare9-1) instead.
6422
6423**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
6424
6425**Return value**
6426
6427| Type          | Description                         |
6428| -------------- | ----------------------------- |
6429| Promise\<void> | Promise that returns no value.|
6430
6431**Example**
6432
6433```ts
6434import { BusinessError } from '@kit.BasicServicesKit';
6435
6436videoPlayer.prepare().then(() => {
6437  console.info('Succeeded in preparing');
6438}).catch((error: BusinessError) => {
6439  console.error(`video catchCallback, error:${error}`);
6440});
6441```
6442
6443### play<sup>(deprecated)</sup>
6444
6445play(callback: AsyncCallback\<void>): void
6446
6447Starts video playback. This API uses an asynchronous callback to return the result.
6448
6449> **NOTE**
6450>
6451> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.play](#play9) instead.
6452
6453**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
6454
6455**Parameters**
6456
6457| Name  | Type                | Mandatory| Description                    |
6458| -------- | -------------------- | ---- | ------------------------ |
6459| callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
6460
6461**Example**
6462
6463```ts
6464import { BusinessError } from '@kit.BasicServicesKit';
6465
6466videoPlayer.play((err: BusinessError) => {
6467  if (err) {
6468    console.error('Failed to play!');
6469  } else {
6470    console.info('Succeeded in playing!');
6471  }
6472});
6473```
6474
6475### play<sup>(deprecated)</sup>
6476
6477play(): Promise\<void>
6478
6479Starts video playback. This API uses a promise to return the result.
6480
6481> **NOTE**
6482>
6483> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.play](#play9-1) instead.
6484
6485**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
6486
6487**Return value**
6488
6489| Type          | Description                         |
6490| -------------- | ----------------------------- |
6491| Promise\<void> | Promise that returns no value.|
6492
6493**Example**
6494
6495```ts
6496import { BusinessError } from '@kit.BasicServicesKit';
6497
6498videoPlayer.play().then(() => {
6499  console.info('Succeeded in playing');
6500}).catch((error: BusinessError) => {
6501  console.error(`video catchCallback, error:${error}`);
6502});
6503```
6504
6505### pause<sup>(deprecated)</sup>
6506
6507pause(callback: AsyncCallback\<void>): void
6508
6509Pauses video playback. This API uses an asynchronous callback to return the result.
6510
6511> **NOTE**
6512> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.pause](#pause9) instead.
6513
6514**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
6515
6516**Parameters**
6517
6518| Name  | Type                | Mandatory| Description                    |
6519| -------- | -------------------- | ---- | ------------------------ |
6520| callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
6521
6522**Example**
6523
6524```ts
6525import { BusinessError } from '@kit.BasicServicesKit';
6526
6527videoPlayer.pause((err: BusinessError) => {
6528  if (err) {
6529    console.error('Failed to pause!');
6530  } else {
6531    console.info('Succeeded in pausing!');
6532  }
6533});
6534```
6535
6536### pause<sup>(deprecated)</sup>
6537
6538pause(): Promise\<void>
6539
6540Pauses video playback. This API uses a promise to return the result.
6541
6542> **NOTE**
6543>
6544> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.pause](#pause9-1) instead.
6545
6546**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
6547
6548**Return value**
6549
6550| Type          | Description                         |
6551| -------------- | ----------------------------- |
6552| Promise\<void> | Promise that returns no value.|
6553
6554**Example**
6555
6556```ts
6557import { BusinessError } from '@kit.BasicServicesKit';
6558
6559videoPlayer.pause().then(() => {
6560  console.info('Succeeded in pausing');
6561}).catch((error: BusinessError) => {
6562  console.error(`video catchCallback, error:${error}`);
6563});
6564```
6565
6566### stop<sup>(deprecated)</sup>
6567
6568stop(callback: AsyncCallback\<void>): void
6569
6570Stops video playback. This API uses an asynchronous callback to return the result.
6571
6572> **NOTE**
6573>
6574> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.stop](#stop9) instead.
6575
6576**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
6577
6578**Parameters**
6579
6580| Name  | Type                | Mandatory| Description                    |
6581| -------- | -------------------- | ---- | ------------------------ |
6582| callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
6583
6584**Example**
6585
6586```ts
6587import { BusinessError } from '@kit.BasicServicesKit';
6588
6589videoPlayer.stop((err: BusinessError) => {
6590  if (err) {
6591    console.error('Failed to stop!');
6592  } else {
6593    console.info('Succeeded in stopping!');
6594  }
6595});
6596```
6597
6598### stop<sup>(deprecated)</sup>
6599
6600stop(): Promise\<void>
6601
6602Stops video playback. This API uses a promise to return the result.
6603
6604> **NOTE**
6605>
6606> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.stop](#stop9-1) instead.
6607
6608**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
6609
6610**Return value**
6611
6612| Type          | Description                         |
6613| -------------- | ----------------------------- |
6614| Promise\<void> | Promise that returns no value.|
6615
6616**Example**
6617
6618```ts
6619import { BusinessError } from '@kit.BasicServicesKit';
6620
6621videoPlayer.stop().then(() => {
6622  console.info('Succeeded in stopping');
6623}).catch((error: BusinessError) => {
6624  console.error(`video catchCallback, error:${error}`);
6625});
6626```
6627
6628### reset<sup>(deprecated)</sup>
6629
6630reset(callback: AsyncCallback\<void>): void
6631
6632Resets video playback. This API uses an asynchronous callback to return the result.
6633
6634> **NOTE**
6635>
6636> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.reset](#reset9) instead.
6637
6638**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
6639
6640**Parameters**
6641
6642| Name  | Type                | Mandatory| Description                    |
6643| -------- | -------------------- | ---- | ------------------------ |
6644| callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
6645
6646**Example**
6647
6648```ts
6649import { BusinessError } from '@kit.BasicServicesKit';
6650
6651videoPlayer.reset((err: BusinessError) => {
6652  if (err) {
6653    console.error('Failed to reset!');
6654  } else {
6655    console.info('Succeeded in resetting!');
6656  }
6657});
6658```
6659
6660### reset<sup>(deprecated)</sup>
6661
6662reset(): Promise\<void>
6663
6664Resets video playback. This API uses a promise to return the result.
6665
6666> **NOTE**
6667>
6668> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.reset](#reset9-1) instead.
6669
6670**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
6671
6672**Return value**
6673
6674| Type          | Description                         |
6675| -------------- | ----------------------------- |
6676| Promise\<void> | Promise that returns no value.|
6677
6678**Example**
6679
6680```ts
6681import { BusinessError } from '@kit.BasicServicesKit';
6682
6683videoPlayer.reset().then(() => {
6684  console.info('Succeeded in resetting');
6685}).catch((error: BusinessError) => {
6686  console.error(`video catchCallback, error:${error}`);
6687});
6688```
6689
6690### seek<sup>(deprecated)</sup>
6691
6692seek(timeMs: number, callback: AsyncCallback\<number>): void
6693
6694Seeks to the specified playback position. The previous key frame at the specified position is played. This API uses an asynchronous callback to return the result.
6695
6696> **NOTE**
6697>
6698> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.seek](#seek9) instead.
6699
6700**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
6701
6702**Parameters**
6703
6704| Name  | Type                  | Mandatory| Description                                                        |
6705| -------- | ---------------------- | ---- | ------------------------------------------------------------ |
6706| timeMs   | number                 | Yes  | Position to seek to, in ms. The value range is [0, duration].|
6707| callback | AsyncCallback\<number> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the new playback position; otherwise, **err** is an error object.                              |
6708
6709**Example**
6710
6711```ts
6712import { BusinessError } from '@kit.BasicServicesKit';
6713
6714let videoPlayer: media.VideoPlayer;
6715media.createVideoPlayer((error: BusinessError, video: media.VideoPlayer) => {
6716  if (video != null) {
6717    videoPlayer = video;
6718    console.info('Succeeded in creating VideoPlayer');
6719  } else {
6720    console.error(`Failed to create VideoPlayer, error:${error}`);
6721  }
6722});
6723
6724let seekTime: number = 5000;
6725videoPlayer.seek(seekTime, (err: BusinessError, result: number) => {
6726  if (err) {
6727    console.error('Failed to do seek!');
6728  } else {
6729    console.info('Succeeded in doing seek!');
6730  }
6731});
6732```
6733
6734### seek<sup>(deprecated)</sup>
6735
6736seek(timeMs: number, mode:SeekMode, callback: AsyncCallback\<number>): void
6737
6738Seeks to the specified playback position. This API uses an asynchronous callback to return the result.
6739
6740> **NOTE**
6741>
6742> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.seek](#seek9) instead.
6743
6744**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
6745
6746**Parameters**
6747
6748| Name  | Type                  | Mandatory| Description                                                        |
6749| -------- | ---------------------- | ---- | ------------------------------------------------------------ |
6750| timeMs   | number                 | Yes  | Position to seek to, in ms. The value range is [0, duration].|
6751| mode     | [SeekMode](#seekmode8) | Yes  | Seek mode.                                                  |
6752| callback | AsyncCallback\<number> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the new playback position; otherwise, **err** is an error object.                              |
6753
6754**Example**
6755
6756```ts
6757import { BusinessError } from '@kit.BasicServicesKit';
6758
6759let videoPlayer: media.VideoPlayer | null = null;
6760media.createVideoPlayer((error: BusinessError, video: media.VideoPlayer) => {
6761  if (video != null) {
6762    videoPlayer = video;
6763    console.info('Succeeded in creating VideoPlayer');
6764  } else {
6765    console.error(`Failed to create VideoPlayer, error:${error}`);
6766  }
6767});
6768let seekTime: number = 5000;
6769if (videoPlayer) {
6770  (videoPlayer as media.VideoPlayer).seek(seekTime, media.SeekMode.SEEK_NEXT_SYNC, (err: BusinessError, result: number) => {
6771    if (err) {
6772      console.error('Failed to do seek!');
6773    } else {
6774      console.info('Succeeded in doing seek!');
6775    }
6776  });
6777}
6778```
6779
6780### seek<sup>(deprecated)</sup>
6781
6782seek(timeMs: number, mode?:SeekMode): Promise\<number>
6783
6784Seeks to the specified playback position. If **mode** is not specified, the previous key frame at the specified position is played. This API uses a promise to return the result.
6785
6786> **NOTE**
6787>
6788> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.seek](#seek9) instead.
6789
6790**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
6791
6792**Parameters**
6793
6794| Name| Type                  | Mandatory| Description                                                        |
6795| ------ | ---------------------- | ---- | ------------------------------------------------------------ |
6796| timeMs | number                 | Yes  | Position to seek to, in ms. The value range is [0, duration].|
6797| mode   | [SeekMode](#seekmode8) | No  | Seek mode based on the video I frame. The default value is **SEEK_PREV_SYNC**.           |
6798
6799**Return value**
6800
6801| Type            | Description                                       |
6802| ---------------- | ------------------------------------------- |
6803| Promise\<number>| Promise used to return the playback position, in ms.|
6804
6805**Example**
6806
6807```ts
6808import { BusinessError } from '@kit.BasicServicesKit';
6809
6810let videoPlayer: media.VideoPlayer | null = null;
6811media.createVideoPlayer((error: BusinessError, video: media.VideoPlayer) => {
6812  if (video != null) {
6813    videoPlayer = video;
6814    console.info('Succeeded in creating VideoPlayer');
6815  } else {
6816    console.error(`Failed to create VideoPlayer, error:${error}`);
6817  }
6818});
6819let seekTime: number = 5000;
6820if (videoPlayer) {
6821  (videoPlayer as media.VideoPlayer).seek(seekTime).then((seekDoneTime: number) => { // seekDoneTime indicates the position after the seek operation is complete.
6822    console.info('Succeeded in doing seek');
6823  }).catch((error: BusinessError) => {
6824    console.error(`video catchCallback, error:${error}`);
6825  });
6826
6827  (videoPlayer as media.VideoPlayer).seek(seekTime, media.SeekMode.SEEK_NEXT_SYNC).then((seekDoneTime: number) => {
6828    console.info('Succeeded in doing seek');
6829  }).catch((error: BusinessError) => {
6830    console.error(`video catchCallback, error:${error}`);
6831  });
6832}
6833```
6834
6835### setVolume<sup>(deprecated)</sup>
6836
6837setVolume(vol: number, callback: AsyncCallback\<void>): void
6838
6839Sets the volume. This API uses an asynchronous callback to return the result.
6840
6841> **NOTE**
6842>
6843> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.setVolume](#setvolume9) instead.
6844
6845**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
6846
6847**Parameters**
6848
6849| Name  | Type                | Mandatory| Description                                                        |
6850| -------- | -------------------- | ---- | ------------------------------------------------------------ |
6851| vol      | number               | Yes  | Relative volume. The value ranges from 0.00 to 1.00. The value **1.00** indicates the maximum volume (100%).|
6852| callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the setting is successful, **err** is **undefined**. Otherwise, **err** is an error object.|
6853
6854**Example**
6855
6856```ts
6857import { BusinessError } from '@kit.BasicServicesKit';
6858
6859let vol: number = 0.5;
6860videoPlayer.setVolume(vol, (err: BusinessError) => {
6861  if (err) {
6862    console.error('Failed to set Volume!');
6863  } else {
6864    console.info('Succeeded in setting Volume!');
6865  }
6866});
6867```
6868
6869### setVolume<sup>(deprecated)</sup>
6870
6871setVolume(vol: number): Promise\<void>
6872
6873Sets the volume. This API uses a promise to return the result.
6874
6875> **NOTE**
6876>
6877> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.setVolume](#setvolume9) instead.
6878
6879**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
6880
6881**Parameters**
6882
6883| Name| Type  | Mandatory| Description                                                        |
6884| ------ | ------ | ---- | ------------------------------------------------------------ |
6885| vol    | number | Yes  | Relative volume. The value ranges from 0.00 to 1.00. The value **1.00** indicates the maximum volume (100%).|
6886
6887**Return value**
6888
6889| Type          | Description                     |
6890| -------------- | ------------------------- |
6891| Promise\<void> | Promise that returns no value.|
6892
6893**Example**
6894
6895```ts
6896import { BusinessError } from '@kit.BasicServicesKit';
6897
6898let vol: number = 0.5;
6899videoPlayer.setVolume(vol).then(() => {
6900  console.info('Succeeded in setting Volume');
6901}).catch((error: BusinessError) => {
6902  console.error(`video catchCallback, error:${error}`);
6903});
6904```
6905
6906### release<sup>(deprecated)</sup>
6907
6908release(callback: AsyncCallback\<void>): void
6909
6910Releases the video playback resources. This API uses an asynchronous callback to return the result.
6911
6912> **NOTE**
6913>
6914> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.release](#release9) instead.
6915
6916**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
6917
6918**Parameters**
6919
6920| Name  | Type                | Mandatory| Description                    |
6921| -------- | -------------------- | ---- | ------------------------ |
6922| callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
6923
6924**Example**
6925
6926```ts
6927import { BusinessError } from '@kit.BasicServicesKit';
6928
6929videoPlayer.release((err: BusinessError) => {
6930  if (err) {
6931    console.error('Failed to release!');
6932  } else {
6933    console.info('Succeeded in releasing!');
6934  }
6935});
6936```
6937
6938### release<sup>(deprecated)</sup>
6939
6940release(): Promise\<void>
6941
6942Releases the video playback resources. This API uses a promise to return the result.
6943
6944> **NOTE**
6945>
6946> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.release](#release9-1) instead.
6947
6948**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
6949
6950**Return value**
6951
6952| Type          | Description                         |
6953| -------------- | ----------------------------- |
6954| Promise\<void> | Promise that returns no value.|
6955
6956**Example**
6957
6958```ts
6959import { BusinessError } from '@kit.BasicServicesKit';
6960
6961videoPlayer.release().then(() => {
6962  console.info('Succeeded in releasing');
6963}).catch((error: BusinessError) => {
6964  console.error(`video catchCallback, error:${error}`);
6965});
6966```
6967
6968### getTrackDescription<sup>(deprecated)</sup>
6969
6970getTrackDescription(callback: AsyncCallback\<Array\<MediaDescription>>): void
6971
6972Obtains the video track information. This API uses an asynchronous callback to return the result.
6973
6974> **NOTE**
6975>
6976> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.getTrackDescription](#gettrackdescription9) instead.
6977
6978**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
6979
6980**Parameters**
6981
6982| Name  | Type                                                        | Mandatory| Description                                      |
6983| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------ |
6984| callback | AsyncCallback\<Array\<[MediaDescription](#mediadescription8)>> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the MediaDescription array obtained; otherwise, **err** is an error object.|
6985
6986**Example**
6987
6988```ts
6989import { BusinessError } from '@kit.BasicServicesKit';
6990
6991videoPlayer.getTrackDescription((error: BusinessError, arrList: Array<media.MediaDescription>) => {
6992  if ((arrList) != null) {
6993    console.info('Succeeded in getting TrackDescription');
6994  } else {
6995    console.error(`Failed to get TrackDescription, error:${error}`);
6996  }
6997});
6998```
6999
7000### getTrackDescription<sup>(deprecated)</sup>
7001
7002getTrackDescription(): Promise\<Array\<MediaDescription>>
7003
7004Obtains the video track information. This API uses a promise to return the result.
7005
7006> **NOTE**
7007>
7008> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.getTrackDescription](#gettrackdescription9-1) instead.
7009
7010**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
7011
7012**Return value**
7013
7014| Type                                                  | Description                                           |
7015| ------------------------------------------------------ | ----------------------------------------------- |
7016| Promise<Array<[MediaDescription](#mediadescription8)>> | Promise used to return the MediaDescription array that holds the video track information.|
7017
7018**Example**
7019
7020```ts
7021import { BusinessError } from '@kit.BasicServicesKit';
7022
7023videoPlayer.getTrackDescription().then((arrList: Array<media.MediaDescription>) => {
7024  if (arrList != null) {
7025    console.info('Succeeded in getting TrackDescription');
7026  } else {
7027    console.error('Failed to get TrackDescription');
7028  }
7029}).catch((error: BusinessError) => {
7030  console.error(`video catchCallback, error:${error}`);
7031});
7032```
7033
7034### setSpeed<sup>(deprecated)</sup>
7035
7036setSpeed(speed: number, callback: AsyncCallback\<number>): void
7037
7038Sets the playback speed. This API uses an asynchronous callback to return the result.
7039
7040> **NOTE**
7041>
7042> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.setSpeed](#setspeed9) instead.
7043
7044**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
7045
7046**Parameters**
7047
7048| Name  | Type                  | Mandatory| Description                                                      |
7049| -------- | ---------------------- | ---- | ---------------------------------------------------------- |
7050| speed    | number                 | Yes  | Video playback speed. For details, see [PlaybackSpeed](#playbackspeed8).|
7051| callback | AsyncCallback\<number> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the playback speed; otherwise, **err** is an error object.                                  |
7052
7053**Example**
7054
7055```ts
7056import { BusinessError } from '@kit.BasicServicesKit';
7057
7058let videoPlayer: media.VideoPlayer | null = null;
7059media.createVideoPlayer((error: BusinessError, video: media.VideoPlayer) => {
7060  if (video != null) {
7061    videoPlayer = video;
7062    console.info('Succeeded in creating VideoPlayer');
7063  } else {
7064    console.error(`Failed to create VideoPlayer, error:${error}`);
7065  }
7066});
7067let speed = media.PlaybackSpeed.SPEED_FORWARD_2_00_X;
7068if (videoPlayer) {
7069  (videoPlayer as media.VideoPlayer).setSpeed(speed, (err: BusinessError, result: number) => {
7070    if (err) {
7071      console.error('Failed to set Speed!');
7072    } else {
7073      console.info('Succeeded in setting Speed!');
7074    }
7075  });
7076}
7077```
7078
7079### setSpeed<sup>(deprecated)</sup>
7080
7081setSpeed(speed: number): Promise\<number>
7082
7083Sets the playback speed. This API uses a promise to return the result.
7084
7085> **NOTE**
7086>
7087> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.setSpeed](#setspeed9) instead.
7088
7089**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
7090
7091**Parameters**
7092
7093| Name| Type  | Mandatory| Description                                                      |
7094| ------ | ------ | ---- | ---------------------------------------------------------- |
7095| speed  | number | Yes  | Video playback speed. For details, see [PlaybackSpeed](#playbackspeed8).|
7096
7097**Return value**
7098
7099| Type            | Description                                                        |
7100| ---------------- | ------------------------------------------------------------ |
7101| Promise\<number>| Promise used to return the playback speed. For details, see [PlaybackSpeed](#playbackspeed8).|
7102
7103**Example**
7104
7105```ts
7106import { BusinessError } from '@kit.BasicServicesKit';
7107
7108let videoPlayer: media.VideoPlayer | null = null;
7109media.createVideoPlayer((error: BusinessError, video: media.VideoPlayer) => {
7110  if (video != null) {
7111    videoPlayer = video;
7112    console.info('Succeeded in creating VideoPlayer');
7113  } else {
7114    console.error(`Failed to create VideoPlayer, error:${error}`);
7115  }
7116});
7117let speed = media.PlaybackSpeed.SPEED_FORWARD_2_00_X;
7118if (videoPlayer) {
7119  (videoPlayer as media.VideoPlayer).setSpeed(speed).then((result: number) => {
7120    console.info('Succeeded in setting Speed');
7121  }).catch((error: BusinessError) => {
7122    console.error(`Failed to set Speed, error:${error}`);//todo:: error.
7123  });
7124}
7125```
7126
7127### on('playbackCompleted')<sup>(deprecated)</sup>
7128
7129on(type: 'playbackCompleted', callback: Callback\<void>): void
7130
7131Subscribes to the video playback completion event.
7132
7133> **NOTE**
7134>
7135> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.on('stateChange')](#onstatechange9) instead.
7136
7137**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
7138
7139**Parameters**
7140
7141| Name  | Type    | Mandatory| Description                                                       |
7142| -------- | -------- | ---- | ----------------------------------------------------------- |
7143| type     | string   | Yes  | Event type, which is **'playbackCompleted'** in this case.|
7144| callback | Callback\<void> | Yes  | Callback invoked when the event is triggered.                                 |
7145
7146**Example**
7147
7148```ts
7149videoPlayer.on('playbackCompleted', () => {
7150  console.info('playbackCompleted called!');
7151});
7152```
7153
7154### on('bufferingUpdate')<sup>(deprecated)</sup>
7155
7156on(type: 'bufferingUpdate', callback: (infoType: BufferingInfoType, value: number) => void): void
7157
7158Subscribes to the video buffering update event. This API works only under online playback.
7159
7160> **NOTE**
7161>
7162> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.on('bufferingUpdate')](#onbufferingupdate9) instead.
7163
7164**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
7165
7166**Parameters**
7167
7168| Name  | Type    | Mandatory| Description                                                        |
7169| -------- | -------- | ---- | ------------------------------------------------------------ |
7170| type     | string   | Yes  | Event type, which is **'bufferingUpdate'** in this case.       |
7171| callback | function | Yes  | Callback invoked when the event is triggered.<br>The value of [BufferingInfoType](#bufferinginfotype8) is fixed at **0**.|
7172
7173**Example**
7174
7175```ts
7176videoPlayer.on('bufferingUpdate', (infoType: media.BufferingInfoType, value: number) => {
7177  console.info('video bufferingInfo type: ' + infoType);
7178  console.info('video bufferingInfo value: ' + value);
7179});
7180```
7181
7182### on('startRenderFrame')<sup>(deprecated)</sup>
7183
7184on(type: 'startRenderFrame', callback: Callback\<void>): void
7185
7186Subscribes to the frame rendering start event.
7187
7188> **NOTE**
7189>
7190> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.on('startRenderFrame')](#onstartrenderframe9) instead.
7191
7192**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
7193
7194**Parameters**
7195
7196| Name  | Type           | Mandatory| Description                                                        |
7197| -------- | --------------- | ---- | ------------------------------------------------------------ |
7198| type     | string          | Yes  | Event type, which is **'startRenderFrame'** in this case.|
7199| callback | Callback\<void> | Yes  | Callback invoked when the event is triggered.                          |
7200
7201**Example**
7202
7203```ts
7204videoPlayer.on('startRenderFrame', () => {
7205  console.info('startRenderFrame called!');
7206});
7207```
7208
7209### on('videoSizeChanged')<sup>(deprecated)</sup>
7210
7211on(type: 'videoSizeChanged', callback: (width: number, height: number) => void): void
7212
7213Subscribes to the video width and height change event.
7214
7215> **NOTE**
7216> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.on('videoSizeChange')](#onvideosizechange9) instead.
7217
7218**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
7219
7220**Parameters**
7221
7222| Name  | Type    | Mandatory| Description                                                        |
7223| -------- | -------- | ---- | ------------------------------------------------------------ |
7224| type     | string   | Yes  | Event type, which is **'videoSizeChanged'** in this case.|
7225| callback | function | Yes  | Callback invoked when the event is triggered. **width** indicates the video width, and **height** indicates the video height.   |
7226
7227**Example**
7228
7229```ts
7230videoPlayer.on('videoSizeChanged', (width: number, height: number) => {
7231  console.info('video width is: ' + width);
7232  console.info('video height is: ' + height);
7233});
7234```
7235### on('audioInterrupt')<sup>(deprecated)</sup>
7236
7237on(type: 'audioInterrupt', callback: (info: audio.InterruptEvent) => void): void
7238
7239Subscribes to the audio interruption event. For details, see [audio.InterruptEvent](../apis-audio-kit/js-apis-audio.md#interruptevent9).
7240
7241> **NOTE**
7242>
7243> This API is supported in API version 9 and deprecated since API version 9. You are advised to use [AVPlayer.on('audioInterrupt')](#onaudiointerrupt9) instead.
7244
7245**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
7246
7247**Parameters**
7248
7249| Name  | Type                                                        | Mandatory| Description                                                    |
7250| -------- | ------------------------------------------------------------ | ---- | -------------------------------------------------------- |
7251| type     | string                                                       | Yes  | Event type, which is **'audioInterrupt'** in this case.|
7252| callback | function | Yes  | Callback invoked when the event is triggered.                              |
7253
7254**Example**
7255
7256```ts
7257import { audio } from '@kit.AudioKit';
7258
7259videoPlayer.on('audioInterrupt', (info: audio.InterruptEvent) => {
7260  console.info('audioInterrupt called,and InterruptEvent info is:' + info)
7261})
7262```
7263
7264### on('error')<sup>(deprecated)</sup>
7265
7266on(type: 'error', callback: ErrorCallback): void
7267
7268Subscribes to video playback error events. After an error event is reported, you must handle the event and exit the playback.
7269
7270> **NOTE**
7271>
7272> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.on('error')](#onerror9) instead.
7273
7274**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
7275
7276**Parameters**
7277
7278| Name  | Type         | Mandatory| Description                                                        |
7279| -------- | ------------- | ---- | ------------------------------------------------------------ |
7280| type     | string        | Yes  | Event type, which is **'error'** in this case.<br>This event is triggered when an error occurs during video playback.|
7281| callback | [ErrorCallback](../apis-basic-services-kit/js-apis-base.md#errorcallback) | Yes  | Callback invoked when the event is triggered.                                      |
7282
7283**Example**
7284
7285```ts
7286import { BusinessError } from '@kit.BasicServicesKit';
7287
7288videoPlayer.on('error', (error: BusinessError) => {  // Set the 'error' event callback.
7289  console.error(`video error called, error: ${error}`);
7290});
7291videoPlayer.url = 'fd://error';  // Set an incorrect URL to trigger the 'error' event.
7292```
7293
7294## VideoPlayState<sup>(deprecated)</sup>
7295
7296type VideoPlayState = 'idle' | 'prepared' | 'playing' | 'paused' | 'stopped' | 'error'
7297
7298Enumerates the video playback states. You can obtain the state through the **state** attribute.
7299
7300> **NOTE**
7301>
7302> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayerState](#avplayerstate9) instead.
7303
7304**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
7305
7306| Type    | Description          |
7307| -------- | -------------- |
7308| 'idle'     | The video player is idle.|
7309| 'prepared' | Video playback is being prepared.|
7310| 'playing'  | Video playback is in progress.|
7311| 'paused'   | Video playback is paused.|
7312| 'stopped'  | Video playback is stopped.|
7313| 'error'    | Video playback is in the error state.    |
7314
7315## AudioRecorder<sup>(deprecated)</sup>
7316
7317> **NOTE**
7318>
7319> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVRecorder](#avrecorder9) instead.
7320
7321Implements audio recording. Before calling any API of **AudioRecorder**, you must use [createAudioRecorder()](#mediacreateaudiorecorderdeprecated) to create an **AudioRecorder** instance.
7322
7323### prepare<sup>(deprecated)</sup>
7324
7325prepare(config: AudioRecorderConfig): void
7326
7327Prepares for recording.
7328
7329> **NOTE**
7330>
7331> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVRecorder.prepare](#prepare9-2) instead.
7332
7333**Required permissions:** ohos.permission.MICROPHONE
7334
7335**System capability**: SystemCapability.Multimedia.Media.AudioRecorder
7336
7337**Parameters**
7338
7339| Name| Type                                       | Mandatory| Description                                                        |
7340| ------ | ------------------------------------------- | ---- | ------------------------------------------------------------ |
7341| config | [AudioRecorderConfig](#audiorecorderconfigdeprecated) | Yes  | Audio recording parameters, including the audio output URI, encoding format, sampling rate, number of audio channels, and output format.|
7342
7343**Error codes**
7344
7345For details about the error codes, see [Media Error Codes](errorcode-media.md).
7346
7347| ID| Error Message             |
7348| -------- | --------------------- |
7349| 201      | permission denied     |
7350
7351**Example**
7352
7353```ts
7354let audioRecorderConfig: media.AudioRecorderConfig = {
7355  audioEncoder : media.AudioEncoder.AAC_LC,
7356  audioEncodeBitRate : 22050,
7357  audioSampleRate : 22050,
7358  numberOfChannels : 2,
7359  format : media.AudioOutputFormat.AAC_ADTS,
7360  uri : 'fd://1',       // The file must be created by the caller and granted with proper permissions.
7361  location : { latitude : 30, longitude : 130},
7362}
7363audioRecorder.on('prepare', () => {    // Set the 'prepare' event callback.
7364  console.info('prepare called');
7365});
7366audioRecorder.prepare(audioRecorderConfig);
7367```
7368
7369### start<sup>(deprecated)</sup>
7370
7371start(): void
7372
7373Starts audio recording. This API can be called only after the **'prepare'** event is triggered.
7374
7375> **NOTE**
7376>
7377> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVRecorder.start](#start9) instead.
7378
7379**System capability**: SystemCapability.Multimedia.Media.AudioRecorder
7380
7381**Example**
7382
7383```ts
7384audioRecorder.on('start', () => {    // Set the 'start' event callback.
7385  console.info('audio recorder start called');
7386});
7387audioRecorder.start();
7388```
7389
7390### pause<sup>(deprecated)</sup>
7391
7392pause():void
7393
7394Pauses audio recording. This API can be called only after the **'start'** event is triggered.
7395
7396> **NOTE**
7397>
7398> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVRecorder.pause](#pause9-2) instead.
7399
7400**System capability**: SystemCapability.Multimedia.Media.AudioRecorder
7401
7402**Example**
7403
7404```ts
7405audioRecorder.on('pause', () => {    // Set the 'pause' event callback.
7406  console.info('audio recorder pause called');
7407});
7408audioRecorder.pause();
7409```
7410
7411### resume<sup>(deprecated)</sup>
7412
7413resume():void
7414
7415Resumes audio recording. This API can be called only after the **'pause'** event is triggered.
7416
7417> **NOTE**
7418>
7419> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVRecorder.resume](#resume9) instead.
7420
7421**System capability**: SystemCapability.Multimedia.Media.AudioRecorder
7422
7423**Example**
7424
7425```ts
7426audioRecorder.on('resume', () => { // Set the 'resume' event callback.
7427  console.info('audio recorder resume called');
7428});
7429audioRecorder.resume();
7430```
7431
7432### stop<sup>(deprecated)</sup>
7433
7434stop(): void
7435
7436Stops audio recording.
7437
7438> **NOTE**
7439>
7440> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVRecorder.stop](#stop9-2) instead.
7441
7442**System capability**: SystemCapability.Multimedia.Media.AudioRecorder
7443
7444**Example**
7445
7446```ts
7447audioRecorder.on('stop', () => {    // Set the 'stop' event callback.
7448  console.info('audio recorder stop called');
7449});
7450audioRecorder.stop();
7451```
7452
7453### release<sup>(deprecated)</sup>
7454
7455release(): void
7456
7457Releases the audio recording resources.
7458
7459> **NOTE**
7460>
7461> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVRecorder.release](#release9-2) instead.
7462
7463**System capability**: SystemCapability.Multimedia.Media.AudioRecorder
7464
7465**Example**
7466
7467```ts
7468audioRecorder.on('release', () => {    // Set the 'release' event callback.
7469  console.info('audio recorder release called');
7470});
7471audioRecorder.release();
7472audioRecorder = undefined;
7473```
7474
7475### reset<sup>(deprecated)</sup>
7476
7477reset(): void
7478
7479Resets audio recording.
7480
7481Before resetting audio recording, you must call **stop()** to stop recording. After audio recording is reset, you must call **prepare()** to set the recording configurations for another recording.
7482
7483> **NOTE**
7484>
7485> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVRecorder.reset](#reset9-2) instead.
7486
7487**System capability**: SystemCapability.Multimedia.Media.AudioRecorder
7488
7489**Example**
7490
7491```ts
7492audioRecorder.on('reset', () => {    // Set the 'reset' event callback.
7493  console.info('audio recorder reset called');
7494});
7495audioRecorder.reset();
7496```
7497
7498### on('prepare' | 'start' | 'pause' | 'resume' | 'stop' | 'release' | 'reset')<sup>(deprecated)</sup>
7499
7500on(type: 'prepare' | 'start' | 'pause' | 'resume' | 'stop' | 'release' | 'reset', callback: () => void): void
7501
7502Subscribes to the audio recording events.
7503
7504> **NOTE**
7505>
7506> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVRecorder.on('stateChange')](#onstatechange9-1) instead.
7507
7508**System capability**: SystemCapability.Multimedia.Media.AudioRecorder
7509
7510**Parameters**
7511
7512| Name  | Type    | Mandatory| Description                                                        |
7513| -------- | -------- | ---- | ------------------------------------------------------------ |
7514| type     | string   | Yes  | Event type. The following events are supported: 'prepare'\|'start'\|  'pause' \| 'resume' \|'stop'\|'release'\|'reset'<br>- 'prepare': triggered when the **prepare()** API is called and the audio recording parameters are set.<br>- 'start': triggered when the **start()** API is called and audio recording starts.<br>- 'pause': triggered when the **pause()** API is called and audio recording is paused.<br>- 'resume': triggered when the **resume()** API is called and audio recording is resumed.<br>- 'stop': triggered when the **stop()** API is called and audio recording stops.<br>- 'release': triggered when the **release()** API is called and the recording resources are released.<br>- 'reset': triggered when the **reset()** API is called and audio recording is reset.|
7515| callback | ()=>void | Yes  | Callback invoked when the event is triggered.                                          |
7516
7517**Example**
7518
7519```ts
7520import { BusinessError } from '@kit.BasicServicesKit';
7521
7522let audioRecorder: media.AudioRecorder = media.createAudioRecorder(); // Create an AudioRecorder instance.
7523let audioRecorderConfig: media.AudioRecorderConfig = {
7524  audioEncoder : media.AudioEncoder.AAC_LC,
7525  audioEncodeBitRate : 22050,
7526  audioSampleRate : 22050,
7527  numberOfChannels : 2,
7528  format : media.AudioOutputFormat.AAC_ADTS,
7529  uri : 'fd://xx',  // The file must be created by the caller and granted with proper permissions.
7530  location : { latitude : 30, longitude : 130}
7531}
7532audioRecorder.on('error', (error: BusinessError) => {  // Set the 'error' event callback.
7533  console.error(`audio error called, error: ${error}`);
7534});
7535audioRecorder.on('prepare', () => {  // Set the 'prepare' event callback.
7536  console.info('prepare called');
7537  audioRecorder.start();  // // Start recording and trigger the 'start' event callback.
7538});
7539audioRecorder.on('start', () => {  // Set the 'start' event callback.
7540  console.info('audio recorder start called');
7541});
7542audioRecorder.on('pause', () => {  // Set the 'pause' event callback.
7543  console.info('audio recorder pause called');
7544});
7545audioRecorder.on('resume', () => {  // Set the 'resume' event callback.
7546  console.info('audio recorder resume called');
7547});
7548audioRecorder.on('stop', () => {  // Set the 'stop' event callback.
7549  console.info('audio recorder stop called');
7550});
7551audioRecorder.on('release', () => {  // Set the 'release' event callback.
7552  console.info('audio recorder release called');
7553});
7554audioRecorder.on('reset', () => {  // Set the 'reset' event callback.
7555  console.info('audio recorder reset called');
7556});
7557audioRecorder.prepare(audioRecorderConfig)  // // Set recording parameters and trigger the 'prepare' event callback.
7558```
7559
7560### on('error')<sup>(deprecated)</sup>
7561
7562on(type: 'error', callback: ErrorCallback): void
7563
7564Subscribes to audio recording error events. After an error event is reported, you must handle the event and exit the recording.
7565
7566> **NOTE**
7567>
7568> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVRecorder.on('error')](#onerror9-1) instead.
7569
7570**System capability**: SystemCapability.Multimedia.Media.AudioRecorder
7571
7572**Parameters**
7573
7574| Name  | Type         | Mandatory| Description                                                        |
7575| -------- | ------------- | ---- | ------------------------------------------------------------ |
7576| type     | string        | Yes  | Event type, which is **'error'** in this case.<br>This event is triggered when an error occurs during audio recording.|
7577| callback | [ErrorCallback](../apis-basic-services-kit/js-apis-base.md#errorcallback) | Yes  | Callback invoked when the event is triggered.                                      |
7578
7579**Example**
7580
7581```ts
7582import { BusinessError } from '@kit.BasicServicesKit';
7583
7584let audioRecorderConfig: media.AudioRecorderConfig = {
7585  audioEncoder : media.AudioEncoder.AAC_LC,
7586  audioEncodeBitRate : 22050,
7587  audioSampleRate : 22050,
7588  numberOfChannels : 2,
7589  format : media.AudioOutputFormat.AAC_ADTS,
7590  uri : 'fd://xx',   // The file must be created by the caller and granted with proper permissions.
7591  location : { latitude : 30, longitude : 130}
7592}
7593audioRecorder.on('error', (error: BusinessError) => {  // Set the 'error' event callback.
7594  console.error(`audio error called, error: ${error}`);
7595});
7596audioRecorder.prepare(audioRecorderConfig);  // // Do not set any parameter in prepare and trigger the 'error' event callback.
7597```
7598
7599## AudioRecorderConfig<sup>(deprecated)</sup>
7600
7601> **NOTE**
7602>
7603> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVRecorderConfig](#avrecorderconfig9) instead.
7604
7605Describes audio recording configurations.
7606
7607**System capability**: SystemCapability.Multimedia.Media.AudioRecorder
7608
7609| Name                               | Type                                        | Mandatory| Description                                                        |
7610| ----------------------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ |
7611| audioEncoder                        | [AudioEncoder](#audioencoderdeprecated)                | No  | Audio encoding format. The default value is **AAC_LC**.<br>**Note**: This parameter is deprecated since API version 8. Use **audioEncoderMime** instead.|
7612| audioEncodeBitRate                  | number                                       | No  | Audio encoding bit rate. The default value is **48000**.                             |
7613| audioSampleRate                     | number                                       | No  | Audio sampling rate. The default value is **48000**.<br>Variable bit rate. The bit rate is for reference only.                             |
7614| numberOfChannels                    | number                                       | No  | Number of audio channels. The default value is **2**.                                 |
7615| format                              | [AudioOutputFormat](#audiooutputformatdeprecated)      | No  | Audio output format. The default value is **MPEG_4**.<br>**Note**: This parameter is deprecated since API version 8. Use **fileFormat** instead.|
7616| location                            | [Location](#location)                        | No  | Geographical location of the recorded audio.                                        |
7617| uri                                 | string                                       | Yes  | Audio output URI. Supported: fd://xx (fd number)<br>![](figures/en-us_image_url.png) <br>The file must be created by the caller and granted with proper permissions.|
7618| audioEncoderMime<sup>8+</sup>       | [CodecMimeType](#codecmimetype8)             | No  | Container encoding format.                                              |
7619| fileFormat<sup>8+</sup>             | [ContainerFormatType](#containerformattype8) | No  | Audio encoding format.                                              |
7620
7621## AudioEncoder<sup>(deprecated)</sup>
7622
7623> **NOTE**
7624>
7625> This API is supported since API version 6 and deprecated since API version 8. You are advised to use [CodecMimeType](#codecmimetype8) instead.
7626
7627Enumerates the audio encoding formats.
7628
7629**System capability**: SystemCapability.Multimedia.Media.AudioRecorder
7630
7631| Name   | Value  | Description                                                        |
7632| ------- | ---- | ------------------------------------------------------------ |
7633| DEFAULT | 0    | Default encoding format.<br>This API is defined but not implemented yet.             |
7634| AMR_NB  | 1    | AMR-NB.<br>This API is defined but not implemented yet.|
7635| AMR_WB  | 2    | Adaptive Multi Rate-Wide Band Speech Codec (AMR-WB).<br>This API is defined but not implemented yet.|
7636| AAC_LC  | 3    | Advanced Audio Coding Low Complexity (AAC-LC).|
7637| HE_AAC  | 4    | High-Efficiency Advanced Audio Coding (HE_AAC).<br>This API is defined but not implemented yet.|
7638
7639## AudioOutputFormat<sup>(deprecated)</sup>
7640
7641> **NOTE**
7642>
7643> This API is supported since API version 6 and deprecated since API version 8. You are advised to use [ContainerFormatType](#containerformattype8) instead.
7644
7645Enumerates the audio output formats.
7646
7647**System capability**: SystemCapability.Multimedia.Media.AudioRecorder
7648
7649| Name    | Value  | Description                                                        |
7650| -------- | ---- | ------------------------------------------------------------ |
7651| DEFAULT  | 0    | Default output format.<br>This API is defined but not implemented yet.             |
7652| MPEG_4   | 2    | MPEG-4.                                          |
7653| AMR_NB   | 3    | AMR_NB.<br>This API is defined but not implemented yet.         |
7654| AMR_WB   | 4    | AMR_WB.<br>This API is defined but not implemented yet.         |
7655| AAC_ADTS | 6    | Audio Data Transport Stream (ADTS), which is a transport stream format of AAC-based audio.|
7656
7657
7658## media.createAVImageGenerator<sup>12+</sup>
7659
7660createAVImageGenerator(callback: AsyncCallback\<AVImageGenerator>): void
7661
7662Creates an **AVImageGenerator** instance. This API uses an asynchronous callback to return the result.
7663
7664**System capability**: SystemCapability.Multimedia.Media.AVImageGenerator
7665
7666**Parameters**
7667
7668| Name  | Type                                 | Mandatory| Description                                                        |
7669| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ |
7670| callback | AsyncCallback\<[AVImageGenerator](#avimagegenerator12)> | Yes  | Callback used to return the result. If the operation is successful, an **AVImageGenerator** instance is returned; otherwise, **null** is returned. The API can be used to obtain a video thumbnail.|
7671
7672**Error codes**
7673
7674For details about the error codes, see [Media Error Codes](errorcode-media.md).
7675
7676| ID| Error Message                      |
7677| -------- | ------------------------------ |
7678| 5400101  | No memory. Returned by callback. |
7679
7680**Example**
7681
7682```ts
7683import { BusinessError } from '@kit.BasicServicesKit';
7684
7685let avImageGenerator: media.AVImageGenerator;
7686media.createAVImageGenerator((error: BusinessError, generator: media.AVImageGenerator) => {
7687  if (generator != null) {
7688    avImageGenerator = generator;
7689    console.info('Succeeded in creating AVImageGenerator');
7690  } else {
7691    console.error(`Failed to creat AVImageGenerator, error message:${error.message}`);
7692  }
7693});
7694```
7695
7696## media.createAVImageGenerator<sup>12+</sup>
7697
7698createAVImageGenerator(): Promise\<AVImageGenerator>
7699
7700Creates an **AVImageGenerator** instance. This API uses a promise to return the result.
7701
7702**System capability**: SystemCapability.Multimedia.Media.AVImageGenerator
7703
7704**Return value**
7705
7706| Type                           | Description                                                        |
7707| ------------------------------- | ------------------------------------------------------------ |
7708| Promise\<[AVImageGenerator](#avimagegenerator12)> | Promise used to return the result. If the operation is successful, an **AVImageGenerator** instance is returned; otherwise, **null** is returned. The API can be used to obtain a video thumbnail.|
7709
7710**Error codes**
7711
7712For details about the error codes, see [Media Error Codes](errorcode-media.md).
7713
7714| ID| Error Message                     |
7715| -------- | ----------------------------- |
7716| 5400101  | No memory. Returned by promise. |
7717
7718**Example**
7719
7720```ts
7721import { BusinessError } from '@kit.BasicServicesKit';
7722
7723let avImageGenerator: media.AVImageGenerator;
7724media.createAVImageGenerator().then((generator: media.AVImageGenerator) => {
7725  if (generator != null) {
7726    avImageGenerator = generator;
7727    console.info('Succeeded in creating AVImageGenerator');
7728  } else {
7729    console.error('Failed to creat AVImageGenerator');
7730  }
7731}).catch((error: BusinessError) => {
7732  console.error(`Failed to creat AVImageGenerator, error message:${error.message}`);
7733});
7734```
7735
7736## AVImageGenerator<sup>12+</sup>
7737
7738Provides APIs to obtain a thumbnail from a video. Before calling any API of **AVImageGenerator**, you must use [createAVImageGenerator()](#mediacreateavimagegenerator12) to create an **AVImageGenerator** instance.
7739
7740For details about the demo for obtaining video thumbnails, see [Obtaining Video Thumbnails](../../media/media/avimagegenerator.md).
7741
7742### Attributes
7743
7744**System capability**: SystemCapability.Multimedia.Media.AVImageGenerator
7745
7746| Name                                               | Type                                                        | Readable| Writable| Description                                                        |
7747| --------------------------------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ |
7748| fdSrc<sup>12+</sup>                                  | [AVFileDescriptor](js-apis-media.md#avfiledescriptor9)                       | Yes  | Yes  | Media file descriptor, which specifies the data source.<br>**Example:**<br>There is a media file that stores continuous assets, the address offset is 0, and the byte length is 100. Its file descriptor is **AVFileDescriptor { fd = resourceHandle; offset = 0; length = 100; }**.<br>**NOTE**<br> - After the resource handle (FD) is transferred to an **AVImageGenerator** instance, do not use the resource handle to perform other read and write operations, including but not limited to transferring this handle to other **AVPlayer**, **AVMetadataExtractor**, **AVImageGenerator**, or **AVTranscoder** instance. Competition occurs when multiple AVImageGenerator use the same resource handle to read and write files at the same time, resulting in errors in obtaining data.|
7749
7750### fetchFrameByTime<sup>12+</sup>
7751
7752fetchFrameByTime(timeUs: number, options: AVImageQueryOptions, param: PixelMapParams, callback: AsyncCallback\<image.PixelMap>): void
7753
7754Obtains a video thumbnail. This API uses an asynchronous callback to return the result.
7755
7756**System capability**: SystemCapability.Multimedia.Media.AVImageGenerator
7757
7758**Parameters**
7759
7760| Name  | Type                                        | Mandatory| Description                               |
7761| -------- | -------------------------------------------- | ---- | ----------------------------------- |
7762| timeUs | number                   | Yes  | Time of the video for which a thumbnail is to be obtained, in μs.|
7763| options | [AVImageQueryOptions](#avimagequeryoptions12)     | Yes  | Relationship between the time passed in and the video frame.|
7764| param | [PixelMapParams](#pixelmapparams12)     | Yes  | Format parameters of the thumbnail to be obtained.|
7765| callback | AsyncCallback\<[image.PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)>   | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the **PixelMap** instance obtained; otherwise, **err** is an error object.|
7766
7767**Error codes**
7768
7769For details about the error codes, see [Media Error Codes](errorcode-media.md).
7770
7771| ID| Error Message                                  |
7772| -------- | ------------------------------------------ |
7773| 5400102  | Operation not allowed. Returned by callback. |
7774| 5400106  | Unsupported format. Returned by callback.  |
7775
7776**Example**
7777
7778```ts
7779import { BusinessError } from '@kit.BasicServicesKit';
7780import { image } from '@kit.ImageKit';
7781
7782let avImageGenerator: media.AVImageGenerator | undefined = undefined;
7783let pixel_map : image.PixelMap | undefined = undefined;
7784
7785// Initialize input parameters.
7786let timeUs: number = 0
7787
7788let queryOption: media.AVImageQueryOptions = media.AVImageQueryOptions.AV_IMAGE_QUERY_NEXT_SYNC
7789
7790let param: media.PixelMapParams = {
7791  width : 300,
7792  height : 300,
7793}
7794
7795// Obtain the thumbnail.
7796media.createAVImageGenerator((err: BusinessError, generator: media.AVImageGenerator) => {
7797  if(generator != null){
7798    avImageGenerator = generator;
7799    console.info(`Succeeded in creating AVImageGenerator`);
7800    avImageGenerator.fetchFrameByTime(timeUs, queryOption, param, (error: BusinessError, pixelMap) => {
7801      if (error) {
7802        console.error(`Failed to fetch FrameByTime, err = ${JSON.stringify(error)}`)
7803        return
7804      }
7805      pixel_map = pixelMap;
7806    });
7807  } else {
7808    console.error(`Failed to creat AVImageGenerator, error message:${err.message}`);
7809  };
7810});
7811```
7812
7813### fetchFrameByTime<sup>12+</sup>
7814
7815fetchFrameByTime(timeUs: number, options: AVImageQueryOptions, param: PixelMapParams): Promise<image.PixelMap>
7816
7817Obtains a video thumbnail. This API uses a promise to return the result.
7818
7819**System capability**: SystemCapability.Multimedia.Media.AVImageGenerator
7820
7821**Parameters**
7822
7823| Name  | Type                                        | Mandatory| Description                               |
7824| -------- | -------------------------------------------- | ---- | ----------------------------------- |
7825| timeUs | number                   | Yes  | Time of the video for which a thumbnail is to be obtained, in μs.|
7826| options | [AVImageQueryOptions](#avimagequeryoptions12)     | Yes  | Relationship between the time passed in and the video frame.|
7827| param | [PixelMapParams](#pixelmapparams12)    | Yes  | Format parameters of the thumbnail to be obtained.|
7828
7829**Return value**
7830
7831| Type          | Description                                    |
7832| -------------- | ---------------------------------------- |
7833| Promise\<[image.PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)> | Promise used to return the video thumbnail.|
7834
7835**Error codes**
7836
7837For details about the error codes, see [Media Error Codes](errorcode-media.md).
7838
7839| ID| Error Message                                 |
7840| -------- | ----------------------------------------- |
7841| 5400102  | Operation not allowed. Returned by promise. |
7842| 5400106  | Unsupported format. Returned by promise.  |
7843
7844**Example**
7845
7846```ts
7847import { BusinessError } from '@kit.BasicServicesKit';
7848import { image } from '@kit.ImageKit';
7849
7850let avImageGenerator: media.AVImageGenerator | undefined = undefined;
7851let pixel_map : image.PixelMap | undefined = undefined;
7852
7853// Initialize input parameters.
7854let timeUs: number = 0
7855
7856let queryOption: media.AVImageQueryOptions = media.AVImageQueryOptions.AV_IMAGE_QUERY_NEXT_SYNC
7857
7858let param: media.PixelMapParams = {
7859  width : 300,
7860  height : 300,
7861}
7862
7863// Obtain the thumbnail.
7864media.createAVImageGenerator((err: BusinessError, generator: media.AVImageGenerator) => {
7865  if(generator != null){
7866    avImageGenerator = generator;
7867    console.info(`Succeeded in creating AVImageGenerator`);
7868    avImageGenerator.fetchFrameByTime(timeUs, queryOption, param).then((pixelMap: image.PixelMap) => {
7869      pixel_map = pixelMap;
7870    }).catch((error: BusinessError) => {
7871      console.error(`Failed to fetch FrameByTime, error message:${error.message}`);
7872    });
7873  } else {
7874    console.error(`Failed to creat AVImageGenerator, error message:${err.message}`);
7875  };
7876});
7877```
7878
7879### release<sup>12+</sup>
7880
7881release(callback: AsyncCallback\<void>): void
7882
7883Releases this **AVMetadataExtractor** instance. This API uses an asynchronous callback to return the result.
7884
7885**System capability**: SystemCapability.Multimedia.Media.AVImageGenerator
7886
7887**Parameters**
7888
7889| Name  | Type                                        | Mandatory| Description                               |
7890| -------- | -------------------------------------------- | ---- | ----------------------------------- |
7891| callback | AsyncCallback\<void>                   | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
7892
7893**Error codes**
7894
7895For details about the error codes, see [Media Error Codes](errorcode-media.md).
7896
7897| ID| Error Message                                  |
7898| -------- | ------------------------------------------ |
7899| 5400102  | Operation not allowed. Returned by callback. |
7900
7901**Example**
7902
7903```ts
7904import { BusinessError } from '@kit.BasicServicesKit';
7905
7906let avImageGenerator: media.AVImageGenerator | undefined = undefined;
7907
7908// Release the resources.
7909media.createAVImageGenerator((err: BusinessError, generator: media.AVImageGenerator) => {
7910  if(generator != null){
7911    avImageGenerator = generator;
7912    console.info(`Succeeded in creating AVImageGenerator`);
7913    avImageGenerator.release((error: BusinessError) => {
7914      if (error) {
7915        console.error(`Failed to release, err = ${JSON.stringify(error)}`);
7916        return;
7917      }
7918      console.info(`Succeeded in releasing`);
7919    });
7920  } else {
7921    console.error(`Failed to creat AVImageGenerator, error message:${err.message}`);
7922  };
7923});
7924```
7925
7926### release<sup>12+</sup>
7927
7928release(): Promise\<void>
7929
7930Releases this **AVMetadataExtractor** instance. This API uses a promise to return the result.
7931
7932**System capability**: SystemCapability.Multimedia.Media.AVImageGenerator
7933
7934**Return value**
7935
7936| Type          | Description                                    |
7937| -------------- | ---------------------------------------- |
7938| Promise\<void> | Promise that returns no value.|
7939
7940**Error codes**
7941
7942For details about the error codes, see [Media Error Codes](errorcode-media.md).
7943
7944| ID| Error Message                                 |
7945| -------- | ----------------------------------------- |
7946| 5400102  | Operation not allowed. Returned by promise. |
7947
7948**Example**
7949
7950```ts
7951import { BusinessError } from '@kit.BasicServicesKit';
7952
7953let avImageGenerator: media.AVImageGenerator | undefined = undefined;
7954
7955// Release the instance.
7956media.createAVImageGenerator((err: BusinessError, generator: media.AVImageGenerator) => {
7957  if(generator != null){
7958    avImageGenerator = generator;
7959    console.info(`Succeeded in creating AVImageGenerator`);
7960    avImageGenerator.release().then(() => {
7961      console.info(`Succeeded in releasing.`);
7962    }).catch((error: BusinessError) => {
7963      console.error(`Failed to release, error message:${error.message}`);
7964    });
7965  } else {
7966    console.error(`Failed to creat AVImageGenerator, error message:${err.message}`);
7967  };
7968});
7969```
7970
7971## AVImageQueryOptions<sup>12+</sup>
7972
7973Enumerates the relationship between the video frame and the time at which the video thumbnail is obtained.
7974
7975The time passed in for obtaining the thumbnail may be different from the time of the video frame for which the thumbnail is actually obtained. Therefore, you need to specify their relationship.
7976
7977**System capability**: SystemCapability.Multimedia.Media.AVImageGenerator
7978
7979| Name                    | Value             | Description                                                        |
7980| ------------------------ | --------------- | ------------------------------------------------------------ |
7981| AV_IMAGE_QUERY_NEXT_SYNC       | 0   | The key frame at or next to the specified time is selected.                      |
7982| AV_IMAGE_QUERY_PREVIOUS_SYNC        | 1    | The key frame at or prior to the specified time is selected.|
7983| AV_IMAGE_QUERY_CLOSEST_SYNC        | 2    | The key frame closest to the specified time is selected.                |
7984| AV_IMAGE_QUERY_CLOSEST             | 3    | The frame (not necessarily a key frame) closest to the specified time is selected.|
7985
7986## PixelMapParams<sup>12+</sup>
7987
7988Defines the format parameters of the video thumbnail to be obtained.
7989
7990**System capability**: SystemCapability.Multimedia.Media.AVImageGenerator
7991
7992| Name  | Type  | Readable| Writable| Description                                                                           |
7993|--------|--------|------|------|---------------------------------------------------------------------------------|
7994| width  | number | Yes  | Yes  | Width of the thumbnail. The value must be greater than 0 and less than or equal to the width of the original video. Otherwise, the returned thumbnail will not be scaled.|
7995| height | number | Yes  | Yes  | Height of the thumbnail. The value must be greater than 0 and less than or equal to the height of the original video. Otherwise, the returned thumbnail will not be scaled.|
7996
7997## media.createMediaSourceWithUrl<sup>12+</sup>
7998
7999createMediaSourceWithUrl(url: string, headers?: Record\<string, string>): MediaSource
8000
8001Creates a media source for streaming media to be pre-downloaded.
8002
8003**Atomic service API**: This API can be used in atomic services since API version 13.
8004
8005**System capability**: SystemCapability.Multimedia.Media.Core
8006
8007**Parameters**
8008
8009| Name  | Type    | Mandatory| Description                |
8010| -------- | -------- | ---- | -------------------- |
8011| url | string | Yes  | - URL of the media source. The following streaming media formats are supported: HLS, HTTP-FLV, DASH, and HTTPS.<br> - FD path of the local M3U8 file. |
8012| headers | Record\<string, string> | No  | HTTP header customized for streaming media pre-download.|
8013
8014**Return value**
8015
8016| Type          | Description                                      |
8017| -------------- | ------------------------------------------ |
8018| [MediaSource](#mediasource12) | **MediaSource** instance.|
8019
8020**Error codes**
8021
8022For details about the error codes, see [Media Error Codes](errorcode-media.md).
8023
8024| ID| Error Message                                 |
8025| -------- | ----------------------------------------- |
8026| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed.      |
8027| 5400101  | No memory.  |
8028
8029**Example 1**
8030
8031```ts
8032let headers: Record<string, string> = {"User-Agent" : "User-Agent-Value"};
8033let mediaSource : media.MediaSource = media.createMediaSourceWithUrl("http://xxx",  headers);
8034```
8035
8036**Example 2**
8037
8038<!--code_no_check-->
8039```ts
8040import { common } from '@kit.AbilityKit';
8041import { resourceManager } from '@kit.LocalizationKit';
8042
8043let context = getContext(this) as common.UIAbilityContext;
8044let mgr = context.resourceManager;
8045let fileDescriptor = await mgr.getRawFd("xxx.m3u8");
8046
8047let fd:string = fileDescriptor.fd.toString();
8048let offset:string = fileDescriptor.offset.toString();
8049let length:string = fileDescriptor.length.toString();
8050let fdUrl:string = "fd://" + fd + "?offset=" + offset + "&size=" + length;
8051
8052let headers: Record<string, string> = {"User-Agent" : "User-Agent-Value"};
8053let mediaSource : media.MediaSource = media.createMediaSourceWithUrl(fdUrl,  headers);
8054
8055let mimeType : media.AVMimeTypes = media.AVMimeTypes.APPLICATION_M3U8;
8056mediaSource.setMimeType(mimeType);
8057
8058```
8059
8060## MediaSource<sup>12+</sup>
8061
8062Defines the media data information, which is from [createMediaSourceWithUrl](#mediacreatemediasourcewithurl12).
8063
8064**System capability**: SystemCapability.Multimedia.Media.Core
8065
8066### setMimeType<sup>12+</sup>
8067
8068setMimeType(mimeType: AVMimeTypes): void
8069
8070Sets the MIME type to help the player process extended media sources.
8071
8072**Atomic service API**: This API can be used in atomic services since API version 12.
8073
8074**System capability**: SystemCapability.Multimedia.Media.Core
8075
8076**Parameters**
8077
8078| Name  | Type    | Mandatory| Description                |
8079| -------- | -------- | ---- | -------------------- |
8080| mimeType | [AVMimeTypes](#mediasource12) | Yes  | MIME type.|
8081
8082### setMediaResourceLoaderDelegate<sup>18+</sup>
8083
8084setMediaResourceLoaderDelegate(resourceLoader: MediaSourceLoader): void
8085
8086Sets a **MediaSourceLoader** object, which is used to help the player request media data.
8087
8088**Atomic service API**: This API can be used in atomic services since API version 18.
8089
8090**System capability**: SystemCapability.Multimedia.Media.Core
8091
8092**Parameters**
8093
8094| Name  | Type    | Mandatory| Description                |
8095| -------- | -------- | ---- | -------------------- |
8096| resourceLoader | [MediaSourceLoader](#mediasourceloader18) | Yes  | **MediaSourceLoader** object used to obtain media data for the player.|
8097
8098**Example**
8099
8100```ts
8101import { BusinessError } from '@kit.BasicServicesKit';
8102
8103let headers: Record<string, string> = {"User-Agent" : "User-Agent-Value"};
8104let mediaSource : media.MediaSource = media.createMediaSourceWithUrl("http://xxx",  headers);
8105
8106// Implemented by applications as required.
8107let resourceLoader: media.MediaSourceLoader = {
8108  open: SourceOpenCallback,
8109  read: SourceReadCallback,
8110  close: SourceCloseCallback
8111};
8112
8113mediaSource.setMediaResourceLoaderDelegate(resourceLoader);
8114```
8115
8116## SourceOpenCallback<sup>18+</sup>
8117
8118type SourceOpenCallback = (request: MediaSourceLoadingRequest) => number
8119
8120This callback function is implemented by applications to handle resource open requests and return a unique handle for the opened resource.
8121
8122> **NOTE**
8123>
8124> The client must return the handle immediately after processing the request.
8125
8126**Atomic service API**: This API can be used in atomic services since API version 18.
8127
8128**System capability**: SystemCapability.Multimedia.Media.Core
8129
8130**Parameters**
8131
8132| Name  | Type    | Mandatory| Description                |
8133| -------- | -------- | ---- | -------------------- |
8134| request | [MediaSourceLoadingRequest](#mediasourceloadingrequest18) | Yes | 	Parameters for the resource open request, including detailed information about the requested resource and the data push method.|
8135
8136**Return value**
8137
8138| Type  | Description                |
8139| -------- | -------------------- |
8140| number  | Handle for the current resource open request. A value greater than 0 means the request is successful, whereas a value less than or equal to 0 means it fails.<br> - The handle for the request object is unique.|
8141
8142**Example**
8143
8144```ts
8145import HashMap from '@ohos.util.HashMap';
8146
8147let uuid: number = 1;
8148let requests: HashMap<number, media.MediaSourceLoadingRequest> = new HashMap();
8149
8150let sourceOpenCallback: media.SourceOpenCallback = (request: media.MediaSourceLoadingRequest) => {
8151  console.log(`Opening resource: ${request.url}`);
8152  // Open the resource and return a unique handle, ensuring the mapping between the UUID and request.
8153  uuid += 1;
8154  requests.set(uuid, request);
8155  return uuid;
8156}
8157```
8158
8159## SourceReadCallback<sup>18+</sup>
8160
8161type SourceReadCallback = (uuid: number, requestedOffset: number, requestedLength: number) => void
8162
8163This callback function is implemented by applications to handle resource read requests. When data is available, applications should push it to the player using the [respondData](#responddata18) API of the corresponding **MediaSourceLoadingRequest** object.
8164
8165> **NOTE**
8166>
8167> The client must return the handle immediately after processing the request.
8168
8169**Atomic service API**: This API can be used in atomic services since API version 18.
8170
8171**System capability**: SystemCapability.Multimedia.Media.Core
8172
8173**Parameters**
8174
8175| Name  | Type    | Mandatory| Description                |
8176| -------- | -------- | ---- | -------------------- |
8177| uuid | number | Yes | 	ID for the resource handle.|
8178| requestedOffset | number | Yes | 	Offset of the current media data relative to the start of the resource.|
8179| requestedLength | number | Yes | 	Length of the current request. The value **-1** indicates reaching the end of the resource. After pushing the data, call [finishLoading](#finishloading18) to notify the player that the push is complete.|
8180
8181**Example**
8182
8183```ts
8184let sourceReadCallback: media.SourceReadCallback = (uuid: number, requestedOffset: number, requestedLength: number) => {
8185  console.log(`Reading resource with handle ${uuid}, offset: ${requestedOffset}, length: ${requestedLength}`);
8186  // Check whether the UUID is valid and store the read request. Avoid blocking the request while pushing data and header information.
8187}
8188```
8189
8190## SourceCloseCallback<sup>18+</sup>
8191
8192type SourceCloseCallback = (uuid: number) => void
8193
8194This callback function is implemented by applications to release related resources.
8195
8196> **NOTE**
8197>
8198> The client must return the handle immediately after processing the request.
8199
8200**Atomic service API**: This API can be used in atomic services since API version 18.
8201
8202**System capability**: SystemCapability.Multimedia.Media.Core
8203
8204**Parameters**
8205
8206| Name  | Type    | Mandatory| Description                |
8207| -------- | -------- | ---- | -------------------- |
8208| uuid      | number | Yes | 	ID for the resource handle.|
8209
8210**Example**
8211
8212```ts
8213import HashMap from '@ohos.util.HashMap';
8214
8215let requests: HashMap<number, media.MediaSourceLoadingRequest> = new HashMap();
8216
8217let sourceCloseCallback: media.SourceCloseCallback = (uuid: number) => {
8218  console.log(`Closing resource with handle ${uuid}`);
8219  // Clear resources related to the current UUID.
8220  requests.remove(uuid);
8221}
8222```
8223
8224## MediaSourceLoader<sup>18+</sup>
8225
8226Defines a media data loader, which needs to be implemented by applications.
8227
8228**Atomic service API**: This API can be used in atomic services since API version 18.
8229
8230**System capability**: SystemCapability.Multimedia.Media.Core
8231
8232| Name  | Type    | Mandatory| Description                |
8233| -------- | -------- | ---- | -------------------- |
8234| open | [SourceOpenCallback](#sourceopencallback18) | Yes | Callback function implemented by applications to handle resource open requests.|
8235| read | [SourceReadCallback](#sourcereadcallback18) | Yes | Callback function implemented by applications to handle resource read requests.|
8236| close | [SourceCloseCallback](#sourceclosecallback18) | Yes | Callback function implemented by applications to handle resource close requests.|
8237
8238**Example**
8239
8240```ts
8241import HashMap from '@ohos.util.HashMap';
8242
8243let headers: Record<string, string> = {"User-Agent" : "User-Agent-Value"};
8244let mediaSource : media.MediaSource = media.createMediaSourceWithUrl("http://xxx",  headers);
8245let uuid: number = 1;
8246let requests: HashMap<number, media.MediaSourceLoadingRequest> = new HashMap();
8247let mediaSourceLoader: media.MediaSourceLoader = {
8248  open: (request: media.MediaSourceLoadingRequest) => {
8249    console.log(`Opening resource: ${request.url}`);
8250    // Open the resource and return a unique handle, ensuring the mapping between the UUID and request.
8251    uuid += 1;
8252    requests.set(uuid, request);
8253    return uuid;
8254  },
8255  read: (uuid: number, requestedOffset: number, requestedLength: number) => {
8256    console.log(`Reading resource with handle ${uuid}, offset: ${requestedOffset}, length: ${requestedLength}`);
8257    // Check whether the UUID is valid and store the read request. Avoid blocking the request while pushing data and header information.
8258  },
8259  close: (uuid: number) => {
8260    console.log(`Closing resource with handle ${uuid}`);
8261    // Clear resources related to the current UUID.
8262    requests.remove(uuid);
8263  }
8264};
8265
8266mediaSource.setMediaResourceLoaderDelegate(mediaSourceLoader);
8267let playStrategy : media.PlaybackStrategy = {
8268  preferredBufferDuration: 20,
8269};
8270let player = await media.createAVPlayer();
8271player.setMediaSource(mediaSource, playStrategy);
8272```
8273
8274## MediaSourceLoadingRequest<sup>18+</sup>
8275
8276Defines a loading request object. Applications use this object to obtain the location of the requested resource and to interact with the player for data exchange.
8277
8278**Atomic service API**: This API can be used in atomic services since API version 18.
8279
8280### Attributes
8281
8282**System capability**: SystemCapability.Multimedia.Media.Core
8283
8284| Name  | Type   | Read-Only  | Optional  | Description               |
8285| --------------------------------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ |
8286| url<sup>18+</sup>        | string                        | No  | No  | Resource URL, which is the path to the resource that the application needs to open.|
8287| header<sup>18+</sup>     | Record<string, string>        | No  | Yes  | HTTP request header. If the header exists, the application should set the header information in the HTTP request when downloading data.|
8288
8289### respondData<sup>18+</sup>
8290
8291respondData(uuid: number, offset: number, buffer: ArrayBuffer): number
8292
8293Sends data to the player.
8294
8295**Atomic service API**: This API can be used in atomic services since API version 18.
8296
8297**System capability**: SystemCapability.Multimedia.Media.Core
8298
8299**Parameters**
8300
8301| Name  | Type    | Mandatory| Description                |
8302| -------- | -------- | ---- | -------------------- |
8303| uuid | number | Yes | 	ID for the resource handle.|
8304| offset | number | Yes | 	Offset of the current media data relative to the start of the resource.|
8305| buffer | ArrayBuffer | Yes | 	Media data sent to the player.<br>**Note**: Do not transmit irrelevant data, as it can affect normal data parsing and playback.|
8306
8307**Return value**
8308
8309| Type          | Description                               |
8310| -------------- | ----------------------------------- |
8311| number | Number of bytes received by the server.<br>- A return value less than 0 indicates failure.<br>- A return value of -2 indicates that the player no longer needs the current data, and the client should stop the current read process.<br>- A return value of -3 indicates that the player's buffer is full, and the client should wait for the next read.|
8312
8313**Example**
8314
8315```ts
8316let requests: HashMap<number, media.MediaSourceLoadingRequest> = new HashMap();
8317let uuid = 1;
8318
8319let request = requests.get(uuid);
8320let num = request.respondData(uuid, offset, buf);
8321```
8322
8323### respondHeader<sup>18+</sup>
8324
8325respondHeader(uuid: number, header?: Record<string, string>, redirectUrl?: string): void
8326
8327Sends response header information to the player. This API must be called before the first call to [respondData](#responddata18).
8328
8329**Atomic service API**: This API can be used in atomic services since API version 18.
8330
8331**System capability**: SystemCapability.Multimedia.Media.Core
8332
8333**Parameters**
8334
8335| Name  | Type    | Mandatory| Description                |
8336| -------- | -------- | ---- | -------------------- |
8337| uuid | number | Yes | 	ID for the resource handle.|
8338| header | Record<string, string> | No | Header information in the HTTP response. The application can intersect the header fields with the fields supported by the underlying layer for parsing or directly pass in all corresponding header information.<br> - The following fields need to be parsed by the underlying player: Transfer-Encoding, Location, Content-Type, Content-Range, Content-Encode, Accept-Ranges, and content-length.|
8339| redirectUrl | string | No | 	Redirect URL in the HTTP response.|
8340
8341**Example**
8342
8343```ts
8344let requests: HashMap<number, media.MediaSourceLoadingRequest> = new HashMap();
8345let uuid = 1;
8346
8347// The application fills this in as needed.
8348let header:Record<string, string> = {
8349  'Transfer-Encoding':'xxx',
8350  'Location' : 'xxx',
8351  'Content-Type' : 'xxx',
8352  'Content-Range' : 'xxx',
8353  'Content-Encode' : 'xxx',
8354  'Accept-Ranges' : 'xxx',
8355  'content-length' : 'xxx'
8356};
8357let request = requests.get(uuid);
8358request.respondHeader(uuid, header);
8359```
8360
8361### finishLoading<sup>18+</sup>
8362
8363finishLoading(uuid: number, state: LoadingRequestError): void
8364
8365Notifies the player of the current request status. After pushing all the data for a single resource, the application should send the **LOADING_ERROR_SUCCESS** state to notify the player that the resource push is complete.
8366
8367**Atomic service API**: This API can be used in atomic services since API version 18.
8368
8369**System capability**: SystemCapability.Multimedia.Media.Core
8370
8371**Parameters**
8372
8373| Name  | Type    | Mandatory| Description                |
8374| -------- | -------- | ---- | -------------------- |
8375| uuid | number | Yes | 	ID for the resource handle.|
8376| state  | [LoadingRequestError](#loadingrequesterror18) | Yes | Request status.|
8377
8378**Example**
8379
8380```ts
8381let requests: HashMap<number, media.MediaSourceLoadingRequest> = new HashMap();
8382let uuid = 1;
8383
8384let request = requests.get(uuid);
8385let loadingError = media.LoadingRequestError.LOADING_ERROR_SUCCESS;
8386request.finishLoading(uuid, loadingError);
8387```
8388
8389## LoadingRequestError<sup>18+</sup>
8390
8391Enumerates the reasons for data loading status changes.
8392
8393**Atomic service API**: This API can be used in atomic services since API version 18.
8394
8395**System capability**: SystemCapability.Multimedia.Media.Core
8396
8397| Name                | Value  | Description                          |
8398| -------------------- | ---- | ------------------------------ |
8399| LOADING_ERROR_SUCCESS | 0    | Returned by the client to indicate that the end of the resource.|
8400| LOADING_ERROR_NOT_READY | 1    | Returned by the client to indicate that the resource is not ready for access.|
8401| LOADING_ERROR_NO_RESOURCE | 2    | Returned by the client to indicate that the requested resource URL does not exist.|
8402| LOADING_ERROR_INVAID_HANDLE | 3    | Returned by the client to indicate that the ID of the requested resource handle (specified by **uuid**) is invalid.|
8403| LOADING_ERROR_ACCESS_DENIED | 4    | Returned by the client to indicate that the client does not have permission to request the resource.|
8404| LOADING_ERROR_ACCESS_TIMEOUT | 5    | Returned by the client to indicate that the access to the resource times out.|
8405| LOADING_ERROR_AUTHORIZE_FAILED | 6    | Returned by the client to indicate that authorization fails.|
8406
8407## AVMimeTypes<sup>12+</sup>
8408
8409Enumerates the MIME type, which is set by using [setMimeType](#setmimetype12).
8410
8411**Atomic service API**: This API can be used in atomic services since API version 12.
8412
8413**System capability**: SystemCapability.Multimedia.Media.Core
8414
8415
8416| Name      | Value  | Description                                                        |
8417| ---------- | ---- | ------------------------------------------------------------ |
8418| APPLICATION_M3U8       | application/m3u8    | Local M3U8 file.|
8419
8420
8421## PlaybackStrategy<sup>12+</sup>
8422
8423Describes the playback strategy.
8424
8425**System capability**: SystemCapability.Multimedia.Media.Core
8426
8427| Name | Type    | Mandatory| Description                |
8428| -------- | -------- | ---- | -------------------- |
8429| preferredWidth| number | No  | Preferred width, in px. The value is an integer greater than 0, for example, 1080.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
8430| preferredHeight | number | No  | Preferred height, in px. The value is an integer greater than 0, for example, 1920.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
8431| preferredBufferDuration | number | No | Preferred buffer duration, in seconds. The value ranges from 1 to 20.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
8432| preferredHdr | boolean | No  | Whether HDR is preferred. The value **true** means that HDR is preferred, and **false** means the opposite.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
8433| enableSuperResolution<sup>18+</sup> | boolean | No  | Whether to enable super resolution. The value **true** means to enable it, and **false** (default) means to disable it.<br>If super resolution is disabled, super resolution APIs cannot be called. If super resolution is enabled, the default target resolution is 1920 x 1080, in px.<br>**Atomic service API**: This API can be used in atomic services since API version 18.|
8434| showFirstFrameOnPrepare<sup>17+</sup> | boolean | No  | Whether to show the first frame after **prepare** is called. The value **true** means to show the first frame after **prepare** is called, and **false** means the opposite. The default value is **false**.<br>**Atomic service API**: This API can be used in atomic services since API version 17.|
8435| mutedMediaType | [MediaType](#mediatype8) | No| Media type for muted playback. Only **MediaType.MEDIA_TYPE_AUD** can be set.|
8436| preferredAudioLanguage<sup>13+</sup> | string | No| Preferred audio track language. Set this parameter based on service requirements in DASH scenarios. In non-DASH scenarios, this parameter is not supported, and you are advised to retain the default value.<br>**Atomic service API**: This API can be used in atomic services since API version 13.|
8437| preferredSubtitleLanguage<sup>13+</sup> | string | No| Preferred subtitle language. Set this parameter based on service requirements in DASH scenarios. In non-DASH scenarios, this parameter is not supported, and you are advised to retain the default value.<br>**Atomic service API**: This API can be used in atomic services since API version 13.|
8438| preferredBufferDurationForPlaying<sup>18+</sup> | number | No| Preferred buffer duration for playback. The playback starts once the buffering time exceeds this value. The value ranges from 0 to 20, in seconds.<br>**Atomic service API**: This API can be used in atomic services since API version 18.|
8439| thresholdForAutoQuickPlay<sup>18+</sup> | number | No| Thread for starting smart frame catching, in seconds. The value must be greater than or equal to 2s and greater than **preferredBufferDurationForPlaying**. The default value is 5s.     <br>You can use the playback strategy to maintain the real-time quality of live streams by adjusting the smart frame-catch threshold. For FLV live streams, you can set this parameter based on service requirements. This parameter is not supported for non-FLV live streams yet. Fluctuations in network conditions can cause the player to build up a lot of data over time. The player periodically checks the gap between the current playback time and the timestamp of the latest frame in the cache. If this gap is too big, the player starts catching up at 1.2x speed. Once the gap falls below **preferredBufferDurationForPlaying**, the player stops catching up and resumes the normal playback speed.<br>**Atomic service API**: This API can be used in atomic services since API version 18.|
8440
8441## AVScreenCaptureRecordPreset<sup>12+</sup>
8442
8443Enumerates the encoding and container formats used during screen capture.
8444
8445**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture
8446
8447| Name                             | Value  | Description                                        |
8448| --------------------------------- | ---- | -------------------------------------------- |
8449| SCREEN_RECORD_PRESET_H264_AAC_MP4 | 0    | The H.264 video encoding format, AAC audio encoding format, and MP4 container format are used.|
8450| SCREEN_RECORD_PRESET_H265_AAC_MP4 | 1    | The H.265 video encoding format, AAC audio encoding format, and MP4 container format are used.|
8451
8452## AVScreenCaptureStateCode<sup>12+</sup>
8453
8454Enumerates the screen capture states used in callbacks.
8455
8456**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture
8457
8458| Name                                    | Value  | Description                    |
8459| ---------------------------------------- | ---- | ------------------------ |
8460| SCREENCAPTURE_STATE_STARTED              | 0    | Screen capture is started.            |
8461| SCREENCAPTURE_STATE_CANCELED             | 1    | Screen capture is canceled.            |
8462| SCREENCAPTURE_STATE_STOPPED_BY_USER      | 2    | Screen capture is manually stopped by the user.    |
8463| SCREENCAPTURE_STATE_INTERRUPTED_BY_OTHER | 3    | Screen capture is interrupted by another screen capture.    |
8464| SCREENCAPTURE_STATE_STOPPED_BY_CALL      | 4    | Screen capture is interrupted by an incoming call.        |
8465| SCREENCAPTURE_STATE_MIC_UNAVAILABLE      | 5    | The microphone is unavailable during screen capture.|
8466| SCREENCAPTURE_STATE_MIC_MUTED_BY_USER    | 6    | The microphone is muted by the user.      |
8467| SCREENCAPTURE_STATE_MIC_UNMUTED_BY_USER  | 7    | The microphone is unmuted by the user.      |
8468| SCREENCAPTURE_STATE_ENTER_PRIVATE_SCENE  | 8    | The system enters a privacy page during screen capture.      |
8469| SCREENCAPTURE_STATE_EXIT_PRIVATE_SCENE   | 9    | The system exits a privacy page during screen capture.      |
8470| SCREENCAPTURE_STATE_STOPPED_BY_USER_SWITCHES   | 10    | Screen capture is interrupted by system user switchover.      |
8471
8472## AVScreenCaptureFillMode<sup>18+</sup>
8473
8474Enumerates the video fill modes during screen capture.
8475
8476**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture
8477
8478| Name                             | Value  | Description                                        |
8479| --------------------------------- | ---- | -------------------------------------------- |
8480| PRESERVE_ASPECT_RATIO | 0    | Keeps the original aspect ratio, matching the aspect ratio of the physical screen.|
8481| SCALE_TO_FILL | 1    | Stretches the image to fit the specified dimensions.|
8482
8483## AVScreenCaptureRecordConfig<sup>12+</sup>
8484
8485Defines the screen capture parameters.
8486
8487**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture
8488
8489| Name             | Type                                                        | Mandatory| Description                                                        |
8490| ----------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
8491| fd                | number                                                       | Yes  | FD of the file output.                                          |
8492| frameWidth        | number                                                       | No  | Video width, in px. The default value varies according to the display in use.|
8493| frameHeight       | number                                                       | No  | Video height, in px. The default value varies according to the display in use.|
8494| videoBitrate      | number                                                       | No  | Video bit rate. The default value is **10000000**.                            |
8495| audioSampleRate   | number                                                       | No  | Audio sampling rate. This value is used for both internal capture and external capture (using microphones). Only **48000** (default value) and **16000** are supported.|
8496| audioChannelCount | number                                                       | No  | Number of audio channels. This value is used for both internal capture and external capture (using microphones). Only **1** and **2** (default) are supported.|
8497| audioBitrate      | number                                                       | No  | Audio bit rate. This value is used for both internal capture and external capture (using microphones). The default value is **96000**.|
8498| preset            | [AVScreenCaptureRecordPreset](#avscreencapturerecordpreset12) | No  | Encoding and container format used. The default value is **SCREEN_RECORD_PRESET_H264_AAC_MP4**.|
8499| displayId<sup>15+</sup>            | number | No  | ID of the display used for screen capture. By default, the main screen is captured.|
8500| fillMode<sup>18+</sup>            | [AVScreenCaptureFillMode](#avscreencapturefillmode18)| No  | Video fill mode during screen capture.|
8501
8502## AVScreenCaptureRecorder<sup>12+</sup>
8503
8504Provides APIs to manage screen capture. Before calling any API in **AVScreenCaptureRecorder**, you must use [createAVScreenCaptureRecorder()](#mediacreateavscreencapturerecorder12) to create an **AVScreenCaptureRecorder** instance.
8505
8506### init<sup>12+</sup>
8507
8508init(config: AVScreenCaptureRecordConfig): Promise\<void>
8509
8510Initializes screen capture and sets screen capture parameters. This API uses a promise to return the result.
8511
8512**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture
8513
8514**Parameters**
8515
8516| Name| Type                                                        | Mandatory| Description                    |
8517| ------ | ------------------------------------------------------------ | ---- | ------------------------ |
8518| config | [AVScreenCaptureRecordConfig](#avscreencapturerecordconfig12) | Yes  | Screen capture parameters to set.|
8519
8520**Return value**
8521
8522| Type          | Description                               |
8523| -------------- | ----------------------------------- |
8524| Promise\<void> | Promise that returns no value.|
8525
8526**Error codes**
8527
8528| ID| Error Message                                      |
8529| -------- | ---------------------------------------------- |
8530| 401      | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. Return by promise. |
8531| 5400103  | IO error. Return by promise.                   |
8532| 5400105  | Service died. Return by promise.               |
8533
8534**Example**
8535
8536```ts
8537import { BusinessError } from '@kit.BasicServicesKit';
8538
8539let avCaptureConfig: media.AVScreenCaptureRecordConfig = {
8540    fd: 0, // Before passing in an FD to this parameter, the file must be created by the caller and granted with the write permissions.
8541    frameWidth: 640,
8542    frameHeight: 480
8543    // Add other parameters.
8544}
8545
8546avScreenCaptureRecorder.init(avCaptureConfig).then(() => {
8547    console.info('Succeeded in initing avScreenCaptureRecorder');
8548}).catch((err: BusinessError) => {
8549    console.info('Failed to init avScreenCaptureRecorder, error: ' + err.message);
8550})
8551```
8552
8553### startRecording<sup>12+</sup>
8554
8555startRecording(): Promise\<void>
8556
8557Starts screen capture. This API uses a promise to return the result.
8558
8559**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture
8560
8561**Return value**
8562
8563| Type          | Description                            |
8564| -------------- | -------------------------------- |
8565| Promise\<void> | Promise that returns no value.|
8566
8567**Error codes**
8568
8569| ID| Error Message                        |
8570| -------- | -------------------------------- |
8571| 5400103  | IO error. Return by promise.     |
8572| 5400105  | Service died. Return by promise. |
8573
8574**Example**
8575
8576```ts
8577import { BusinessError } from '@kit.BasicServicesKit';
8578
8579avScreenCaptureRecorder.startRecording().then(() => {
8580    console.info('Succeeded in starting avScreenCaptureRecorder');
8581}).catch((err: BusinessError) => {
8582    console.info('Failed to start avScreenCaptureRecorder, error: ' + err.message);
8583})
8584```
8585
8586### stopRecording<sup>12+</sup>
8587
8588stopRecording(): Promise\<void>
8589
8590Stops screen capture. This API uses a promise to return the result.
8591
8592**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture
8593
8594**Return value**
8595
8596| Type          | Description                             |
8597| -------------- | --------------------------------- |
8598| Promise\<void> | Promise that returns no value.|
8599
8600**Error codes**
8601
8602| ID| Error Message                        |
8603| -------- | -------------------------------- |
8604| 5400103  | IO error. Return by promise.     |
8605| 5400105  | Service died. Return by promise. |
8606
8607**Example**
8608
8609```ts
8610import { BusinessError } from '@kit.BasicServicesKit';
8611
8612avScreenCaptureRecorder.stopRecording().then(() => {
8613    console.info('Succeeded in stopping avScreenCaptureRecorder');
8614}).catch((err: BusinessError) => {
8615    console.info('Failed to stop avScreenCaptureRecorder, error: ' + err.message);
8616})
8617```
8618
8619### skipPrivacyMode<sup>12+</sup>
8620
8621skipPrivacyMode(windowIDs: Array\<number>): Promise\<void>
8622
8623During screen capture, the application can exempt its privacy windows from security purposes. This API uses a promise to return the result.
8624For example, if a user enters a password in this application during screen capture, the application will not display a black screen.
8625
8626**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture
8627
8628**Parameters**
8629
8630| Name| Type   | Mandatory| Description                                                     |
8631| ------ | ------- | ---- | --------------------------------------------------------- |
8632| windowIDs | Array\<number> | Yes  | IDs of windows that require privacy exemption, including the main window IDs and subwindow IDs. For details about how to obtain window properties, see [Window API Reference](../apis-arkui/js-apis-window.md#getwindowproperties9).|
8633
8634**Return value**
8635
8636| Type          | Description                            |
8637| -------------- | -------------------------------- |
8638| Promise\<void> | Promise used to return the window IDs.|
8639
8640**Error codes**
8641
8642| ID| Error Message                        |
8643| -------- | -------------------------------- |
8644| 5400103  | IO error. Return by promise.     |
8645| 5400105  | Service died. Return by promise. |
8646
8647**Example**
8648
8649```ts
8650import { BusinessError } from '@kit.BasicServicesKit';
8651
8652let windowIDs = [];
8653avScreenCaptureRecorder.skipPrivacyMode(windowIDs).then(() => {
8654    console.info('Succeeded in skipping privacy mode');
8655}).catch((err: BusinessError) => {
8656    console.info('Failed to skip privacy mode, error: ' + err.message);
8657})
8658```
8659
8660### setMicEnabled<sup>12+</sup>
8661
8662setMicEnabled(enable: boolean): Promise\<void>
8663
8664Enables or disables the microphone. This API uses a promise to return the result.
8665
8666**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture
8667
8668**Parameters**
8669
8670| Name| Type   | Mandatory| Description                                                     |
8671| ------ | ------- | ---- | --------------------------------------------------------- |
8672| enable | boolean | Yes  | Whether to enable or disable the microphone. The value **true** means to enable the microphone, and **false** means the opposite.|
8673
8674**Return value**
8675
8676| Type          | Description                                   |
8677| -------------- | --------------------------------------- |
8678| Promise\<void> | Promise that returns no value.|
8679
8680**Error codes**
8681
8682| ID| Error Message                        |
8683| -------- | -------------------------------- |
8684| 5400103  | IO error. Return by promise.     |
8685| 5400105  | Service died. Return by promise. |
8686
8687**Example**
8688
8689```ts
8690import { BusinessError } from '@kit.BasicServicesKit';
8691
8692avScreenCaptureRecorder.setMicEnabled(true).then(() => {
8693    console.info('Succeeded in setMicEnabled avScreenCaptureRecorder');
8694}).catch((err: BusinessError) => {
8695    console.info('Failed to setMicEnabled avScreenCaptureRecorder, error: ' + err.message);
8696})
8697```
8698
8699### release<sup>12+</sup>
8700
8701release(): Promise\<void>
8702
8703Releases this **AVScreenCaptureRecorder** instance. This API uses a promise to return the result.
8704
8705**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture
8706
8707**Return value**
8708
8709| Type          | Description                             |
8710| -------------- | --------------------------------- |
8711| Promise\<void> | Promise that returns no value.|
8712
8713**Error codes**
8714
8715| ID| Error Message                        |
8716| -------- | -------------------------------- |
8717| 5400103  | IO error. Return by promise.     |
8718| 5400105  | Service died. Return by promise. |
8719
8720**Example**
8721
8722```ts
8723import { BusinessError } from '@kit.BasicServicesKit';
8724
8725avScreenCaptureRecorder.release().then(() => {
8726    console.info('Succeeded in releasing avScreenCaptureRecorder');
8727}).catch((err: BusinessError) => {
8728    console.info('Faile to release avScreenCaptureRecorder, error: ' + err.message);
8729})
8730```
8731
8732### on('stateChange')<sup>12+</sup>
8733
8734on(type: 'stateChange', callback: Callback\<AVScreenCaptureStateCode>): void
8735
8736Subscribes to screen capture state changes. An application can subscribe to only one screen capture state change event. When the application initiates multiple subscriptions to this event, the last subscription is applied.
8737
8738**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture
8739
8740**Parameters**
8741
8742| Name  | Type    | Mandatory| Description                                                        |
8743| -------- | -------- | ---- | ------------------------------------------------------------ |
8744| type     | string   | Yes  | Event type, which is **'stateChange'** in this case.           |
8745| callback | function | Yes  | Callback invoked when the event is triggered. [AVScreenCaptureStateCode](#avscreencapturestatecode12) indicates the new state.|
8746
8747**Example**
8748
8749```ts
8750avScreenCaptureRecorder.on('stateChange', (state: media.AVScreenCaptureStateCode) => {
8751    console.info('avScreenCaptureRecorder stateChange to ' + state);
8752})
8753```
8754
8755### on('error')<sup>12+</sup>
8756
8757on(type: 'error', callback: ErrorCallback): void
8758
8759Subscribes to AVScreenCaptureRecorder errors. You can handle the errors based on the application logic. An application can subscribe to only one AVScreenCaptureRecorder error event. When the application initiates multiple subscriptions to this event, the last subscription is applied.
8760
8761**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture
8762
8763**Parameters**
8764
8765| Name  | Type         | Mandatory| Description                                   |
8766| -------- | ------------- | ---- | --------------------------------------- |
8767| type     | string        | Yes  | Event type, which is **'error'** in this case.|
8768| callback | [ErrorCallback](../apis-basic-services-kit/js-apis-base.md#errorcallback) | Yes  | Callback invoked when the event is triggered.                 |
8769
8770**Error codes**
8771
8772| ID| Error Message                        |
8773| -------- | -------------------------------- |
8774| 201      | permission denied.     |
8775| 5400103  | IO error. Return by ErrorCallback. |
8776| 5400105  | Service died. Return by ErrorCallback. |
8777
8778**Example**
8779
8780```ts
8781avScreenCaptureRecorder.on('error', (err: BusinessError) => {
8782    console.error('avScreenCaptureRecorder error:' + err.message);
8783})
8784```
8785
8786### off('stateChange')<sup>12+</sup>
8787
8788 off(type: 'stateChange', callback?: Callback\<AVScreenCaptureStateCode>): void
8789
8790Unsubscribes from screen capture state changes. You can specify a callback to cancel the specified subscription.
8791
8792**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture
8793
8794**Parameters**
8795
8796| Name  | Type    | Mandatory| Description                                                        |
8797| -------- | -------- | ---- | ------------------------------------------------------------ |
8798| type     | string   | Yes  | Event type, which is **'stateChange'** in this case.           |
8799| callback | function | No  | Callback used for unsubscription. [AVScreenCaptureStateCode](#avscreencapturestatecode12) indicates the new state. If this parameter is not specified, the last subscription is canceled.|
8800
8801**Example**
8802
8803```ts
8804avScreenCaptureRecorder.off('stateChange');
8805```
8806
8807### off('error')<sup>12+</sup>
8808
8809off(type: 'error', callback?: ErrorCallback): void
8810
8811Unsubscribes from AVScreenCaptureRecorder errors. You can specify a callback to cancel the specified subscription.
8812
8813**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture
8814
8815**Parameters**
8816
8817| Name  | Type    | Mandatory| Description                                                      |
8818| -------- | -------- | ---- | ---------------------------------------------------------- |
8819| type     | string   | Yes  | Event type, which is **'error'** in this case.               |
8820| callback | [ErrorCallback](../apis-basic-services-kit/js-apis-base.md#errorcallback) | No  | Callback used for unsubscription. If this parameter is not specified, the last subscription is canceled.|
8821
8822**Example**
8823
8824```ts
8825avScreenCaptureRecorder.off('error');
8826```
8827