• 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 | undefined = undefined;
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**Return value**
300
301| Type          | Description                                    |
302| -------------- | ---------------------------------------- |
303| Promise\<[AVMetadataExtractor](#avmetadataextractor11)>  | Promise used to return the AVMetadataExtractor instance.|
304
305**Error codes**
306
307For details about the error codes, see [Media Error Codes](errorcode-media.md).
308
309| ID| Error Message                      |
310| -------- | ------------------------------ |
311| 5400101  | No memory. Returned by promise. |
312
313**Example**
314
315```ts
316import { BusinessError } from '@kit.BasicServicesKit';
317
318let avMetadataExtractor: media.AVMetadataExtractor;
319media.createAVMetadataExtractor().then((extractor: media.AVMetadataExtractor) => {
320  if (extractor != null) {
321    avMetadataExtractor = extractor;
322    console.info('Succeeded in creating AVMetadataExtractor');
323  } else {
324    console.error(`Failed to create AVMetadataExtractor`);
325  }
326}).catch((error: BusinessError) => {
327  console.error(`Failed to create AVMetadataExtractor, error message:${error.message}`);
328});
329```
330
331## media.createSoundPool<sup>10+</sup>
332
333createSoundPool(maxStreams: number, audioRenderInfo: audio.AudioRendererInfo, callback: AsyncCallback\<SoundPool>): void
334
335Creates a SoundPool instance. This API uses an asynchronous callback to return the result.
336
337> **NOTE**
338>
339> - 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.
340> - 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.
341
342**System capability**: SystemCapability.Multimedia.Media.SoundPool
343
344**Parameters**
345
346| Name  | Type                                           | Mandatory| Description                                                        |
347| -------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ |
348| 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.|
349| 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.|
350| 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.|
351
352**Error codes**
353
354For details about the error codes, see [Media Error Codes](errorcode-media.md).
355
356| ID| Error Message                      |
357| -------- | ------------------------------ |
358| 5400101  | No memory. Return by callback. |
359
360**Example**
361
362```js
363import { audio } from '@kit.AudioKit';
364
365let soundPool: media.SoundPool;
366let audioRendererInfo: audio.AudioRendererInfo = {
367  usage : audio.StreamUsage.STREAM_USAGE_MUSIC,
368  rendererFlags : 0
369};
370
371media.createSoundPool(5, audioRendererInfo, (error, soundPool_: media.SoundPool) => {
372  if (error) {
373    console.error(`Failed to createSoundPool`);
374    return;
375  } else {
376    soundPool = soundPool_;
377    console.info(`Succeeded in createSoundPool`);
378  }
379});
380```
381
382## media.createSoundPool<sup>10+</sup>
383
384createSoundPool(maxStreams: number, audioRenderInfo: audio.AudioRendererInfo): Promise\<SoundPool>
385
386Creates a SoundPool instance. This API uses a promise to return the result.
387
388> **NOTE**
389>
390> - 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.
391> - 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.
392
393**System capability**: SystemCapability.Multimedia.Media.SoundPool
394
395**Parameters**
396
397| Name  | Type                                           | Mandatory| Description                                                        |
398| -------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ |
399| 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.|
400| audioRenderInfo | [audio.AudioRendererInfo](../apis-audio-kit/js-apis-audio.md#audiorendererinfo8)  | Yes  | Audio renderer parameters.|
401
402**Return value**
403
404| Type                                     | Description                                                        |
405| ----------------------------------------- | ------------------------------------------------------------ |
406| 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.|
407
408**Error codes**
409
410For details about the error codes, see [Media Error Codes](errorcode-media.md).
411
412| ID| Error Message                     |
413| -------- | ----------------------------- |
414| 5400101  | No memory. Return by promise. |
415
416**Example**
417
418```js
419import { audio } from '@kit.AudioKit';
420import { BusinessError } from '@kit.BasicServicesKit';
421
422let soundPool: media.SoundPool;
423let audioRendererInfo: audio.AudioRendererInfo = {
424  usage : audio.StreamUsage.STREAM_USAGE_MUSIC,
425  rendererFlags : 0
426};
427
428media.createSoundPool(5, audioRendererInfo).then((soundpool_: media.SoundPool) => {
429  if (soundpool_ != null) {
430    soundPool = soundpool_;
431    console.info('Succceeded in creating SoundPool');
432  } else {
433    console.error('Failed to create SoundPool');
434  }
435}, (error: BusinessError) => {
436  console.error(`soundpool catchCallback, error message:${error.message}`);
437});
438```
439
440## media.createAVScreenCaptureRecorder<sup>12+</sup>
441
442createAVScreenCaptureRecorder(): Promise\<AVScreenCaptureRecorder>
443
444Creates an AVScreenCaptureRecorder instance. This API uses a promise to return the result.
445
446**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture
447
448**Return value**
449
450| Type                                                        | Description                                                        |
451| ------------------------------------------------------------ | ------------------------------------------------------------ |
452| 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.|
453
454**Error codes**
455
456| ID| Error Message                      |
457| -------- | ------------------------------ |
458| 5400101  | No memory. Return by promise. |
459
460**Example**
461
462```ts
463import { BusinessError } from '@kit.BasicServicesKit';
464
465let avScreenCaptureRecorder: media.AVScreenCaptureRecorder;
466media.createAVScreenCaptureRecorder().then((captureRecorder: media.AVScreenCaptureRecorder) => {
467  if (captureRecorder != null) {
468    avScreenCaptureRecorder = captureRecorder;
469    console.info('Succeeded in createAVScreenCaptureRecorder');
470  } else {
471    console.error('Failed to createAVScreenCaptureRecorder');
472  }
473}).catch((error: BusinessError) => {
474  console.error(`createAVScreenCaptureRecorder catchCallback, error message:${error.message}`);
475});
476```
477
478## SoundPool<sup>10+</sup>
479
480type SoundPool = _SoundPool
481
482SoundPool, which provides APIs for loading, unloading, playing, and stopping playing system sounds, setting the volume, and setting the number of loops.
483
484**System capability**: SystemCapability.Multimedia.Media.SoundPool
485
486| Type    | Description                      |
487| -------- | ------------------------------ |
488| [_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.|
489
490## PlayParameters<sup>10+</sup>
491
492type PlayParameters = _PlayParameters
493
494Describes the playback parameters of the sound pool.
495
496**System capability**: SystemCapability.Multimedia.Media.SoundPool
497
498| Type    | Description                      |
499| -------- | ------------------------------ |
500| [_PlayParameters](js-apis-inner-multimedia-soundPool.md#playparameters)  | Playback parameters of the sound pool.|
501
502## AVErrorCode<sup>9+</sup>
503
504Enumerates the [media error codes](errorcode-media.md).
505
506**Atomic service API**: This API can be used in atomic services since API version 11.
507
508**System capability**: SystemCapability.Multimedia.Media.Core
509
510| Name                                 | Value     | Description                                |
511| :------------------------------------ | ------- | ------------------------------------ |
512| AVERR_OK                              | 0       | The operation is successful.                      |
513| AVERR_NO_PERMISSION                   | 201     | No permission to perform the operation.              |
514| AVERR_INVALID_PARAMETER               | 401     | Invalid input parameter.                  |
515| AVERR_UNSUPPORT_CAPABILITY            | 801     | Unsupported API.       |
516| AVERR_NO_MEMORY                       | 5400101 | The system memory is insufficient or the number of services reaches the upper limit.|
517| 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.|
518| AVERR_IO                              | 5400103 | The data stream is abnormal.                |
519| AVERR_TIMEOUT                         | 5400104 | The system or network response times out.            |
520| AVERR_SERVICE_DIED                    | 5400105 | The service process is dead.                  |
521| AVERR_UNSUPPORT_FORMAT                | 5400106 | The format of the media asset is not supported.      |
522| AVERR_AUDIO_INTERRUPTED<sup>11+</sup> | 5400107 | The audio focus is interrupted.                  |
523| 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.       |
524| 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.       |
525| 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.       |
526| 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.       |
527| 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.       |
528| 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.       |
529| 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.       |
530| 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.       |
531| 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.       |
532| 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.       |
533| 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.       |
534| 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.       |
535| 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.       |
536| 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.       |
537
538## MediaType<sup>8+</sup>
539
540Enumerates the media types.
541
542**System capability**: SystemCapability.Multimedia.Media.Core
543
544| Name          | Value                   | Description                |
545| -------------- | --------------------- | ------------------- |
546| MEDIA_TYPE_AUD | 0                     | Media.<br>**Atomic service API**: This API can be used in atomic services since API version 11.          |
547| MEDIA_TYPE_VID | 1                     | Video.<br>**Atomic service API**: This API can be used in atomic services since API version 11.         |
548| MEDIA_TYPE_SUBTITLE<sup>12+</sup> | 2    | Subtitle.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
549
550## CodecMimeType<sup>8+</sup>
551
552Enumerates the codec MIME types.
553
554**System capability**: SystemCapability.Multimedia.Media.Core
555
556| Name        | Value                   | Description                    |
557| ------------ | --------------------- | ------------------------ |
558| VIDEO_H263   | 'video/h263'          | Video in H.263 format.     |
559| VIDEO_AVC    | 'video/avc'           | Video in AVC format.      |
560| VIDEO_MPEG2  | 'video/mpeg2'         | Video in MPEG-2 format.    |
561| VIDEO_MPEG4  | 'video/mp4v-es'         | Video in MPEG-4 format.    |
562| VIDEO_VP8    | 'video/x-vnd.on2.vp8' | Video in VP8 format.      |
563| VIDEO_HEVC<sup>11+</sup>   | 'video/hevc'          | Video in H.265 format.|
564| 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.|
565| AUDIO_VORBIS | 'audio/vorbis'        | Audio in Vorbis format.   |
566| AUDIO_FLAC   | 'audio/flac'          | Audio in FLAC format.     |
567| AUDIO_MP3<sup>12+</sup>   | 'audio/mpeg'          | Audio in MPEG format.     |
568| AUDIO_G711MU<sup>12+</sup>   | 'audio/g711mu'     | Audio in G.711 μ-law format.|
569| AUDIO_AMR_NB<sup>18+</sup>   | 'audio/3gpp'     | Audio in AMR-NB format.|
570| AUDIO_AMR_WB<sup>18+</sup>   | 'audio/amr-wb'     | Audio in AMR-WB format.|
571
572## MediaDescriptionKey<sup>8+</sup>
573
574Enumerates the media description keys.
575
576**System capability**: SystemCapability.Multimedia.Media.Core
577
578| Name                    | Value             | Description                                                        |
579| ------------------------ | --------------- | ------------------------------------------------------------ |
580| 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.|
581| 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.|
582| 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.|
583| 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.|
584| 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.|
585| 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.|
586| 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.|
587| 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.|
588| 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.|
589| 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.|
590| 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.|
591| 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.|
592| 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.|
593| 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.|
594
595## PlaybackInfoKey<sup>12+</sup>
596
597Enumerates the playback description keys.
598
599**System capability**: SystemCapability.Multimedia.Media.Core
600
601| Name                    | Value             | Description                                                        |
602| ------------------------ | --------------- | ------------------------------------------------------------ |
603| SERVER_IP_ADDRESS        | 'server_ip_address'    | IP address of the server, which is a string. |
604| AVG_DOWNLOAD_RATE        | 'average_download_rate'| Average download rate, which is a number, in units of bit/s.|
605| DOWNLOAD_RATE            | 'download_rate'        | Download rate in one second, which is a number, in units of bit/s.|
606| 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.|
607| BUFFER_DURATION          | 'buffer_duration'      | Duration that the cached data can be played, which is a number, in units of seconds.|
608
609## BufferingInfoType<sup>8+</sup>
610
611Enumerates the buffering event types.
612
613**Atomic service API**: This API can be used in atomic services since API version 12.
614
615**System capability**: SystemCapability.Multimedia.Media.Core
616
617| Name             | Value  | Description                            |
618| ----------------- | ---- | -------------------------------- |
619| 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.                  |
620| 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.                  |
621| 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.                |
622| 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. |
623
624## StateChangeReason<sup>9+</sup>
625
626Enumerates the reasons for the state transition of the AVPlayer or AVRecorder instance. The enum value is reported together with **state**.
627
628**Atomic service API**: This API can be used in atomic services since API version 11.
629
630**System capability**: SystemCapability.Multimedia.Media.Core
631
632| Name      | Value  | Description                                                        |
633| ---------- | ---- | ------------------------------------------------------------ |
634| USER       | 1    | State transition triggered by user behavior. It happens when a user or the client calls an API.|
635| 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.|
636
637## AVPlayer<sup>9+</sup>
638
639A 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.
640
641For 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).
642
643> **NOTE**
644>
645> When using the AVPlayer instance, you are advised to register the following callbacks to proactively obtain status changes:
646> - [on('stateChange')](#onstatechange9): listens for AVPlayer state changes.
647> - [on('error')](#onerror9): listens for error events.
648
649### Properties
650
651**System capability**: SystemCapability.Multimedia.Media.AVPlayer
652
653| Name                                               | Type                                                        | Read-Only| Optional| Description                                                        |
654| --------------------------------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ |
655| 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.|
656| 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 property is required when media assets of an application are continuously stored in a file.<br>The video formats MP4, MPEG-TS, and MKV are supported.<br>The audio formats M4A, AAC, MP3, OGG, WAV, FLAC, 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.|
657| 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.|
658| surfaceId<sup>9+</sup>                              | string                                                       | No  | Yes  | Video window ID. By default, there is no video window.<br>This parameter can be set when the AVPlayer is in the initialized state.<br>It can be set again when the AVPlayer is in the prepared, playing, paused, completed, or stopped state, in the prerequisite that the video window ID has been set in the initialized state. After the new setting is performed, the video is played in the new window.<br>It is used to render the window for video playback and therefore is not required in audio-only playback scenarios.<br>**Example:**<br>[Create a surface ID through XComponent](../apis-arkui/arkui-ts/ts-basic-components-xcomponent.md#getxcomponentsurfaceid9).<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
659| 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 property<br>and can be set only when the AVPlayer is in the prepared, playing, paused, or completed state.<br>This setting is not supported in live mode.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
660| videoScaleType<sup>9+</sup>                         | [VideoScaleType](#videoscaletype9)                           | No  | Yes  | Video scale type. The default value is **VIDEO_SCALE_TYPE_FIT**. It is a dynamic property<br>and can be set only when the AVPlayer is in the prepared, playing, paused, or completed state.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
661| 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 property<br>and can be set only when the AVPlayer is in the prepared, playing, paused, or completed state.<br>To take effect, this property must be set before [play()](#play9) is called for the first time.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
662| 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 property must be set before [prepare()](#prepare9) is called for the first time.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
663| 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 property and is restored to the default value **EFFECT_DEFAULT** when **usage** of **audioRendererInfo** is changed. It can be set only when the AVPlayer is in the prepared, playing, paused, or completed state.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
664| 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.                 |
665| 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.|
666| 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.|
667| 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.|
668| 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.|
669
670### on('stateChange')<sup>9+</sup>
671
672on(type: 'stateChange', callback: OnAVPlayerStateChangeHandle): void
673
674Subscribes to AVPlayer state changes.
675
676**Atomic service API**: This API can be used in atomic services since API version 11.
677
678**System capability**: SystemCapability.Multimedia.Media.AVPlayer
679
680**Parameters**
681
682| Name  | Type    | Mandatory| Description                                                        |
683| -------- | -------- | ---- | ------------------------------------------------------------ |
684| type     | string   | Yes  | Event type, which is **'stateChange'** in this case. This event can be triggered by both user operations and the system.|
685| callback | [OnAVPlayerStateChangeHandle](#onavplayerstatechangehandle12) | Yes  | Callback invoked when the event is triggered.|
686
687**Example**
688
689```ts
690avPlayer.on('stateChange', async (state: string, reason: media.StateChangeReason) => {
691  switch (state) {
692    case 'idle':
693      console.info('state idle called');
694      break;
695    case 'initialized':
696      console.info('initialized prepared called');
697      break;
698    case 'prepared':
699      console.info('state prepared called');
700      break;
701    case 'playing':
702      console.info('state playing called');
703      break;
704    case 'paused':
705      console.info('state paused called');
706      break;
707    case 'completed':
708      console.info('state completed called');
709      break;
710    case 'stopped':
711      console.info('state stopped called');
712      break;
713    case 'released':
714      console.info('state released called');
715      break;
716    case 'error':
717      console.info('state error called');
718      break;
719    default:
720      console.info('unknown state :' + state);
721      break;
722  }
723});
724```
725
726### off('stateChange')<sup>9+</sup>
727
728off(type: 'stateChange', callback?: OnAVPlayerStateChangeHandle): void
729
730Unsubscribes from AVPlayer state changes.
731
732**Atomic service API**: This API can be used in atomic services since API version 11.
733
734**System capability**: SystemCapability.Multimedia.Media.AVPlayer
735
736**Parameters**
737
738| Name| Type  | Mandatory| Description                                                 |
739| ------ | ------ | ---- | ----------------------------------------------------- |
740| type   | string | Yes  | Event type, which is **'stateChange'** in this case.|
741| callback   | [OnAVPlayerStateChangeHandle](#onavplayerstatechangehandle12) | No  | Callback invoked when the event is triggered.<br>This parameter is supported since API version 12.|
742
743**Example**
744
745```ts
746avPlayer.off('stateChange');
747```
748
749### on('error')<sup>9+</sup>
750
751on(type: 'error', callback: ErrorCallback): void
752
753Subscribes 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.
754
755**Atomic service API**: This API can be used in atomic services since API version 11.
756
757**System capability**: SystemCapability.Multimedia.Media.AVPlayer
758
759**Parameters**
760
761| Name  | Type    | Mandatory| Description                                                        |
762| -------- | -------- | ---- | ------------------------------------------------------------ |
763| type     | string   | Yes  | Event type, which is **'error'** in this case. This event can be triggered by both user operations and the system.|
764| callback | [ErrorCallback](../apis-basic-services-kit/js-apis-base.md#errorcallback) | Yes  | Callback used to return the error code ID and error message.|
765
766**Error codes**
767
768For details about the error codes, see [Media Error Codes](errorcode-media.md).
769
770In 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.
771
772| ID| Error Message             |
773| -------- | --------------------- |
774| 201      | Permission denied.     |
775| 401      | The parameter check failed. |
776| 801      | Capability not supported. |
777| 5400101  | No memory. |
778| 5400102  | Operation not allowed.|
779| 5400103  | I/O error.             |
780| 5400104  | Time out.              |
781| 5400105  | Service died.         |
782| 5400106  | Unsupported format.     |
783| 5411001  | IO can not find host.    |
784| 5411002  | IO connection timeout.  |
785| 5411003  | IO network abnormal.     |
786| 5411004  | IO network unavailable.  |
787| 5411005  | IO no permission.        |
788| 5411006  | IO request denied.  |
789| 5411007  | IO resource not found. |
790| 5411008  | IO SSL client cert needed.    |
791| 5411009  | IO SSL connect fail.     |
792| 5411010  | IO SSL server cert untrusted.    |
793| 5411011  | IO unsupported request.      |
794
795**Example**
796
797```ts
798import { BusinessError } from '@kit.BasicServicesKit';
799
800avPlayer.on('error', (error: BusinessError) => {
801  console.info('error happened,and error message is :' + error.message);
802  console.info('error happened,and error code is :' + error.code);
803});
804```
805
806### off('error')<sup>9+</sup>
807
808off(type: 'error', callback?: ErrorCallback): void
809
810Unsubscribes from AVPlayer errors.
811
812**Atomic service API**: This API can be used in atomic services since API version 11.
813
814**System capability**: SystemCapability.Multimedia.Media.AVPlayer
815
816**Parameters**
817
818| Name| Type  | Mandatory| Description                                     |
819| ------ | ------ | ---- | ----------------------------------------- |
820| type   | string | Yes  | Event type, which is **'error'** in this case.|
821| 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.|
822
823**Example**
824
825```ts
826avPlayer.off('error');
827```
828
829### setMediaSource<sup>12+</sup>
830
831setMediaSource(src:MediaSource, strategy?: PlaybackStrategy): Promise\<void>
832
833Sets 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.
834
835**Atomic service API**: This API can be used in atomic services since API version 12.
836
837**System capability**: SystemCapability.Multimedia.Media.AVPlayer
838
839**Parameters**
840
841| Name  | Type    | Mandatory| Description                |
842| -------- | -------- | ---- | -------------------- |
843| src | [MediaSource](#mediasource12) | Yes  | Source of the streaming media to pre-download.|
844| strategy | [PlaybackStrategy](#playbackstrategy12) | No  | strategy for playing the pre-downloaded streaming media.|
845
846**Return value**
847
848| Type          | Description                                      |
849| -------------- | ------------------------------------------ |
850| Promise\<void> | Promise that returns no value.|
851
852**Error codes**
853
854For details about the error codes, see [Media Error Codes](errorcode-media.md).
855
856| ID| Error Message                                 |
857| -------- | ----------------------------------------- |
858| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed.      |
859| 5400102  | Operation not allowed. Return by promise. |
860
861**Example**
862
863<!--code_no_check-->
864```ts
865let player = await media.createAVPlayer();
866let headers: Record<string, string> = {"User-Agent" : "User-Agent-Value"};
867let mediaSource : media.MediaSource = media.createMediaSourceWithUrl("http://xxx",  headers);
868let playStrategy : media.PlaybackStrategy = {
869  preferredWidth: 1,
870  preferredHeight: 2,
871  preferredBufferDuration: 3,
872  preferredHdr: false,
873  preferredBufferDurationForPlaying: 1,
874  thresholdForAutoQuickPlay: 5
875};
876player.setMediaSource(mediaSource, playStrategy);
877```
878
879### setPlaybackStrategy<sup>12+</sup>
880
881setPlaybackStrategy(strategy: PlaybackStrategy): Promise\<void>
882
883Sets a playback strategy. This API can be called only when the AVPlayer is in the initialized state.
884
885**Atomic service API**: This API can be used in atomic services since API version 12.
886
887**System capability**: SystemCapability.Multimedia.Media.AVPlayer
888
889**Parameters**
890
891| Name  | Type    | Mandatory| Description                |
892| -------- | -------- | ---- | -------------------- |
893| strategy | [PlaybackStrategy](#playbackstrategy12) | Yes  | Playback strategy.|
894
895**Return value**
896
897| Type          | Description                                 |
898| -------------- | ------------------------------------ |
899| Promise\<void> | Promise that returns no value.|
900
901**Error codes**
902
903For details about the error codes, see [Media Error Codes](errorcode-media.md).
904
905| ID| Error Message                                 |
906| -------- | ----------------------------------------- |
907| 401      | Parameter error. Possible causes: 1. Incorrect parameter types. 2. Parameter verification failed. |
908| 5400102  | Operation not allowed. Return by promise. |
909
910**Example**
911
912<!--code_no_check-->
913```ts
914import { common } from '@kit.AbilityKit';
915
916private context: Context | undefined;
917constructor(context: Context) {
918  this.context = context; // this.getUIContext().getHostContext();
919}
920
921let player = await media.createAVPlayer();
922let fileDescriptor = await this.context.resourceManager.getRawFd('xxx.mp4');
923player.fdSrc = fileDescriptor
924let playStrategy : media.PlaybackStrategy = {
925  preferredWidth: 1,
926  preferredHeight: 2,
927  preferredBufferDuration: 3,
928  preferredHdr: false,
929  mutedMediaType: media.MediaType.MEDIA_TYPE_AUD,
930  preferredBufferDurationForPlaying: 1,
931  thresholdForAutoQuickPlay: 5
932};
933player.setPlaybackStrategy(playStrategy);
934```
935
936### setPlaybackRange<sup>18+</sup>
937
938setPlaybackRange(startTimeMs: number, endTimeMs: number, mode?: SeekMode) : Promise\<void>
939
940Sets 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.
941
942**Atomic service API**: This API can be used in atomic services since API version 18.
943
944**System capability**: SystemCapability.Multimedia.Media.AVPlayer
945
946**Parameters**
947
948| Name  | Type                  | Mandatory| Description                       |
949| -------- | ---------------------- | ---- | --------------------------- |
950| 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.|
951| 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.|
952| 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**.|
953
954**Error codes**
955
956For details about the error codes, see [Media Error Codes](errorcode-media.md).
957
958| ID| Error Message                                  |
959| -------- | ------------------------------------------ |
960| 401  | The parameter check failed. Return by promise. |
961| 5400102  | Operation not allowed. Return by promise. |
962
963**Example**
964
965```ts
966import { media } from '@kit.MediaKit';
967import { BusinessError } from '@kit.BasicServicesKit';
968
969avPlayer.setPlaybackRange(0, 6000, media.SeekMode.SEEK_CLOSEST).then(() => {
970  console.info('Succeeded setPlaybackRange');
971}).catch((err: BusinessError) => {
972  console.error('Failed to setPlaybackRange' + err.message);
973});
974```
975
976### prepare<sup>9+</sup>
977
978prepare(callback: AsyncCallback\<void>): void
979
980Prepares 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.
981
982**Atomic service API**: This API can be used in atomic services since API version 11.
983
984**System capability**: SystemCapability.Multimedia.Media.AVPlayer
985
986**Parameters**
987
988| Name  | Type    | Mandatory| Description                |
989| -------- | -------- | ---- | -------------------- |
990| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.|
991
992**Error codes**
993
994For details about the error codes, see [Media Error Codes](errorcode-media.md).
995
996| ID| Error Message                                  |
997| -------- | ------------------------------------------ |
998| 5400102  | Operation not allowed. Return by callback. |
999| 5400106  | Unsupported format. Return by callback.      |
1000
1001**Example**
1002
1003```ts
1004import { BusinessError } from '@kit.BasicServicesKit';
1005
1006avPlayer.prepare((err: BusinessError) => {
1007  if (err) {
1008    console.error('Failed to prepare,error message is :' + err.message);
1009  } else {
1010    console.info('Succeeded in preparing');
1011  }
1012});
1013```
1014
1015### prepare<sup>9+</sup>
1016
1017prepare(): Promise\<void>
1018
1019Prepares 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.
1020
1021If your application frequently switches between short videos, you can create multiple AVPlayer objects to prepare the next video in advance, thereby improving the switching performance. For details, see [Smooth Switchover Between Online Short Videos](https://developer.huawei.com/consumer/en/doc/best-practices/bpta-smooth-switching).
1022
1023**Atomic service API**: This API can be used in atomic services since API version 11.
1024
1025**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1026
1027**Return value**
1028
1029| Type          | Description                     |
1030| -------------- | ------------------------- |
1031| Promise\<void> | Promise that returns no value.|
1032
1033**Error codes**
1034
1035For details about the error codes, see [Media Error Codes](errorcode-media.md).
1036
1037| ID| Error Message                                 |
1038| -------- | ----------------------------------------- |
1039| 5400102  | Operation not allowed. Return by promise. |
1040| 5400106  | Unsupported format. Return by promise.      |
1041
1042**Example**
1043
1044```ts
1045import { BusinessError } from '@kit.BasicServicesKit';
1046
1047avPlayer.prepare().then(() => {
1048  console.info('Succeeded in preparing');
1049}, (err: BusinessError) => {
1050  console.error('Failed to prepare,error message is :' + err.message);
1051});
1052```
1053
1054### setMediaMuted<sup>12+</sup>
1055
1056setMediaMuted(mediaType: MediaType,  muted: boolean ): Promise\<void>
1057
1058Mutes 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.
1059
1060**Atomic service API**: This API can be used in atomic services since API version 12.
1061
1062**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1063
1064**Parameters**
1065
1066| Name  | Type    | Mandatory| Description                |
1067| -------- | -------- | ---- | -------------------- |
1068| mediaType | [MediaType](#mediatype8) | Yes  | Media type.|
1069| muted | boolean | Yes  | Whether to mute the audio. The value **true** means to mute the audio, and **false** means the opposite.|
1070
1071**Return value**
1072
1073| Type          | Description                     |
1074| -------------- | ------------------------- |
1075| Promise\<void> | Promise that returns no value.|
1076
1077**Error codes**
1078
1079For details about the error codes, see [Media Error Codes](errorcode-media.md).
1080
1081| ID| Error Message|
1082| -------- | ----------------------------------------- |
1083| 401 | The parameter check failed. Return by promise. |
1084| 5400102 | Operation not allowed. Return by promise. |
1085
1086**Example**
1087
1088```ts
1089import { BusinessError } from '@kit.BasicServicesKit';
1090
1091avPlayer.prepare().then(() => {
1092  console.info('Succeeded in preparing');
1093  avPlayer.setMediaMuted(media.MediaType.MEDIA_TYPE_AUD, true);
1094}, (err: BusinessError) => {
1095  console.error('Failed to prepare,error message is :' + err.message);
1096});
1097```
1098
1099### play<sup>9+</sup>
1100
1101play(callback: AsyncCallback\<void>): void
1102
1103Starts 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.
1104
1105**Atomic service API**: This API can be used in atomic services since API version 11.
1106
1107**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1108
1109**Parameters**
1110
1111| Name  | Type    | Mandatory| Description                |
1112| -------- | -------- | ---- | -------------------- |
1113| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.|
1114
1115**Error codes**
1116
1117For details about the error codes, see [Media Error Codes](errorcode-media.md).
1118
1119| ID| Error Message                                  |
1120| -------- | ------------------------------------------ |
1121| 5400102  | Operation not allowed. Return by callback. |
1122
1123**Example**
1124
1125```ts
1126import { BusinessError } from '@kit.BasicServicesKit';
1127
1128avPlayer.play((err: BusinessError) => {
1129  if (err) {
1130    console.error('Failed to play,error message is :' + err.message);
1131  } else {
1132    console.info('Succeeded in playing');
1133  }
1134});
1135```
1136
1137### play<sup>9+</sup>
1138
1139play(): Promise\<void>
1140
1141Starts 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.
1142
1143**Atomic service API**: This API can be used in atomic services since API version 11.
1144
1145**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1146
1147**Return value**
1148
1149| Type          | Description                     |
1150| -------------- | ------------------------- |
1151| Promise\<void> | Promise that returns no value.|
1152
1153**Error codes**
1154
1155For details about the error codes, see [Media Error Codes](errorcode-media.md).
1156
1157| ID| Error Message                                 |
1158| -------- | ----------------------------------------- |
1159| 5400102  | Operation not allowed. Return by promise. |
1160
1161**Example**
1162
1163```ts
1164import { BusinessError } from '@kit.BasicServicesKit';
1165
1166avPlayer.play().then(() => {
1167  console.info('Succeeded in playing');
1168}, (err: BusinessError) => {
1169  console.error('Failed to play,error message is :' + err.message);
1170});
1171```
1172
1173### pause<sup>9+</sup>
1174
1175pause(callback: AsyncCallback\<void>): void
1176
1177Pauses 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.
1178
1179**Atomic service API**: This API can be used in atomic services since API version 11.
1180
1181**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1182
1183**Parameters**
1184
1185| Name  | Type    | Mandatory| Description                |
1186| -------- | -------- | ---- | -------------------- |
1187| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.|
1188
1189**Error codes**
1190
1191For details about the error codes, see [Media Error Codes](errorcode-media.md).
1192
1193| ID| Error Message                                  |
1194| -------- | ------------------------------------------ |
1195| 5400102  | Operation not allowed. Return by callback. |
1196
1197**Example**
1198
1199```ts
1200import { BusinessError } from '@kit.BasicServicesKit';
1201
1202avPlayer.pause((err: BusinessError) => {
1203  if (err) {
1204    console.error('Failed to pause,error message is :' + err.message);
1205  } else {
1206    console.info('Succeeded in pausing');
1207  }
1208});
1209```
1210
1211### pause<sup>9+</sup>
1212
1213pause(): Promise\<void>
1214
1215Pauses 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.
1216
1217**Atomic service API**: This API can be used in atomic services since API version 11.
1218
1219**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1220
1221**Return value**
1222
1223| Type          | Description                     |
1224| -------------- | ------------------------- |
1225| Promise\<void> | Promise that returns no value.|
1226
1227**Error codes**
1228
1229For details about the error codes, see [Media Error Codes](errorcode-media.md).
1230
1231| ID| Error Message                                 |
1232| -------- | ----------------------------------------- |
1233| 5400102  | Operation not allowed. Return by promise. |
1234
1235**Example**
1236
1237```ts
1238import { BusinessError } from '@kit.BasicServicesKit';
1239
1240avPlayer.pause().then(() => {
1241  console.info('Succeeded in pausing');
1242}, (err: BusinessError) => {
1243  console.error('Failed to pause,error message is :' + err.message);
1244});
1245```
1246
1247### stop<sup>9+</sup>
1248
1249stop(callback: AsyncCallback\<void>): void
1250
1251Stops 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.
1252
1253**Atomic service API**: This API can be used in atomic services since API version 11.
1254
1255**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1256
1257**Parameters**
1258
1259| Name  | Type    | Mandatory| Description                |
1260| -------- | -------- | ---- | -------------------- |
1261| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.|
1262
1263**Error codes**
1264
1265For details about the error codes, see [Media Error Codes](errorcode-media.md).
1266
1267| ID| Error Message                                  |
1268| -------- | ------------------------------------------ |
1269| 5400102  | Operation not allowed. Return by callback. |
1270
1271**Example**
1272
1273```ts
1274import { BusinessError } from '@kit.BasicServicesKit';
1275
1276avPlayer.stop((err: BusinessError) => {
1277  if (err) {
1278    console.error('Failed to stop,error message is :' + err.message);
1279  } else {
1280    console.info('Succeeded in stopping');
1281  }
1282});
1283```
1284
1285### stop<sup>9+</sup>
1286
1287stop(): Promise\<void>
1288
1289Stops 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.
1290
1291**Atomic service API**: This API can be used in atomic services since API version 11.
1292
1293**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1294
1295**Return value**
1296
1297| Type          | Description                     |
1298| -------------- | ------------------------- |
1299| Promise\<void> | Promise that returns no value.|
1300
1301**Error codes**
1302
1303For details about the error codes, see [Media Error Codes](errorcode-media.md).
1304
1305| ID| Error Message                                 |
1306| -------- | ----------------------------------------- |
1307| 5400102  | Operation not allowed. Return by promise. |
1308
1309**Example**
1310
1311```ts
1312import { BusinessError } from '@kit.BasicServicesKit';
1313
1314avPlayer.stop().then(() => {
1315  console.info('Succeeded in stopping');
1316}, (err: BusinessError) => {
1317  console.error('Failed to stop,error message is :' + err.message);
1318});
1319```
1320
1321### reset<sup>9+</sup>
1322
1323reset(callback: AsyncCallback\<void>): void
1324
1325Resets 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.
1326
1327**Atomic service API**: This API can be used in atomic services since API version 11.
1328
1329**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1330
1331**Parameters**
1332
1333| Name  | Type    | Mandatory| Description                |
1334| -------- | -------- | ---- | -------------------- |
1335| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.|
1336
1337**Error codes**
1338
1339For details about the error codes, see [Media Error Codes](errorcode-media.md).
1340
1341| ID| Error Message                                  |
1342| -------- | ------------------------------------------ |
1343| 5400102  | Operation not allowed. Return by callback. |
1344
1345**Example**
1346
1347```ts
1348import { BusinessError } from '@kit.BasicServicesKit';
1349
1350avPlayer.reset((err: BusinessError) => {
1351  if (err) {
1352    console.error('Failed to reset,error message is :' + err.message);
1353  } else {
1354    console.info('Succeeded in resetting');
1355  }
1356});
1357```
1358
1359### reset<sup>9+</sup>
1360
1361reset(): Promise\<void>
1362
1363Resets 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.
1364
1365**Atomic service API**: This API can be used in atomic services since API version 11.
1366
1367**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1368
1369**Return value**
1370
1371| Type          | Description                     |
1372| -------------- | ------------------------- |
1373| Promise\<void> | Promise that returns no value.|
1374
1375**Error codes**
1376
1377For details about the error codes, see [Media Error Codes](errorcode-media.md).
1378
1379| ID| Error Message                                 |
1380| -------- | ----------------------------------------- |
1381| 5400102  | Operation not allowed. Return by promise. |
1382
1383**Example**
1384
1385```ts
1386import { BusinessError } from '@kit.BasicServicesKit';
1387
1388avPlayer.reset().then(() => {
1389  console.info('Succeeded in resetting');
1390}, (err: BusinessError) => {
1391  console.error('Failed to reset,error message is :' + err.message);
1392});
1393```
1394
1395### release<sup>9+</sup>
1396
1397release(callback: AsyncCallback\<void>): void
1398
1399Releases 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.
1400
1401**Atomic service API**: This API can be used in atomic services since API version 11.
1402
1403**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1404
1405**Parameters**
1406
1407| Name  | Type    | Mandatory| Description                |
1408| -------- | -------- | ---- | -------------------- |
1409| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.|
1410
1411**Error codes**
1412
1413For details about the error codes, see [Media Error Codes](errorcode-media.md).
1414
1415| ID| Error Message                                  |
1416| -------- | ------------------------------------------ |
1417| 5400102  | Operation not allowed. Return by callback. |
1418
1419**Example**
1420
1421```ts
1422import { BusinessError } from '@kit.BasicServicesKit';
1423
1424avPlayer.release((err: BusinessError) => {
1425  if (err) {
1426    console.error('Failed to release,error message is :' + err.message);
1427  } else {
1428    console.info('Succeeded in releasing');
1429  }
1430});
1431```
1432
1433### release<sup>9+</sup>
1434
1435release(): Promise\<void>
1436
1437Releases 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.
1438
1439**Atomic service API**: This API can be used in atomic services since API version 11.
1440
1441**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1442
1443**Return value**
1444
1445| Type          | Description                     |
1446| -------------- | ------------------------- |
1447| Promise\<void> | Promise that returns no value.|
1448
1449**Error codes**
1450
1451For details about the error codes, see [Media Error Codes](errorcode-media.md).
1452
1453| ID| Error Message                                 |
1454| -------- | ----------------------------------------- |
1455| 5400102  | Operation not allowed. Return by promise. |
1456
1457**Example**
1458
1459```ts
1460import { BusinessError } from '@kit.BasicServicesKit';
1461
1462avPlayer.release().then(() => {
1463  console.info('Succeeded in releasing');
1464}, (err: BusinessError) => {
1465  console.error('Failed to release,error message is :' + err.message);
1466});
1467```
1468
1469### getTrackDescription<sup>9+</sup>
1470
1471getTrackDescription(callback: AsyncCallback\<Array\<MediaDescription>>): void
1472
1473Obtains 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.
1474
1475**Atomic service API**: This API can be used in atomic services since API version 11.
1476
1477**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1478
1479**Parameters**
1480
1481| Name  | Type                                                        | Mandatory| Description                                        |
1482| -------- | ------------------------------------------------------------ | ---- | -------------------------------------------- |
1483| 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.|
1484
1485**Error codes**
1486
1487For details about the error codes, see [Media Error Codes](errorcode-media.md).
1488
1489| ID| Error Message                                  |
1490| -------- | ------------------------------------------ |
1491| 5400102  | Operation not allowed. Return by callback. |
1492
1493**Example**
1494
1495```ts
1496import { BusinessError } from '@kit.BasicServicesKit';
1497
1498avPlayer.getTrackDescription((error: BusinessError, arrList: Array<media.MediaDescription>) => {
1499  if ((arrList) != null) {
1500    console.info('Succeeded in doing getTrackDescription');
1501  } else {
1502    console.error(`Failed to do getTrackDescription, error:${error}`);
1503  }
1504});
1505```
1506
1507### getTrackDescription<sup>9+</sup>
1508
1509getTrackDescription(): Promise\<Array\<MediaDescription>>
1510
1511Obtains 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.
1512
1513**Atomic service API**: This API can be used in atomic services since API version 11.
1514
1515**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1516
1517**Return value**
1518
1519| Type                                                  | Description                                             |
1520| ------------------------------------------------------ | ------------------------------------------------- |
1521| Promise<Array<[MediaDescription](#mediadescription8)>> | Promise used to return the MediaDescription array that holds the audio and video track information.|
1522
1523**Error codes**
1524
1525For details about the error codes, see [Media Error Codes](errorcode-media.md).
1526
1527| ID| Error Message                                 |
1528| -------- | ----------------------------------------- |
1529| 5400102  | Operation not allowed. Return by promise. |
1530
1531**Example**
1532
1533```ts
1534import { BusinessError } from '@kit.BasicServicesKit';
1535
1536avPlayer.getTrackDescription().then((arrList: Array<media.MediaDescription>) => {
1537  console.info('Succeeded in getting TrackDescription');
1538}).catch((error: BusinessError) => {
1539  console.error(`Failed to get TrackDescription, error:${error}`);
1540});
1541```
1542
1543### getSelectedTracks<sup>12+</sup>
1544
1545getSelectedTracks(): Promise\<Array\<number>>
1546
1547Obtains 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.
1548
1549**Atomic service API**: This API can be used in atomic services since API version 12.
1550
1551**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1552
1553**Return value**
1554
1555| Type                                                  | Description                                             |
1556| ------------------------------------------------------ | ------------------------------------------------- |
1557| Promise\<Array\<number>> | Promise used to return the index array.|
1558
1559**Error codes**
1560
1561For details about the error codes, see [Media Error Codes](errorcode-media.md).
1562
1563| ID| Error Message                                 |
1564| -------- | ----------------------------------------- |
1565| 5400102  | Operation not allowed. |
1566
1567**Example**
1568
1569```ts
1570import { BusinessError } from '@kit.BasicServicesKit';
1571
1572avPlayer.getSelectedTracks().then((arrList: Array<number>) => {
1573  console.info('Succeeded in getting SelectedTracks');
1574}).catch((error: BusinessError) => {
1575  console.error(`Failed to get SelectedTracks, error:${error}`);
1576});
1577```
1578
1579### getPlaybackInfo<sup>12+</sup>
1580
1581getPlaybackInfo(): Promise\<PlaybackInfo>
1582
1583Obtains 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.
1584
1585**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1586
1587**Return value**
1588
1589| Type                                                  | Description                                             |
1590| ------------------------------------------------------ | ------------------------------------------------- |
1591| Promise<[PlaybackInfo](#playbackinfo12)> | Promise used to return **PlaybackInfo**.|
1592
1593**Example**
1594
1595```ts
1596import { BusinessError } from '@kit.BasicServicesKit';
1597
1598let avPlayer: media.AVPlayer | undefined = undefined;
1599let playbackInfo: media.PlaybackInfo | undefined = undefined;
1600media.createAVPlayer(async (err: BusinessError, player: media.AVPlayer) => {
1601  if (player != null) {
1602    avPlayer = player;
1603    console.info(`Succeeded in creating AVPlayer`);
1604    if (avPlayer) {
1605      try {
1606        playbackInfo = await avPlayer.getPlaybackInfo();
1607        console.info(`AVPlayer getPlaybackInfo = ${JSON.stringify(playbackInfo)}`); // Print PlaybackInfo.
1608      } catch (error) {
1609        console.error(`error = ${error}`);
1610      }
1611    }
1612  } else {
1613    console.error(`Failed to create AVPlayer, error message:${err.message}`);
1614  }
1615});
1616```
1617
1618### getPlaybackPosition<sup>18+</sup>
1619
1620getPlaybackPosition(): number
1621
1622Obtains the current playback position. This API can be called only when the AVPlayer is in the prepared, playing, paused, or completed state.
1623
1624**Atomic service API**: This API can be used in atomic services since API version 18.
1625
1626**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1627
1628**Return value**
1629
1630| Type                                                  | Description                                             |
1631| ------------------------------------------------------ | ------------------------------------------------- |
1632| number | Current playback time, in milliseconds.|
1633
1634**Error codes**
1635
1636For details about the error codes, see [Media Error Codes](errorcode-media.md).
1637
1638| ID| Error Message                                 |
1639| -------- | ----------------------------------------- |
1640| 5400102  | Operation not allowed. |
1641
1642**Example**
1643
1644```ts
1645import { BusinessError } from '@kit.BasicServicesKit';
1646
1647avPlayer.prepare().then(() => {
1648  console.info('Succeeded in preparing');
1649  let playbackPosition: number = avPlayer.getPlaybackPosition();
1650  console.info(`AVPlayer getPlaybackPosition== ${playbackPosition}`);
1651}, (err: BusinessError) => {
1652  console.error('Failed to prepare,error message is :' + err.message);
1653});
1654```
1655
1656### selectTrack<sup>12+</sup>
1657
1658selectTrack(index: number, mode?: SwitchMode): Promise\<void>
1659
1660Selects 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.
1661
1662**Atomic service API**: This API can be used in atomic services since API version 12.
1663
1664**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1665
1666**Parameters**
1667
1668| Name  | Type    | Mandatory| Description                |
1669| -------- | -------- | ---- | -------------------- |
1670| index | number | Yes  | Index of the track. You can call [getTrackDescription](#gettrackdescription9-1) to obtain all track information [MediaDescription](#mediadescription8) of the current resource.|
1671| 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.|
1672
1673**Return value**
1674
1675| Type          | Description                     |
1676| -------------- | ------------------------- |
1677| Promise\<void> | Promise that returns no value.|
1678
1679**Error codes**
1680
1681For details about the error codes, see [Media Error Codes](errorcode-media.md).
1682
1683| ID| Error Message                                 |
1684| -------- | ----------------------------------------- |
1685| 401      | The parameter check failed. Return by promise.       |
1686| 5400102  | Operation not allowed. Return by promise. |
1687
1688**Example**
1689
1690<!--code_no_check-->
1691```ts
1692import { BusinessError } from '@kit.BasicServicesKit';
1693
1694let avPlayer: media.AVPlayer = await media.createAVPlayer();
1695let audioTrackIndex: Object = 0;
1696avPlayer.getTrackDescription((error: BusinessError, arrList: Array<media.MediaDescription>) => {
1697  if (arrList != null) {
1698    for (let i = 0; i < arrList.length; i++) {
1699      if (i != 0) {
1700        // Obtain the audio track list.
1701        audioTrackIndex = arrList[i][media.MediaDescriptionKey.MD_KEY_TRACK_INDEX];
1702      }
1703    }
1704  } else {
1705    console.error(`Failed to get TrackDescription, error:${error}`);
1706  }
1707});
1708
1709// Select an audio track.
1710avPlayer.selectTrack(parseInt(audioTrackIndex.toString()));
1711```
1712
1713### deselectTrack<sup>12+</sup>
1714
1715deselectTrack(index: number): Promise\<void>
1716
1717Deselects 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.
1718
1719**Atomic service API**: This API can be used in atomic services since API version 12.
1720
1721**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1722
1723**Parameters**
1724
1725| Name  | Type    | Mandatory| Description                |
1726| -------- | -------- | ---- | -------------------- |
1727| index | number | Yes  | Track index, which is obtained from [MediaDescription](#mediadescription8) by calling [getTrackDescription](#gettrackdescription9-1).|
1728
1729**Return value**
1730
1731| Type          | Description                     |
1732| -------------- | ------------------------- |
1733| Promise\<void> | Promise that returns no value.|
1734
1735**Error codes**
1736
1737For details about the error codes, see [Media Error Codes](errorcode-media.md).
1738
1739| ID| Error Message                                 |
1740| -------- | ----------------------------------------- |
1741| 401      | The parameter check failed. Return by promise.       |
1742| 5400102  | Operation not allowed. Return by promise. |
1743
1744**Example**
1745
1746<!--code_no_check-->
1747```ts
1748import { BusinessError } from '@kit.BasicServicesKit';
1749
1750let avPlayer: media.AVPlayer = await media.createAVPlayer();
1751let audioTrackIndex: Object = 0;
1752avPlayer.getTrackDescription((error: BusinessError, arrList: Array<media.MediaDescription>) => {
1753  if (arrList != null) {
1754    for (let i = 0; i < arrList.length; i++) {
1755      if (i != 0) {
1756        // Obtain the audio track list.
1757        audioTrackIndex = arrList[i][media.MediaDescriptionKey.MD_KEY_TRACK_INDEX];
1758      }
1759    }
1760  } else {
1761    console.error(`Failed to get TrackDescription, error:${error}`);
1762  }
1763});
1764
1765// Select an audio track.
1766avPlayer.selectTrack(parseInt(audioTrackIndex.toString()));
1767// Deselect the audio track and restore to the default audio track.
1768avPlayer.deselectTrack(parseInt(audioTrackIndex.toString()));
1769```
1770
1771### setDecryptionConfig<sup>11+</sup>
1772
1773setDecryptionConfig(mediaKeySession: drm.MediaKeySession, secureVideoPath: boolean): void
1774
1775Sets 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.
1776
1777**Atomic service API**: This API can be used in atomic services since API version 12.
1778
1779**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1780
1781**Parameters**
1782
1783| Name  | Type                                                        | Mandatory| Description                                        |
1784| -------- | ------------------------------------------------------------ | ---- | -------------------------------------------- |
1785| mediaKeySession | [drm.MediaKeySession](../apis-drm-kit/arkts-apis-drm-MediaKeySession.md) | Yes  | Decryption session.|
1786| 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.|
1787
1788**Error codes**
1789
1790For details about the error codes, see [Media Error Codes](errorcode-media.md).
1791
1792| ID| Error Message                                 |
1793| -------- | ----------------------------------------- |
1794| 401  | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. |
1795
1796**Example**
1797
1798For details about the DRM module, see [@ohos.multimedia.drm](../apis-drm-kit/arkts-apis-drm.md).
1799```ts
1800import { drm } from '@kit.DrmKit';
1801
1802// Create a media key system.
1803let keySystem:drm.MediaKeySystem = drm.createMediaKeySystem('com.clearplay.drm');
1804// Create a media key session.
1805let keySession:drm.MediaKeySession = keySystem.createMediaKeySession(drm.ContentProtectionLevel.CONTENT_PROTECTION_LEVEL_SW_CRYPTO);
1806// Generate a media key request and set the response to the media key request.
1807// Flag indicating whether a secure video channel is used.
1808let secureVideoPath:boolean = false;
1809// Set the decryption configuration.
1810avPlayer.setDecryptionConfig(keySession, secureVideoPath);
1811```
1812
1813### getMediaKeySystemInfos<sup>11+</sup>
1814
1815getMediaKeySystemInfos(): Array\<drm.MediaKeySystemInfo>
1816
1817Obtains 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.
1818
1819**Atomic service API**: This API can be used in atomic services since API version 12.
1820
1821**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1822
1823**Return value**
1824
1825| Type                                                  | Description                                             |
1826| ------------------------------------------------------ | ------------------------------------------------- |
1827|  Array<[drm.MediaKeySystemInfo](../apis-drm-kit/arkts-apis-drm-i.md#mediakeysysteminfo)> | Array of MediaKeySystemInfo objects, each of which contains the **uuid** and **pssh** properties.|
1828
1829**Example**
1830
1831```ts
1832import { drm } from '@kit.DrmKit';
1833
1834const infos = avPlayer.getMediaKeySystemInfos();
1835console.info('GetMediaKeySystemInfos count: ' + infos.length);
1836for (let i = 0; i < infos.length; i++) {
1837  console.info('GetMediaKeySystemInfos uuid: ' + infos[i]["uuid"]);
1838  console.info('GetMediaKeySystemInfos pssh: ' + infos[i]["pssh"]);
1839}
1840```
1841
1842### seek<sup>9+</sup>
1843
1844seek(timeMs: number, mode?:SeekMode): void
1845
1846Seeks 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.
1847This API is not supported in live mode.
1848
1849**Atomic service API**: This API can be used in atomic services since API version 11.
1850
1851**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1852
1853**Parameters**
1854
1855| Name| Type                  | Mandatory| Description                                                        |
1856| ------ | ---------------------- | ---- | ------------------------------------------------------------ |
1857| timeMs | number                 | Yes  | Position to seek to, in ms. The value range is [0, [duration](#properties)]. In SEEK_CONTINUOU mode, the value **-1** can be used to indicate the end of SEEK_CONTINUOUS mode.|
1858| 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.**|
1859
1860**Example**
1861
1862```ts
1863let seekTime: number = 1000;
1864avPlayer.seek(seekTime, media.SeekMode.SEEK_PREV_SYNC);
1865```
1866
1867```ts
1868// Use SEEK_CONTINUOUS with the onChange callback of the Slider. When slideMode is Moving, it triggers continuous seeking during the drag.
1869let slideMovingTime: number = 2000;
1870avPlayer.seek(slideMovingTime, media.SeekMode.SEEK_CONTINUOUS);
1871
1872// To end the seek when slideMode is End, call seek(-1, media.SeekMode.SEEK_CONTINUOUS).
1873avPlayer.seek(-1, media.SeekMode.SEEK_CONTINUOUS);
1874```
1875
1876### isSeekContinuousSupported<sup>18+</sup>
1877
1878isSeekContinuousSupported() : boolean
1879
1880Checks whether the media source supports [seek](#seek9) in SEEK_CONTINUOUS mode (specified by [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.
1881
1882**Atomic service API**: This API can be used in atomic services since API version 18.
1883
1884**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1885
1886**Return value**
1887
1888| Type          | Description                                      |
1889| -------------- | ------------------------------------------ |
1890| boolean | Check result. The value **true** means that the media source supports [seek](#seek9) in SEEK_CONTINUOUS mode, and **false** means the opposite.|
1891
1892**Example**
1893
1894```ts
1895let isSupported = avPlayer.isSeekContinuousSupported();
1896```
1897
1898### on('seekDone')<sup>9+</sup>
1899
1900on(type: 'seekDone', callback: Callback\<number>): void
1901
1902Subscribes to the event to check whether the seek operation takes effect.
1903
1904**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1905
1906**Atomic service API**: This API can be used in atomic services since API version 11.
1907
1908**Parameters**
1909
1910| Name  | Type    | Mandatory| Description                                                        |
1911| -------- | -------- | ---- | ------------------------------------------------------------ |
1912| 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.|
1913| 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** property. The time in this callback only means that the requested seek operation is complete.|
1914
1915**Example**
1916
1917```ts
1918avPlayer.on('seekDone', (seekDoneTime:number) => {
1919  console.info('seekDone called,and seek time is:' + seekDoneTime);
1920});
1921```
1922
1923### off('seekDone')<sup>9+</sup>
1924
1925off(type: 'seekDone', callback?: Callback\<number>): void
1926
1927Unsubscribes from the event that checks whether the seek operation takes effect.
1928
1929**Atomic service API**: This API can be used in atomic services since API version 11.
1930
1931**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1932
1933**Parameters**
1934
1935| Name| Type  | Mandatory| Description                                                |
1936| ------ | ------ | ---- | ---------------------------------------------------- |
1937| type   | string | Yes  | Event type, which is **'seekDone'** in this case.|
1938| 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** property. The time in this callback only means that the requested seek operation is complete.<br>This parameter is supported since API version 12.|
1939
1940**Example**
1941
1942```ts
1943avPlayer.off('seekDone');
1944```
1945
1946### setSpeed<sup>9+</sup>
1947
1948setSpeed(speed: PlaybackSpeed): void
1949
1950Sets 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.
1951This API is not supported in live mode.
1952
1953**Atomic service API**: This API can be used in atomic services since API version 12.
1954
1955**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1956
1957**Parameters**
1958
1959| Name| Type                            | Mandatory| Description              |
1960| ------ | -------------------------------- | ---- | ------------------ |
1961| speed  | [PlaybackSpeed](#playbackspeed8) | Yes  | Playback speed to set.|
1962
1963**Example**
1964
1965```ts
1966avPlayer.setSpeed(media.PlaybackSpeed.SPEED_FORWARD_2_00_X);
1967```
1968
1969### on('speedDone')<sup>9+</sup>
1970
1971on(type: 'speedDone', callback: Callback\<number>): void
1972
1973Subscribes to the event to check whether the playback speed is successfully set.
1974
1975**Atomic service API**: This API can be used in atomic services since API version 12.
1976
1977**System capability**: SystemCapability.Multimedia.Media.AVPlayer
1978
1979**Parameters**
1980
1981| Name  | Type    | Mandatory| Description                                                        |
1982| -------- | -------- | ---- | ------------------------------------------------------------ |
1983| type     | string   | Yes  | Event type, which is **'speedDone'** in this case. This event is triggered each time **setSpeed()** is called.|
1984| 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).|
1985
1986**Example**
1987
1988```ts
1989avPlayer.on('speedDone', (speed:number) => {
1990  console.info('speedDone called,and speed value is:' + speed);
1991});
1992```
1993
1994### off('speedDone')<sup>9+</sup>
1995
1996off(type: 'speedDone', callback?: Callback\<number>): void
1997
1998Unsubscribes from the event that checks whether the playback speed is successfully set.
1999
2000**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2001
2002**Parameters**
2003
2004| Name| Type  | Mandatory| Description                                                     |
2005| ------ | ------ | ---- | --------------------------------------------------------- |
2006| type   | string | Yes  | Event type, which is **'speedDone'** in this case.|
2007| 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.|
2008
2009**Example**
2010
2011```ts
2012avPlayer.off('speedDone');
2013```
2014
2015
2016### setPlaybackRate<sup>20+</sup>
2017
2018setPlaybackRate(rate: number): void
2019
2020Sets the playback rate. This API can be called only when the AVPlayer is in the prepared, playing, paused, or completed state. The value range is [0.125, 4.0]. You can check whether the setting takes effect through the [playbackRateDone](#onplaybackratedone20) event.
2021
2022>**NOTE**
2023>
2024>This API is not supported in live mode.
2025
2026**Atomic service API**: This API can be used in atomic services since API version 20.
2027
2028**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2029
2030**Parameters**
2031
2032| Name| Type                            | Mandatory| Description              |
2033| ------ | -------------------------------- | ---- | ------------------ |
2034| rate  | number | Yes  | Playback rate to set.|
2035
2036**Error codes**
2037
2038For details about the error codes, see [Media Error Codes](errorcode-media.md).
2039
2040| ID| Error Message                                  |
2041| -------- | ------------------------------------------ |
2042| 5400108  | The parameter check failed, parameter value out of range.      |
2043| 5400102  | Operation not allowed, if invalid state or live stream.     |
2044
2045**Example**
2046
2047```ts
2048avPlayer.setPlaybackRate(2.0);
2049```
2050
2051
2052### on('playbackRateDone')<sup>20+</sup>
2053
2054on(type: 'playbackRateDone', callback: OnPlaybackRateDone): void
2055
2056Subscribes to the event indicating that the playback rate set by calling [setPlaybackRate](#setplaybackrate20) is applied.
2057
2058**Atomic service API**: This API can be used in atomic services since API version 20.
2059
2060**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2061
2062**Parameters**
2063
2064| Name  | Type    | Mandatory| Description                                                        |
2065| -------- | -------- | ---- | ------------------------------------------------------------ |
2066| type     | string   | Yes  | Event type, which is **'playbackRateDone'** in this case. This event is triggered each time **setPlaybackRate** is called.|
2067| callback | [OnPlaybackRateDone](#onplaybackratedone20) | Yes  | Callback invoked when the event is triggered. It reports the new playback rate.<br>This parameter is supported since API version 20.|
2068
2069**Example**
2070
2071```ts
2072avPlayer.on('playbackRateDone', (rate:number) => {
2073  console.info('playbackRateDone called,and rate value is:' + rate);
2074});
2075```
2076
2077### off('playbackRateDone')<sup>20+</sup>
2078
2079off(type: 'playbackRateDone', callback?: OnPlaybackRateDone): void
2080
2081Unsubscribes from the event indicating that the playback rate set by calling [setPlaybackRate](#setplaybackrate20) is applied.
2082
2083**Atomic service API**: This API can be used in atomic services since API version 20.
2084
2085**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2086
2087**Parameters**
2088
2089| Name| Type  | Mandatory| Description                                                     |
2090| ------ | ------ | ---- | --------------------------------------------------------- |
2091| type   | string | Yes  | Event type, which is **'playbackRateDone'** in this case.|
2092| callback | [OnPlaybackRateDone](#onplaybackratedone20) | No  |  Callback invoked when the event is triggered. It reports the new playback rate. If this parameter is specified, only the specified callback is unregistered. Otherwise, all callbacks associated with the specified event will be unregistered.<br>This parameter is supported since API version 20.|
2093
2094**Example**
2095
2096```ts
2097avPlayer.off('playbackRateDone');
2098```
2099
2100
2101### setBitrate<sup>9+</sup>
2102
2103setBitrate(bitrate: number): void
2104
2105Sets 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.
2106
2107**Atomic service API**: This API can be used in atomic services since API version 12.
2108
2109**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2110
2111**Parameters**
2112
2113| Name | Type  | Mandatory| Description                                                        |
2114| ------- | ------ | ---- | ------------------------------------------------------------ |
2115| 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.|
2116
2117**Example**
2118
2119```ts
2120let bitrate: number = 96000;
2121avPlayer.setBitrate(bitrate);
2122```
2123
2124### on('bitrateDone')<sup>9+</sup>
2125
2126on(type: 'bitrateDone', callback: Callback\<number>): void
2127
2128Subscribes to the event to check whether the bit rate is successfully set.
2129
2130**Atomic service API**: This API can be used in atomic services since API version 12.
2131
2132**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2133
2134**Parameters**
2135
2136| Name  | Type    | Mandatory| Description                                                        |
2137| -------- | -------- | ---- | ------------------------------------------------------------ |
2138| type     | string   | Yes  | Event type, which is **'bitrateDone'** in this case. This event is triggered each time **setBitrate()** is called.|
2139| callback | Callback\<number> | Yes  | Callback invoked when the event is triggered. It reports the effective bit rate.            |
2140
2141**Example**
2142
2143```ts
2144avPlayer.on('bitrateDone', (bitrate:number) => {
2145  console.info('bitrateDone called,and bitrate value is:' + bitrate);
2146});
2147```
2148
2149### off('bitrateDone')<sup>9+</sup>
2150
2151off(type: 'bitrateDone', callback?: Callback\<number>): void
2152
2153Unsubscribes from the event that checks whether the bit rate is successfully set.
2154
2155**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2156
2157**Parameters**
2158
2159| Name| Type  | Mandatory| Description                                                        |
2160| ------ | ------ | ---- | ------------------------------------------------------------ |
2161| type   | string | Yes  | Event type, which is **'bitrateDone'** in this case.|
2162| 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.            |
2163
2164**Example**
2165
2166```ts
2167avPlayer.off('bitrateDone');
2168```
2169
2170### on('availableBitrates')<sup>9+</sup>
2171
2172on(type: 'availableBitrates', callback: Callback\<Array\<number>>): void
2173
2174Subscribes to available bit rates of HLS/DASH streams. This event is reported only after the AVPlayer switches to the prepared state.
2175
2176**Atomic service API**: This API can be used in atomic services since API version 12.
2177
2178**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2179
2180**Parameters**
2181
2182| Name  | Type    | Mandatory| Description                                                        |
2183| -------- | -------- | ---- | ------------------------------------------------------------ |
2184| type     | string   | Yes  | Event type, which is **'availableBitrates'** in this case. This event is triggered once after the AVPlayer switches to the prepared state.|
2185| 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.|
2186
2187**Example**
2188
2189```ts
2190avPlayer.on('availableBitrates', (bitrates: Array<number>) => {
2191  console.info('availableBitrates called,and availableBitrates length is:' + bitrates.length);
2192});
2193```
2194
2195### off('availableBitrates')<sup>9+</sup>
2196
2197off(type: 'availableBitrates', callback?: Callback\<Array\<number>>): void
2198
2199Unsubscribes from available bit rates of HLS/DASH streams. This event is reported after [prepare](#prepare9) is called.
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 **'availableBitrates'** in this case.|
2210| 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.|
2211
2212**Example**
2213
2214```ts
2215avPlayer.off('availableBitrates');
2216```
2217
2218
2219### on('mediaKeySystemInfoUpdate')<sup>11+</sup>
2220
2221on(type: 'mediaKeySystemInfoUpdate', callback: Callback\<Array\<drm.MediaKeySystemInfo>>): void
2222
2223Subscribes to media key system information changes.
2224
2225**Atomic service API**: This API can be used in atomic services since API version 12.
2226
2227**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2228
2229**Parameters**
2230
2231| Name  | Type    | Mandatory| Description                                                        |
2232| -------- | -------- | ---- | ------------------------------------------------------------ |
2233| 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.|
2234| callback | Callback\<Array\<drm.[MediaKeySystemInfo](../apis-drm-kit/arkts-apis-drm-i.md#mediakeysysteminfo)>> | Yes  | Callback invoked when the event is triggered. It reports a **MediaKeySystemInfo** array.|
2235
2236**Example**
2237
2238```ts
2239import { drm } from '@kit.DrmKit';
2240
2241avPlayer.on('mediaKeySystemInfoUpdate', (mediaKeySystemInfo: Array<drm.MediaKeySystemInfo>) => {
2242    for (let i = 0; i < mediaKeySystemInfo.length; i++) {
2243      console.info('mediaKeySystemInfoUpdate happened uuid: ' + mediaKeySystemInfo[i]["uuid"]);
2244      console.info('mediaKeySystemInfoUpdate happened pssh: ' + mediaKeySystemInfo[i]["pssh"]);
2245    }
2246});
2247```
2248
2249### off('mediaKeySystemInfoUpdate')<sup>11+</sup>
2250
2251off(type: 'mediaKeySystemInfoUpdate', callback?: Callback\<Array\<drm.MediaKeySystemInfo>>): void;
2252
2253Unsubscribes from media key system information changes.
2254
2255**Atomic service API**: This API can be used in atomic services since API version 12.
2256
2257**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2258
2259**Parameters**
2260
2261| Name| Type  | Mandatory| Description                                                        |
2262| ------ | ------ | ---- | ------------------------------------------------------------ |
2263| type   | string | Yes  | Event type, which is **'mediaKeySystemInfoUpdate'** in this case.|
2264| callback | Callback\<Array\<drm.[MediaKeySystemInfo](../apis-drm-kit/arkts-apis-drm-i.md#mediakeysysteminfo)>> | No  | Callback invoked when the event is triggered. It reports a **MediaKeySystemInfo** array. If this parameter is specified, only the specified callback is unregistered. Otherwise, all callbacks associated with the specified event will be unregistered.|
2265
2266**Example**
2267
2268```ts
2269avPlayer.off('mediaKeySystemInfoUpdate');
2270```
2271
2272### setVolume<sup>9+</sup>
2273
2274setVolume(volume: number): void
2275
2276Sets 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.
2277
2278**Atomic service API**: This API can be used in atomic services since API version 12.
2279
2280**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2281
2282**Parameters**
2283
2284| Name| Type  | Mandatory| Description                                                        |
2285| ------ | ------ | ---- | ------------------------------------------------------------ |
2286| volume | number | Yes  | Relative volume. The value ranges from 0.00 to 1.00. The value **1.00** indicates the maximum volume (100%).|
2287
2288**Example**
2289
2290```ts
2291let volume: number = 1.0;
2292avPlayer.setVolume(volume);
2293```
2294
2295### on('volumeChange')<sup>9+</sup>
2296
2297on(type: 'volumeChange', callback: Callback\<number>): void
2298
2299Subscribes to the event to check whether the volume is successfully set.
2300
2301**Atomic service API**: This API can be used in atomic services since API version 12.
2302
2303**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2304
2305**Parameters**
2306
2307| Name  | Type    | Mandatory| Description                                                        |
2308| -------- | -------- | ---- | ------------------------------------------------------------ |
2309| type     | string   | Yes  | Event type, which is **'volumeChange'** in this case. This event is triggered each time **setVolume()** is called.|
2310| callback | Callback\<number> | Yes  | Callback invoked when the event is triggered. It reports the effective volume.           |
2311
2312**Example**
2313
2314```ts
2315avPlayer.on('volumeChange', (vol: number) => {
2316  console.info('volumeChange called,and new volume is :' + vol);
2317});
2318```
2319
2320### off('volumeChange')<sup>9+</sup>
2321
2322off(type: 'volumeChange', callback?: Callback\<number>): void
2323
2324Unsubscribes from the event that checks whether the volume is successfully set.
2325
2326**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2327
2328**Parameters**
2329
2330| Name| Type  | Mandatory| Description                                                        |
2331| ------ | ------ | ---- | ------------------------------------------------------------ |
2332| type   | string | Yes  | Event type, which is **'volumeChange'** in this case.|
2333| 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.           |
2334
2335**Example**
2336
2337```ts
2338avPlayer.off('volumeChange');
2339```
2340
2341### on('endOfStream')<sup>9+</sup>
2342
2343on(type: 'endOfStream', callback: Callback\<void>): void
2344
2345Subscribes to the event that indicates the end of the stream being played. If **[loop](#properties) = true** is set, the AVPlayer seeks to the beginning of the stream and plays the stream again. If **loop** is not set, the completed state is reported through the [stateChange](#onstatechange9) event.
2346
2347**Atomic service API**: This API can be used in atomic services since API version 12.
2348
2349**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2350
2351**Parameters**
2352
2353| Name  | Type    | Mandatory| Description                                                        |
2354| -------- | -------- | ---- | ------------------------------------------------------------ |
2355| type     | string   | Yes  | Event type, which is **'endOfStream'** in this case. This event is triggered when the AVPlayer finishes playing the media asset.|
2356| callback | Callback\<void> | Yes  | Callback invoked when the event is triggered.                              |
2357
2358**Example**
2359
2360```ts
2361avPlayer.on('endOfStream', () => {
2362  console.info('endOfStream called');
2363});
2364```
2365
2366### off('endOfStream')<sup>9+</sup>
2367
2368off(type: 'endOfStream', callback?: Callback\<void>): void
2369
2370Unsubscribes from the event that indicates the end of the stream being played.
2371
2372**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2373
2374**Parameters**
2375
2376| Name| Type  | Mandatory| Description                                                        |
2377| ------ | ------ | ---- | ------------------------------------------------------------ |
2378| type   | string | Yes  | Event type, which is **'endOfStream'** in this case.|
2379| callback | Callback\<void> | No  | Callback invoked when the event is triggered.<br>This parameter is supported since API version 12.                              |
2380
2381**Example**
2382
2383```ts
2384avPlayer.off('endOfStream');
2385```
2386
2387### on('timeUpdate')<sup>9+</sup>
2388
2389on(type: 'timeUpdate', callback: Callback\<number>): void
2390
2391Subscribes 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.
2392
2393The **'timeUpdate'** event is not supported in live mode.
2394
2395**Atomic service API**: This API can be used in atomic services since API version 11.
2396
2397**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2398
2399**Parameters**
2400
2401| Name  | Type    | Mandatory| Description                                          |
2402| -------- | -------- | ---- | ---------------------------------------------- |
2403| type     | string   | Yes  | Event type, which is **'timeUpdate'** in this case.|
2404| callback | Callback\<number> | Yes  | Callback used to return the current time.                                    |
2405
2406**Example**
2407
2408```ts
2409avPlayer.on('timeUpdate', (time:number) => {
2410  console.info('timeUpdate called,and new time is :' + time);
2411});
2412```
2413
2414### off('timeUpdate')<sup>9+</sup>
2415
2416off(type: 'timeUpdate', callback?: Callback\<number>): void
2417
2418Unsubscribes from playback position changes.
2419
2420**Atomic service API**: This API can be used in atomic services since API version 11.
2421
2422**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2423
2424**Parameters**
2425
2426| Name| Type  | Mandatory| Description                                              |
2427| ------ | ------ | ---- | -------------------------------------------------- |
2428| type   | string | Yes  | Event type, which is **'timeUpdate'** in this case.|
2429| callback | Callback\<number> | No  | Callback used to return the current time.<br>This parameter is supported since API version 12.            |
2430
2431**Example**
2432
2433```ts
2434avPlayer.off('timeUpdate');
2435```
2436
2437### on('durationUpdate')<sup>9+</sup>
2438
2439
2440on(type: 'durationUpdate', callback: Callback\<number>): void
2441
2442Subscribes 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.
2443The **'durationUpdate'** event is not supported in live mode.
2444
2445**Atomic service API**: This API can be used in atomic services since API version 12.
2446
2447**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2448
2449**Parameters**
2450
2451| Name  | Type    | Mandatory| Description                                              |
2452| -------- | -------- | ---- | -------------------------------------------------- |
2453| type     | string   | Yes  | Event type, which is **'durationUpdate'** in this case.|
2454| callback | Callback\<number> | Yes  | Callback used to return the resource duration.       |
2455
2456**Example**
2457
2458```ts
2459avPlayer.on('durationUpdate', (duration: number) => {
2460  console.info('durationUpdate called,new duration is :' + duration);
2461});
2462```
2463
2464### off('durationUpdate')<sup>9+</sup>
2465
2466off(type: 'durationUpdate', callback?: Callback\<number>): void
2467
2468Unsubscribes from media asset duration changes.
2469
2470**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2471
2472**Parameters**
2473
2474| Name| Type  | Mandatory| Description                                                  |
2475| ------ | ------ | ---- | ------------------------------------------------------ |
2476| type   | string | Yes  | Event type, which is **'durationUpdate'** in this case.|
2477| callback | Callback\<number> | No  | Callback used to return the resource duration.<br>This parameter is supported since API version 12.       |
2478
2479**Example**
2480
2481```ts
2482avPlayer.off('durationUpdate');
2483```
2484
2485### on('bufferingUpdate')<sup>9+</sup>
2486
2487on(type: 'bufferingUpdate', callback: OnBufferingUpdateHandler): void
2488
2489Subscribes to audio and video buffer changes. This subscription is supported only in network playback scenarios.
2490
2491**Atomic service API**: This API can be used in atomic services since API version 12.
2492
2493**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2494
2495**Parameters**
2496
2497| Name  | Type    | Mandatory| Description                                                        |
2498| -------- | -------- | ---- | ------------------------------------------------------------ |
2499| type     | string   | Yes  | Event type, which is **'bufferingUpdate'** in this case.       |
2500| callback | [OnBufferingUpdateHandler](#onbufferingupdatehandler12) | Yes  | Callback invoked when the event is triggered.|
2501
2502**Example**
2503
2504```ts
2505avPlayer.on('bufferingUpdate', (infoType: media.BufferingInfoType, value: number) => {
2506  console.info('bufferingUpdate called,and infoType value is:' + infoType + ', value is :' + value);
2507});
2508```
2509
2510### off('bufferingUpdate')<sup>9+</sup>
2511
2512off(type: 'bufferingUpdate', callback?: OnBufferingUpdateHandler): void
2513
2514Unsubscribes from audio and video buffer changes.
2515
2516**Atomic service API**: This API can be used in atomic services since API version 12.
2517
2518**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2519
2520**Parameters**
2521
2522| Name| Type  | Mandatory| Description                                                     |
2523| ------ | ------ | ---- | --------------------------------------------------------- |
2524| type   | string | Yes  | Event type, which is **'bufferingUpdate'** in this case.|
2525| callback | [OnBufferingUpdateHandler](#onbufferingupdatehandler12) | No  | Callback invoked when the event is triggered.|
2526
2527**Example**
2528
2529```ts
2530avPlayer.off('bufferingUpdate');
2531```
2532
2533### on('startRenderFrame')<sup>9+</sup>
2534
2535on(type: 'startRenderFrame', callback: Callback\<void>): void
2536
2537Subscribes 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.
2538
2539**Atomic service API**: This API can be used in atomic services since API version 12.
2540
2541**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2542
2543**Parameters**
2544
2545| Name  | Type    | Mandatory| Description                                                        |
2546| -------- | -------- | ---- | ------------------------------------------------------------ |
2547| type     | string   | Yes  | Event type, which is **'startRenderFrame'** in this case.|
2548| callback | Callback\<void> | Yes  | Callback invoked when the event is triggered.                          |
2549
2550**Example**
2551
2552```ts
2553avPlayer.on('startRenderFrame', () => {
2554  console.info('startRenderFrame called');
2555});
2556```
2557
2558### off('startRenderFrame')<sup>9+</sup>
2559
2560off(type: 'startRenderFrame', callback?: Callback\<void>): void
2561
2562Unsubscribes from the event that indicates rendering starts for the first frame.
2563
2564**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2565
2566**Parameters**
2567
2568| Name| Type  | Mandatory| Description                                                        |
2569| ------ | ------ | ---- | ------------------------------------------------------------ |
2570| type   | string | Yes  | Event type, which is **'startRenderFrame'** in this case.|
2571| callback | Callback\<void> | No  | Callback invoked when the event is triggered.<br>This parameter is supported since API version 12.                  |
2572
2573**Example**
2574
2575```ts
2576avPlayer.off('startRenderFrame');
2577```
2578
2579### on('videoSizeChange')<sup>9+</sup>
2580
2581on(type: 'videoSizeChange', callback: OnVideoSizeChangeHandler): void
2582
2583Subscribes 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.
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 **'videoSizeChange'** in this case.|
2594| callback | [OnVideoSizeChangeHandler](#onvideosizechangehandler12) | Yes  | Callback invoked when the event is triggered.   |
2595
2596**Example**
2597
2598```ts
2599avPlayer.on('videoSizeChange', (width: number, height: number) => {
2600  console.info('videoSizeChange called,and width is:' + width + ', height is :' + height);
2601});
2602```
2603
2604### off('videoSizeChange')<sup>9+</sup>
2605
2606off(type: 'videoSizeChange', callback?: OnVideoSizeChangeHandler): void
2607
2608Unsubscribes from video size changes.
2609
2610**Atomic service API**: This API can be used in atomic services since API version 12.
2611
2612**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2613
2614**Parameters**
2615
2616| Name| Type  | Mandatory| Description                                                        |
2617| ------ | ------ | ---- | ------------------------------------------------------------ |
2618| type   | string | Yes  | Event type, which is **'videoSizeChange'** in this case.|
2619| callback | [OnVideoSizeChangeHandler](#onvideosizechangehandler12) | No  | Callback invoked when the event is triggered.<br>This parameter is supported since API version 12.   |
2620
2621**Example**
2622
2623```ts
2624avPlayer.off('videoSizeChange');
2625```
2626
2627### on('audioInterrupt')<sup>9+</sup>
2628
2629on(type: 'audioInterrupt', callback: Callback\<audio.InterruptEvent>): void
2630
2631Subscribes 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).
2632
2633**Atomic service API**: This API can be used in atomic services since API version 12.
2634
2635**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2636
2637**Parameters**
2638
2639| Name  | Type                                                        | Mandatory| Description                                                    |
2640| -------- | ------------------------------------------------------------ | ---- | -------------------------------------------------------- |
2641| type     | string                                                       | Yes  | Event type, which is **'audioInterrupt'** in this case.|
2642| callback | Callback\<[audio.InterruptEvent](../apis-audio-kit/js-apis-audio.md#interruptevent9)> | Yes  | Callback invoked when the event is triggered.                          |
2643
2644**Example**
2645
2646```ts
2647import { audio } from '@kit.AudioKit';
2648
2649avPlayer.on('audioInterrupt', (info: audio.InterruptEvent) => {
2650  console.info('audioInterrupt called,and InterruptEvent info is:' + info);
2651});
2652```
2653
2654### off('audioInterrupt')<sup>9+</sup>
2655
2656off(type: 'audioInterrupt', callback?: Callback<audio.InterruptEvent>): void
2657
2658Unsubscribes from the audio interruption event.
2659
2660**Atomic service API**: This API can be used in atomic services since API version 12.
2661
2662**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2663
2664**Parameters**
2665
2666| Name| Type  | Mandatory| Description                                                        |
2667| ------ | ------ | ---- | ------------------------------------------------------------ |
2668| type   | string | Yes  | Event type, which is **'audioInterrupt'** in this case.|
2669| 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.            |
2670
2671**Example**
2672
2673```ts
2674avPlayer.off('audioInterrupt');
2675```
2676
2677### on('audioOutputDeviceChangeWithInfo')<sup>11+</sup>
2678
2679on(type: 'audioOutputDeviceChangeWithInfo', callback: Callback\<audio.AudioStreamDeviceChangeInfo>): void
2680
2681Subscribes to audio stream output device changes and reasons. This API uses an asynchronous callback to return the result.
2682
2683When 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).
2684
2685**Atomic service API**: This API can be used in atomic services since API version 12.
2686
2687**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2688
2689**Parameters**
2690
2691| Name  | Type                      | Mandatory| Description                                       |
2692| :------- | :------------------------- | :--- | :------------------------------------------ |
2693| type     | string                     | Yes  | Event type, which is **'audioOutputDeviceChangeWithInfo'** in this case.|
2694| 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.|
2695
2696**Error codes**
2697
2698| ID| Error Message                                  |
2699| -------- | ------------------------------------------ |
2700| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed.       |
2701
2702**Example**
2703
2704```ts
2705import { audio } from '@kit.AudioKit';
2706
2707avPlayer.on('audioOutputDeviceChangeWithInfo', (data: audio.AudioStreamDeviceChangeInfo) => {
2708  console.info(`${JSON.stringify(data)}`);
2709});
2710```
2711
2712### off('audioOutputDeviceChangeWithInfo')<sup>11+</sup>
2713
2714off(type: 'audioOutputDeviceChangeWithInfo', callback?: Callback\<audio.AudioStreamDeviceChangeInfo>): void
2715
2716Unsubscribes from audio stream output device changes and reasons. This API uses an asynchronous callback to return the result.
2717
2718**Atomic service API**: This API can be used in atomic services since API version 12.
2719
2720**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2721
2722**Parameters**
2723
2724| Name  | Type                      | Mandatory| Description                                       |
2725| :------- | :------------------------- | :--- | :------------------------------------------ |
2726| type     | string                     | Yes  | Event type, which is **'audioOutputDeviceChangeWithInfo'** in this case.|
2727| 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.|
2728
2729**Error codes**
2730
2731| ID| Error Message                                  |
2732| -------- | ------------------------------------------ |
2733| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed.      |
2734
2735**Example**
2736
2737```ts
2738avPlayer.off('audioOutputDeviceChangeWithInfo');
2739```
2740
2741### addSubtitleFromFd<sup>12+</sup>
2742
2743addSubtitleFromFd(fd: number, offset?: number, length?: number): Promise\<void>
2744
2745Adds 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.
2746
2747**Atomic service API**: This API can be used in atomic services since API version 12.
2748
2749**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2750
2751**Parameters**
2752
2753| Name| Type                  | Mandatory| Description                                                        |
2754| ------ | ---------------------- | ---- | ------------------------------------------------------------ |
2755| fd | number   | Yes  | Resource handle, which is obtained by calling [resourceManager.getRawFd](../apis-localization-kit/js-apis-resource-manager.md#getrawfd9).|
2756| offset | number | No  | Resource offset, which needs to be entered based on the preset asset information. An invalid value causes a failure to parse subtitle assets. The default value is **0**.|
2757| length | number | No  | Resource length, which needs to be entered based on the preset asset information. The default value is the remaining bytes from the offset in the file. An invalid value causes a failure to parse subtitle assets. The default value is **0**.|
2758
2759**Return value**
2760
2761| Type          | Description                                      |
2762| -------------- | ------------------------------------------ |
2763| Promise\<void> | Promise that returns no value.|
2764
2765**Error codes**
2766
2767| ID| Error Message                                  |
2768| -------- | ------------------------------------------ |
2769| 401      | The parameter check failed. Return by promise. |
2770| 5400102  | Operation not allowed. Return by promise. |
2771
2772**Example**
2773
2774<!--code_no_check-->
2775```ts
2776import { common } from '@kit.AbilityKit'
2777
2778private context: Context | undefined;
2779constructor(context: Context) {
2780  this.context = context; // this.getUIContext().getHostContext();
2781}
2782let fileDescriptor = await this.context.resourceManager.getRawFd('xxx.srt');
2783
2784avPlayer.addSubtitleFromFd(fileDescriptor.fd, fileDescriptor.offset, fileDescriptor.length);
2785```
2786
2787### addSubtitleFromUrl<sup>12+</sup>
2788
2789addSubtitleFromUrl(url: string): Promise\<void>
2790
2791Adds 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.
2792
2793**Atomic service API**: This API can be used in atomic services since API version 12.
2794
2795**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2796
2797**Parameters**
2798
2799| Name| Type  | Mandatory| Description                                                        |
2800| ------ | ------ | ---- | ------------------------------------------------------------ |
2801| url    | string | Yes  | Address of the external subtitle file.|
2802
2803**Return value**
2804
2805| Type          | Description                                      |
2806| -------------- | ------------------------------------------ |
2807| Promise\<void> | Promise that returns no value.|
2808
2809**Error codes**
2810
2811| ID| Error Message                                  |
2812| -------- | ------------------------------------------ |
2813| 401      | The parameter check failed. Return by promise. |
2814| 5400102  | Operation not allowed. Return by promise. |
2815
2816**Example**
2817
2818<!--code_no_check-->
2819```ts
2820let fdUrl:string = 'http://xxx.xxx.xxx/xx/index.srt';
2821
2822let avPlayer: media.AVPlayer = await media.createAVPlayer();
2823avPlayer.addSubtitleFromUrl(fdUrl);
2824```
2825
2826### on('subtitleUpdate')<sup>12+</sup>
2827
2828on(type: 'subtitleUpdate', callback: Callback\<SubtitleInfo>): void
2829
2830Subscribes 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.
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 **'subtitleUpdate'** in this case. The event is triggered when the external subtitle is updated.|
2841| callback | function | Yes  | Callback invoked when the subtitle is updated.|
2842
2843**Example**
2844
2845```ts
2846avPlayer.on('subtitleUpdate', async (info: media.SubtitleInfo) => {
2847  if (info) {
2848    let text = (!info.text) ? '' : info.text
2849    let startTime = (!info.startTime) ? 0 : info.startTime
2850    let duration = (!info.duration) ? 0 : info.duration
2851    console.info('subtitleUpdate info: text=' + text + ' startTime=' + startTime +' duration=' + duration);
2852  } else {
2853    console.info('subtitleUpdate info is null');
2854  }
2855});
2856```
2857
2858### off('subtitleUpdate')<sup>12+</sup>
2859
2860off(type: 'subtitleUpdate', callback?: Callback\<SubtitleInfo>): void
2861
2862Unsubscribes from subtitle update events.
2863
2864**Atomic service API**: This API can be used in atomic services since API version 12.
2865
2866**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2867
2868**Parameters**
2869
2870| Name  | Type    | Mandatory| Description                                                        |
2871| -------- | -------- | ---- | ------------------------------------------------------------ |
2872| type | string | Yes  | Event type, which is **'subtitleUpdate'** in this case. The event is triggered when the external subtitle is updated.|
2873| callback | function | No  | Callback that has been registered to listen for subtitle update events.|
2874
2875**Example**
2876
2877```ts
2878avPlayer.off('subtitleUpdate');
2879```
2880
2881### on('trackChange')<sup>12+</sup>
2882
2883on(type: 'trackChange', callback: OnTrackChangeHandler): void
2884
2885Subscribes 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.
2886
2887**Atomic service API**: This API can be used in atomic services since API version 12.
2888
2889**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2890
2891**Parameters**
2892
2893| Name  | Type    | Mandatory| Description                                                        |
2894| -------- | -------- | ---- | ------------------------------------------------------------ |
2895| type | string | Yes  | Event type, which is **'trackChange'** in this case. The event is triggered when the track changes.|
2896| callback | [OnTrackChangeHandler](#ontrackchangehandler12) | Yes  | Callback invoked when the event is triggered.|
2897
2898**Example**
2899
2900```ts
2901avPlayer.on('trackChange', (index: number, isSelect: boolean) => {
2902  console.info('trackChange info: index=' + index + ' isSelect=' + isSelect);
2903});
2904```
2905
2906### off('trackChange')<sup>12+</sup>
2907
2908off(type: 'trackChange', callback?: OnTrackChangeHandler): void
2909
2910Unsubscribes from track change events.
2911
2912**Atomic service API**: This API can be used in atomic services since API version 12.
2913
2914**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2915
2916**Parameters**
2917
2918| Name  | Type    | Mandatory| Description                                                        |
2919| -------- | -------- | ---- | ------------------------------------------------------------ |
2920| type | string | Yes  | Event type, which is **'trackChange'** in this case. The event is triggered when the track changes.|
2921| callback | [OnTrackChangeHandler](#ontrackchangehandler12) | No  | Callback that has been registered to listen for track changes.|
2922
2923**Example**
2924
2925```ts
2926avPlayer.off('trackChange');
2927```
2928
2929### on('trackInfoUpdate')<sup>12+</sup>
2930
2931on(type: 'trackInfoUpdate', callback: Callback\<Array\<MediaDescription>>): void
2932
2933Subscribes 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.
2934
2935**Atomic service API**: This API can be used in atomic services since API version 12.
2936
2937**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2938
2939**Parameters**
2940
2941| Name  | Type    | Mandatory| Description                                                        |
2942| -------- | -------- | ---- | ------------------------------------------------------------ |
2943| type | string | Yes  | Event type, which is **'trackInfoUpdate'** in this case. The event is triggered when the track information is updated.|
2944| callback | Callback\<Array\<[MediaDescription](#mediadescription8)>> | Yes  | Callback invoked when the event is triggered.|
2945
2946**Example**
2947
2948```ts
2949avPlayer.on('trackInfoUpdate', (info: Array<media.MediaDescription>) => {
2950  if (info) {
2951    for (let i = 0; i < info.length; i++) {
2952      let propertyIndex: Object = info[i][media.MediaDescriptionKey.MD_KEY_TRACK_INDEX];
2953      let propertyType: Object = info[i][media.MediaDescriptionKey.MD_KEY_TRACK_TYPE];
2954      console.info('track info: index=' + propertyIndex + ' tracktype=' + propertyType);
2955    }
2956  } else {
2957    console.info('track info is null');
2958  }
2959});
2960```
2961
2962### off('trackInfoUpdate')<sup>12+</sup>
2963
2964off(type: 'trackInfoUpdate', callback?: Callback\<Array\<MediaDescription>>): void
2965
2966Unsubscribes from track information update events.
2967
2968**Atomic service API**: This API can be used in atomic services since API version 12.
2969
2970**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2971
2972**Parameters**
2973
2974| Name  | Type    | Mandatory| Description                                                        |
2975| -------- | -------- | ---- | ------------------------------------------------------------ |
2976| type | string | Yes  | Event type, which is **'trackInfoUpdate'** in this case. The event is triggered when the track information is updated.|
2977| callback | Callback\<Array\<[MediaDescription](#mediadescription8)>> | No  | Callback that has been registered to listen for track information updates.|
2978
2979**Example**
2980
2981```ts
2982avPlayer.off('trackInfoUpdate');
2983```
2984
2985### on('amplitudeUpdate')<sup>13+</sup>
2986
2987on(type: 'amplitudeUpdate', callback: Callback\<Array\<number>>): void
2988
2989Subscribes to update events of the maximum audio level value, which is periodically reported when audio resources are played.
2990
2991**System capability**: SystemCapability.Multimedia.Media.AVPlayer
2992
2993**Parameters**
2994
2995| Name  | Type    | Mandatory| Description                                                        |
2996| -------- | -------- | ---- | ------------------------------------------------------------ |
2997| type     | string   | Yes  | Event type, which is **'amplitudeUpdate'** in this case. The event is triggered when the amplitude changes.|
2998| callback | Callback\<Array\<number>> | Yes  | Callback invoked when the event is triggered.|
2999
3000**Example**
3001
3002```ts
3003avPlayer.on('amplitudeUpdate', (value: Array<number>) => {
3004  console.info('amplitudeUpdate called,and amplitudeUpdate = ${value}');
3005});
3006```
3007
3008### off('amplitudeUpdate')<sup>13+</sup>
3009
3010off(type: 'amplitudeUpdate', callback?: Callback\<Array\<number>>): void
3011
3012Unsubscribes from update events of the maximum amplitude.
3013
3014**System capability**: SystemCapability.Multimedia.Media.AVPlayer
3015
3016**Parameters**
3017
3018| Name| Type  | Mandatory| Description                                                        |
3019| ------ | ------ | ---- | ------------------------------------------------------------ |
3020| type   | string | Yes  | Event type, which is **'amplitudeUpdate'** in this case. The event is triggered when the amplitude changes.|
3021| callback | Callback\<Array\<number>> | No  | Callback that has been registered to listen for amplitude updates.|
3022
3023**Example**
3024
3025```ts
3026avPlayer.off('amplitudeUpdate');
3027```
3028
3029### on('seiMessageReceived')<sup>18+</sup>
3030
3031on(type: 'seiMessageReceived', payloadTypes: Array\<number>, callback: OnSeiMessageHandle): void
3032
3033Subscribes 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.
3034
3035**Atomic service API**: This API can be used in atomic services since API version 18.
3036
3037**System capability**: SystemCapability.Multimedia.Media.AVPlayer
3038
3039**Parameters**
3040
3041| Name  | Type    | Mandatory| Description                                                        |
3042| -------- | -------- | ---- | ------------------------------------------------------------ |
3043| type     | string | Yes| Event type, which is **'seiMessageReceived'** in this case. The event is triggered when an SEI message is received.|
3044| payloadTypes | Array\<number> | Yes| Array of subscribed-to payload types of SEI messages. Currently, only payloadType = 5 is supported.|
3045| callback | [OnSeiMessageHandle](#onseimessagehandle18) | Yes| Callback used to listen for SEI message events and receive the subscribed-to payload types.|
3046
3047**Example**
3048
3049```ts
3050import util from '@ohos.util';
3051
3052avPlayer.on('seiMessageReceived', [5], (messages: Array<media.SeiMessage>, playbackPosition?: number) =>
3053{
3054  console.info('seiMessageReceived playbackPosition ' + playbackPosition);
3055
3056  for (let key = 0; key < messages.length; key++) {
3057    console.info('seiMessageReceived messages payloadType ' + messages[key].payloadType + ' payload size ' + messages[key].payload.byteLength);
3058
3059    let textDecoder = util.TextDecoder.create("utf-8",{ignoreBOM: true});
3060    let ab = messages[key]?.payload?.slice(16, messages[key].payload.byteLength);
3061    let result: Uint8Array = new Uint8Array(ab);
3062    let retStr: string = textDecoder.decodeToString(result);
3063    console.info('seiMessageReceived messages payload ' + retStr);
3064  }
3065});
3066```
3067
3068### off('seiMessageReceived')<sup>18+</sup>
3069
3070off(type: 'seiMessageReceived', payloadTypes?: Array\<number>, callback?: OnSeiMessageHandle): void
3071
3072Unsubscribes from the events indicating that an SEI message is received.
3073
3074**Atomic service API**: This API can be used in atomic services since API version 18.
3075
3076**System capability**: SystemCapability.Multimedia.Media.AVPlayer
3077
3078**Parameters**
3079
3080| Name| Type  | Mandatory| Description                                                        |
3081| ------ | ------ | ---- | ------------------------------------------------------------ |
3082| type     | string   | Yes  | Event type, which is **'seiMessageReceived'** in this case. The event is triggered when an SEI message is received.|
3083| payloadTypes | Array\<number> | No  | Array of subscribed-to payload types of SEI messages.|
3084| callback | [OnSeiMessageHandle](#onseimessagehandle18) | No  | Callback used to listen for SEI message events and receive the subscribed-to payload types.|
3085
3086**Example**
3087
3088```ts
3089avPlayer.off('seiMessageReceived');
3090```
3091
3092### setSuperResolution<sup>18+</sup>
3093
3094setSuperResolution(enabled: boolean) : Promise\<void>
3095
3096Enables 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.
3097
3098Before calling [prepare()](#prepare9), enable super resolution by using [PlaybackStrategy](#playbackstrategy12).
3099
3100**Atomic service API**: This API can be used in atomic services since API version 18.
3101
3102**System capability**: SystemCapability.Multimedia.Media.AVPlayer
3103
3104**Parameters**
3105
3106| Name| Type  | Mandatory| Description                                                        |
3107| ------ | ------ | ---- | ------------------------------------------------------------ |
3108| enabled    | boolean | Yes  | Whether to enable or disable super resolution. The value **true** means to enable it, and **false** means to disable it.|
3109
3110**Return value**
3111
3112| Type          | Description                                      |
3113| -------------- | ------------------------------------------ |
3114| Promise\<void> | Promise that returns no value.|
3115
3116**Error codes**
3117
3118For details about the error codes, see [Media Error Codes](errorcode-media.md).
3119
3120| ID| Error Message                                  |
3121| -------- | ------------------------------------------ |
3122| 5400102  | Operation not allowed. Return by promise. |
3123| 5410003  | Super-resolution not supported. Return by promise. |
3124| 5410004  | Missing enable super-resolution feature in [PlaybackStrategy](#playbackstrategy12). Return by promise. |
3125
3126**Example**
3127
3128```ts
3129avPlayer.setSuperResolution(true);
3130```
3131
3132### setVideoWindowSize<sup>18+</sup>
3133
3134setVideoWindowSize(width: number, height: number) : Promise\<void>
3135
3136Sets 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).
3137
3138Before calling [prepare()](#prepare9), enable super resolution by using [PlaybackStrategy](#playbackstrategy12).
3139
3140**Atomic service API**: This API can be used in atomic services since API version 18.
3141
3142**System capability**: SystemCapability.Multimedia.Media.AVPlayer
3143
3144**Parameters**
3145
3146| Name| Type  | Mandatory| Description                                                        |
3147| ------ | ------ | ---- | ------------------------------------------------------------ |
3148| width    | number | Yes  | Target width of the output video after super resolution. The value range is [320-1920], in px.|
3149| height    | number | Yes  | Target height of the output video after super resolution. The value range is [320-1080], in px.|
3150
3151**Return value**
3152
3153| Type          | Description                                      |
3154| -------------- | ------------------------------------------ |
3155| Promise\<void> | Promise that returns no value.|
3156
3157**Error codes**
3158
3159For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Media Error Codes](errorcode-media.md).
3160
3161| ID| Error Message                                  |
3162| -------- | ------------------------------------------ |
3163| 401      | Parameter error. Return by promise. |
3164| 5400102  | Operation not allowed. Return by promise. |
3165| 5410003  | Super-resolution not supported. Return by promise. |
3166| 5410004  | Missing enable super-resolution feature in [PlaybackStrategy](#playbackstrategy12). Return by promise. |
3167
3168**Example**
3169
3170```ts
3171avPlayer.setVideoWindowSize(1920, 1080);
3172```
3173
3174### on('superResolutionChanged')<sup>18+</sup>
3175
3176on(type:'superResolutionChanged', callback: OnSuperResolutionChanged): void
3177
3178Subscribes to the event indicating that super resolution is enabled or disabled.
3179
3180**Atomic service API**: This API can be used in atomic services since API version 18.
3181
3182**System capability**: SystemCapability.Multimedia.Media.AVPlayer
3183
3184**Parameters**
3185
3186| Name  | Type    | Mandatory| Description                                                        |
3187| -------- | -------- | ---- | ------------------------------------------------------------ |
3188| type     | string | Yes| Event type, which is **'superResolutionChanged'** in this case. The event is triggered when super resolution is enabled or disabled.|
3189| callback | [OnSuperResolutionChanged](#onsuperresolutionchanged-18) | Yes| Callback used to listen for super resolution status changes.|
3190
3191**Example**
3192
3193```ts
3194avPlayer.on('superResolutionChanged', (enabled: boolean) => {
3195  console.info('superResolutionChanged called, and enabled is:' + enabled);
3196});
3197```
3198
3199### off('superResolutionChanged')<sup>18+</sup>
3200
3201off(type:'superResolutionChanged', callback?: OnSuperResolutionChanged): void
3202
3203Unsubscribes from the event indicating that super resolution is enabled or disabled.
3204
3205**Atomic service API**: This API can be used in atomic services since API version 18.
3206
3207**System capability**: SystemCapability.Multimedia.Media.AVPlayer
3208
3209**Parameters**
3210
3211| Name  | Type    | Mandatory| Description                                                        |
3212| -------- | -------- | ---- | ------------------------------------------------------------ |
3213| type     | string | Yes| Event type, which is **'superResolutionChanged'** in this case. The event is triggered when super resolution is enabled or disabled.|
3214| callback | [OnSuperResolutionChanged](#onsuperresolutionchanged-18) | No| Callback used to listen for super resolution status changes.|
3215
3216**Example**
3217
3218```ts
3219avPlayer.off('superResolutionChanged');
3220```
3221
3222## AVPlayerState<sup>9+</sup>
3223
3224type AVPlayerState = 'idle' | 'initialized' | 'prepared' | 'playing' | 'paused' | 'completed' | 'stopped' | 'released' | 'error'
3225
3226Describes the state of the [AVPlayer](#avplayer9). Your application can proactively obtain the AVPlayer state through the **state** property 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).
3227
3228**Atomic service API**: This API can be used in atomic services since API version 11.
3229
3230**System capability**: SystemCapability.Multimedia.Media.AVPlayer
3231
3232|              Type              | Description                                                        |
3233| :-----------------------------: | :----------------------------------------------------------- |
3234|              'idle'               | The AVPlayer enters this state after [createAVPlayer()](#mediacreateavplayer9) or [reset()](#reset9) is called.<br>In case [createAVPlayer()](#mediacreateavplayer9) is used, all properties 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>** property and the **loop** property are reset, and other properties are retained.|
3235|           'initialized'           | The AVPlayer enters this state after **url<sup>9+</sup>** or **fdSrc<sup>9+</sup>** property is set in the idle state. In this case, you can configure static properties such as the window and audio.|
3236|            '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.|
3237|             'playing'             | The AVPlayer enters this state when [play()](#play9) is called in the prepared, paused, or completed state.|
3238|             'paused'              | The AVPlayer enters this state when **pause()** is called in the playing state.|
3239|            '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.|
3240|             '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 properties but releases the memory resources. You can call [prepare()](#prepare9) to prepare the resources again, call [reset()](#reset9) to reset the properties, or call [release()](#release9) to destroy the playback engine.|
3241|            '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.|
3242| 'error' | The AVPlayer enters this state when an irreversible error occurs in the playback engine. You can call [reset()](#reset9) to reset the properties 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.|
3243
3244## OnTrackChangeHandler<sup>12+</sup>
3245
3246type OnTrackChangeHandler = (index: number, isSelected: boolean) => void
3247
3248Describes the callback invoked for the track change event.
3249
3250**Atomic service API**: This API can be used in atomic services since API version 12.
3251
3252**System capability**: SystemCapability.Multimedia.Media.AVPlayer
3253
3254| Name  | Type  | Mandatory| Description                                                        |
3255| ------ | ------ | ------ | ---------------------------------------------------------- |
3256| index  | number | Yes| Index of the track that has changed.    |
3257| isSelected | boolean | Yes| Whether the track at the current index is selected. The value **true** means that the track at the current index is selected, and **false** means the opposite.|
3258
3259## OnAVPlayerStateChangeHandle<sup>12+</sup>
3260
3261type OnAVPlayerStateChangeHandle = (state: AVPlayerState, reason: StateChangeReason) => void
3262
3263Describes the callback invoked for the AVPlayer state change event.
3264
3265**Atomic service API**: This API can be used in atomic services since API version 12.
3266
3267**System capability**: SystemCapability.Multimedia.Media.AVPlayer
3268
3269| Name  | Type  | Mandatory| Description                                                        |
3270| ------ | ------ | ------ | ---------------------------------------------------------- |
3271| state  | [AVPlayerState](#avplayerstate9) | Yes| State of the AVPlayer.    |
3272| reason | [StateChangeReason](#statechangereason9) | Yes| Reason for the state change.|
3273
3274## OnBufferingUpdateHandler<sup>12+</sup>
3275
3276type OnBufferingUpdateHandler = (infoType: BufferingInfoType, value: number) => void
3277
3278Describes the callback invoked for the buffering update event.
3279
3280**Atomic service API**: This API can be used in atomic services since API version 12.
3281
3282**System capability**: SystemCapability.Multimedia.Media.AVPlayer
3283
3284| Name  | Type  | Mandatory| Description                                                        |
3285| ------ | ------ | ------ | ------------------------------------------------------------ |
3286| infoType  | [BufferingInfoType](#bufferinginfotype8) | Yes| Buffering information type.    |
3287| value | number | Yes| The value is fixed at **0**.|
3288
3289## OnVideoSizeChangeHandler<sup>12+</sup>
3290
3291type OnVideoSizeChangeHandler = (width: number, height: number) => void
3292
3293Describes the callback invoked for the video size change event.
3294
3295**Atomic service API**: This API can be used in atomic services since API version 12.
3296
3297**System capability**: SystemCapability.Multimedia.Media.AVPlayer
3298
3299| Name  | Type  | Mandatory| Description                                                        |
3300| ------ | ------ | ------ | ------------------------------------------------------------ |
3301| width  | number | Yes| Video width, in px.|
3302| height | number | Yes| Video height, in px.|
3303
3304## OnSeiMessageHandle<sup>18+</sup>
3305
3306type OnSeiMessageHandle = (messages: Array\<SeiMessage>, playbackPosition?: number) => void
3307
3308Describes the handle used to obtain SEI messages. This is used when in subscriptions to SEI message events, and the callback returns detailed SEI information.
3309
3310**Atomic service API**: This API can be used in atomic services since API version 18.
3311
3312**System capability**: SystemCapability.Multimedia.Media.AVPlayer
3313
3314**Parameters**
3315
3316| Name  |   Type  | Mandatory| Description                                                        |
3317| ------ | ------ | ---- | ------------------------------------------------------------ |
3318| messages | Array\<[SeiMessage](#seimessage18)> | Yes | Array of SEI messages.|
3319| playbackPosition | number | No | Current playback position, in milliseconds.|
3320
3321## OnSuperResolutionChanged <sup>18+</sup>
3322
3323type OnSuperResolutionChanged = (enabled: boolean) => void
3324
3325Describes 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.
3326
3327Super resolution is automatically disabled in either of the following cases:
3328* 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.
3329* 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.
3330
3331**Atomic service API**: This API can be used in atomic services since API version 18.
3332
3333**System capability**: SystemCapability.Multimedia.Media.AVPlayer
3334
3335| Name  | Type  | Mandatory| Description                                                        |
3336| ------ | ------ | ------ | ------------------------------------------------------------ |
3337| enabled  | boolean | Yes| Whether super resolution is enabled. The value **true** means that it is enabled, and **false** means the opposite.    |
3338
3339## OnPlaybackRateDone<sup>20+</sup>
3340
3341type OnPlaybackRateDone = (rate: number) => void
3342
3343Describes the callback invoked for the event indicating that the playback rate setting is complete.
3344
3345**Atomic service API**: This API can be used in atomic services since API version 20.
3346
3347**System capability**: SystemCapability.Multimedia.Media.AVPlayer
3348
3349| Name  | Type  | Mandatory| Description                                                        |
3350| ------ | ------ | ------ | ------------------------------------------------------------ |
3351| rate | number | Yes| Playback rate.|
3352
3353## AVFileDescriptor<sup>9+</sup>
3354
3355Describes 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.
3356
3357**Atomic service API**: This API can be used in atomic services since API version 11.
3358
3359**System capability**: SystemCapability.Multimedia.Media.Core
3360
3361| Name  | Type  | Mandatory| Description                                                        |
3362| ------ | ------ | ---- | ------------------------------------------------------------ |
3363| 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).   |
3364| 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.|
3365| 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.|
3366
3367## AVDataSrcDescriptor<sup>10+</sup>
3368
3369Defines 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.
3370
3371**Atomic service API**: This API can be used in atomic services since API version 11.
3372
3373**System capability**: SystemCapability.Multimedia.Media.AVPlayer
3374
3375| Name  | Type  | Mandatory| Description                                                        |
3376| ------ | ------ | ---- | ------------------------------------------------------------ |
3377| 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** property cannot be set, indicating that loop playback is unavailable.|
3378| 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.|
3379
3380## SubtitleInfo<sup>12+</sup>
3381
3382Describes the external subtitle information. When a subtitle update event is subscribed to, the information about the external subtitle is returned through a callback.
3383
3384**Atomic service API**: This API can be used in atomic services since API version 12.
3385
3386**System capability**: SystemCapability.Multimedia.Media.Core
3387
3388| Name  | Type  | Mandatory| Description                                                        |
3389| ------ | ------ | ---- | ------------------------------------------------------------ |
3390| text | string | No | Text information of the subtitle.|
3391| startTime | number | No | Start time for displaying the subtitle, in milliseconds.|
3392| duration | number | No| Duration for displaying the subtitle, in milliseconds.|
3393
3394## SeiMessage<sup>18+</sup>
3395
3396Describes the information of an SEI message.
3397
3398**Atomic service API**: This API can be used in atomic services since API version 18.
3399
3400**System capability**: SystemCapability.Multimedia.Media.Core
3401
3402| Name  | Type  | Read-Only| Optional | Description                                                        |
3403| ------ | ------ | ---- | ---- | ------------------------------------------------------------ |
3404| payloadType | number | No | No | Payload type of the SEI message.|
3405| payload | ArrayBuffer | No | No | Payload data of the SEI message.|
3406
3407## SeekMode<sup>8+</sup>
3408
3409Enumerates the video playback seek modes, which can be passed in the **seek** API.
3410
3411**System capability**: SystemCapability.Multimedia.Media.Core
3412
3413| Name          | Value  | Description                                                        |
3414| -------------- | ---- | ------------------------------------------------------------ |
3415| 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.|
3416| 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.|
3417| 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.|
3418| 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.|
3419
3420## SwitchMode<sup>12+</sup>
3421
3422Enumerates 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.
3423
3424**System capability**: SystemCapability.Multimedia.Media.Core
3425
3426| Name          | Value  | Description                                                        |
3427| -------------- | ---- | ------------------------------------------------------------ |
3428| 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.|
3429| 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.|
3430| 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.|
3431
3432## PlaybackSpeed<sup>8+</sup>
3433
3434Enumerates the video playback speeds, which can be passed in the **setSpeed** API.
3435
3436**Atomic service API**: This API can be used in atomic services since API version 12.
3437
3438**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
3439
3440| Name                | Value  | Description                          |
3441| -------------------- | ---- | ------------------------------ |
3442| 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.|
3443| 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.        |
3444| 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.|
3445| 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.|
3446| 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.|
3447| 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.|
3448| 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.|
3449| 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.|
3450| 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.|
3451| 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.|
3452
3453## VideoScaleType<sup>9+</sup>
3454
3455Enumerates the video scale modes.
3456
3457**Atomic service API**: This API can be used in atomic services since API version 12.
3458
3459**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
3460
3461| Name                       | Value  | Description                                             |
3462| ----------------------------| ---- | ------------------------------------------------ |
3463| VIDEO_SCALE_TYPE_FIT        | 0    | Default mode. The video will be stretched to fit the window.               |
3464| VIDEO_SCALE_TYPE_FIT_CROP   | 1    | Maintains the video's aspect ratio, and scales to fill the shortest side of the window, with the longer side cropped.    |
3465| VIDEO_SCALE_TYPE_FIT_ASPECT<sup>20+</sup> | 2    | Maintains the video's aspect ratio, and scales to fill the longer side of the window, with the shorter side centered and unfilled parts left black.<br>**Atomic service API**: This API can be used in atomic services since API version 20. |
3466
3467## MediaDescription<sup>8+</sup>
3468
3469Defines media information in key-value mode.
3470
3471**Atomic service API**: This API can be used in atomic services since API version 11.
3472
3473**System capability**: SystemCapability.Multimedia.Media.Core
3474
3475| Name         | Type  | Mandatory| Description                                                        |
3476| ------------- | ------ | ---- | ------------------------------------------------------------ |
3477| [key: string] | Object | Yes  | For details about the key range supported and the object type and range of each key, see [MediaDescriptionKey](#mediadescriptionkey8).|
3478
3479**Example**
3480
3481```ts
3482import { BusinessError } from '@kit.BasicServicesKit';
3483
3484function printfItemDescription(obj: media.MediaDescription, key: string) {
3485  let property: Object = obj[key];
3486  console.info('audio key is ' + key); // Specify a key. For details about the keys, see [MediaDescriptionKey].
3487  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].
3488}
3489
3490let avPlayer: media.AVPlayer | undefined = undefined;
3491media.createAVPlayer((err: BusinessError, player: media.AVPlayer) => {
3492  if(player != null) {
3493    avPlayer = player;
3494    console.info(`Succeeded in creating AVPlayer`);
3495    avPlayer.getTrackDescription((error: BusinessError, arrList: Array<media.MediaDescription>) => {
3496      if (arrList != null) {
3497        for (let i = 0; i < arrList.length; i++) {
3498          printfItemDescription(arrList[i], media.MediaDescriptionKey.MD_KEY_TRACK_TYPE);  // Print the MD_KEY_TRACK_TYPE value of each track.
3499        }
3500      } else {
3501        console.error(`Failed to get TrackDescription, error:${error}`);
3502      }
3503    });
3504  } else {
3505    console.error(`Failed to create AVPlayer, error message:${err.message}`);
3506  }
3507});
3508```
3509
3510## PlaybackInfo<sup>12+</sup>
3511
3512Defines the playback information in key-value pairs.
3513
3514**System capability**: SystemCapability.Multimedia.Media.Core
3515
3516| Name         | Type  | Mandatory| Description                                                        |
3517| ------------- | ------ | ---- | ------------------------------------------------------------ |
3518| [key: string] | Object | Yes  | For details about the key range supported and the object type and range of each key, see [PlaybackInfoKey](#playbackinfokey12).|
3519
3520**Example**
3521
3522```ts
3523import { BusinessError } from '@kit.BasicServicesKit';
3524
3525function printfPlaybackInfo(obj: media.PlaybackInfo, key: string) {
3526  let property: Object = obj[key];
3527  console.info('key is ' + key); // // Specify a key. For details about the keys, see [PlaybackInfoKey].
3528  console.info('value is ' + property); // Obtain the value of the key. The value can be any type. For details about the types, see [PlaybackInfoKey].
3529}
3530
3531let avPlayer: media.AVPlayer | undefined = undefined;
3532let playbackInfo: media.PlaybackInfo | undefined = undefined;
3533media.createAVPlayer(async (err: BusinessError, player: media.AVPlayer) => {
3534  if (player != null) {
3535    avPlayer = player;
3536    console.info(`Succeeded in creating AVPlayer`);
3537    if (avPlayer) {
3538      try {
3539        playbackInfo = await avPlayer.getPlaybackInfo();
3540        console.info(`AVPlayer getPlaybackInfo = ${JSON.stringify(playbackInfo)}`); // Print PlaybackInfo.
3541        printfPlaybackInfo(playbackInfo, media.PlaybackInfoKey.SERVER_IP_ADDRESS); // Print the IP address.
3542      } catch (error) {
3543        console.error(`error = ${error}`);
3544      }
3545    }
3546  } else {
3547    console.error(`Failed to create AVPlayer, error message:${err.message}`);
3548  }
3549});
3550```
3551
3552## AVRecorder<sup>9+</sup>
3553
3554A 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.
3555
3556For 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).
3557
3558> **NOTE**
3559>
3560> 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/arkts-apis-camera.md).
3561
3562### Properties
3563
3564**System capability**: SystemCapability.Multimedia.Media.AVRecorder
3565
3566| Name   | Type                                | Read-Only| Optional| Description              |
3567| ------- | ------------------------------------ | ---- | ---- | ------------------ |
3568| state9+ | [AVRecorderState](#avrecorderstate9) | Yes  | No  | AVRecorder state.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
3569
3570### prepare<sup>9+</sup>
3571
3572prepare(config: AVRecorderConfig, callback: AsyncCallback\<void>): void
3573
3574Sets audio and video recording parameters. This API uses an asynchronous callback to return the result.
3575
3576**Required permissions:** ohos.permission.MICROPHONE
3577
3578This permission is required only if audio recording is involved.
3579
3580To 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/arkts-apis-camera.md).
3581
3582**System capability**: SystemCapability.Multimedia.Media.AVRecorder
3583
3584**Parameters**
3585
3586| Name  | Type                                  | Mandatory| Description                                 |
3587| -------- | -------------------------------------- | ---- | ------------------------------------- |
3588| config   | [AVRecorderConfig](#avrecorderconfig9) | Yes  | Audio and video recording parameters to set.           |
3589| callback | AsyncCallback\<void>                   | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
3590
3591**Error codes**
3592
3593For details about the error codes, see [Media Error Codes](errorcode-media.md).
3594
3595| ID| Error Message                               |
3596| -------- | --------------------------------------- |
3597| 201      | Permission denied. Return by callback.  |
3598| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed.    |
3599| 5400102  | Operate not permit. Return by callback. |
3600| 5400105  | Service died. Return by callback.       |
3601
3602**Example**
3603
3604```ts
3605import { BusinessError } from '@kit.BasicServicesKit';
3606
3607// Configure the parameters based on those supported by the hardware device.
3608let avRecorderProfile: media.AVRecorderProfile = {
3609  audioBitrate : 48000,
3610  audioChannels : 2,
3611  audioCodec : media.CodecMimeType.AUDIO_AAC,
3612  audioSampleRate : 48000,
3613  fileFormat : media.ContainerFormatType.CFT_MPEG_4,
3614  videoBitrate : 2000000,
3615  videoCodec : media.CodecMimeType.VIDEO_AVC,
3616  videoFrameWidth : 640,
3617  videoFrameHeight : 480,
3618  videoFrameRate : 30
3619};
3620let avRecorderConfig: media.AVRecorderConfig = {
3621  audioSourceType : media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC,
3622  videoSourceType : media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV,
3623  profile : avRecorderProfile,
3624  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.
3625  rotation: 0, // The value can be 0, 90, 180, or 270. If any other value is used, prepare() reports an error.
3626  location : { latitude : 30, longitude : 130 }
3627};
3628
3629avRecorder.prepare(avRecorderConfig, (err: BusinessError) => {
3630  if (err) {
3631    console.error('Failed to prepare and error is ' + err.message);
3632  } else {
3633    console.info('Succeeded in preparing');
3634  }
3635});
3636```
3637
3638### prepare<sup>9+</sup>
3639
3640prepare(config: AVRecorderConfig): Promise\<void>
3641
3642Sets audio and video recording parameters. This API uses a promise to return the result.
3643
3644**Required permissions:** ohos.permission.MICROPHONE
3645
3646This permission is required only if audio recording is involved.
3647
3648To 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/arkts-apis-camera.md).
3649
3650**Atomic service API**: This API can be used in atomic services since API version 12.
3651
3652**System capability**: SystemCapability.Multimedia.Media.AVRecorder
3653
3654**Parameters**
3655
3656| Name| Type                                  | Mandatory| Description                      |
3657| ------ | -------------------------------------- | ---- | -------------------------- |
3658| config | [AVRecorderConfig](#avrecorderconfig9) | Yes  | Audio and video recording parameters to set.|
3659
3660**Return value**
3661
3662| Type          | Description                                      |
3663| -------------- | ------------------------------------------ |
3664| Promise\<void> | Promise that returns no value.|
3665
3666**Error codes**
3667
3668For details about the error codes, see [Media Error Codes](errorcode-media.md).
3669
3670| ID| Error Message                              |
3671| -------- | -------------------------------------- |
3672| 201      | Permission denied. Return by promise.  |
3673| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed.    |
3674| 5400102  | Operate not permit. Return by promise. |
3675| 5400105  | Service died. Return by promise.       |
3676
3677**Example**
3678
3679```ts
3680import { BusinessError } from '@kit.BasicServicesKit';
3681
3682// Configure the parameters based on those supported by the hardware device.
3683let avRecorderProfile: media.AVRecorderProfile = {
3684  audioBitrate : 48000,
3685  audioChannels : 2,
3686  audioCodec : media.CodecMimeType.AUDIO_AAC,
3687  audioSampleRate : 48000,
3688  fileFormat : media.ContainerFormatType.CFT_MPEG_4,
3689  videoBitrate : 2000000,
3690  videoCodec : media.CodecMimeType.VIDEO_AVC,
3691  videoFrameWidth : 640,
3692  videoFrameHeight : 480,
3693  videoFrameRate : 30
3694};
3695let avRecorderConfig: media.AVRecorderConfig = {
3696  audioSourceType : media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC,
3697  videoSourceType : media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV,
3698  profile : avRecorderProfile,
3699  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.
3700  rotation: 0, // The value can be 0, 90, 180, or 270. If any other value is used, prepare() reports an error.
3701  location : { latitude : 30, longitude : 130 }
3702};
3703
3704avRecorder.prepare(avRecorderConfig).then(() => {
3705  console.info('Succeeded in preparing');
3706}).catch((err: BusinessError) => {
3707  console.error('Failed to prepare and catch error is ' + err.message);
3708});
3709```
3710
3711### getInputSurface<sup>9+</sup>
3712
3713getInputSurface(callback: AsyncCallback\<string>): void
3714
3715Obtains 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.
3716
3717Note 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.
3718
3719This API can be called only after the [prepare()](#prepare9-2) API is called.
3720
3721**System capability**: SystemCapability.Multimedia.Media.AVRecorder
3722
3723**Parameters**
3724
3725| Name  | Type                  | Mandatory| Description                       |
3726| -------- | ---------------------- | ---- | --------------------------- |
3727| 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.|
3728
3729**Error codes**
3730
3731For details about the error codes, see [Media Error Codes](errorcode-media.md).
3732
3733| ID| Error Message                               |
3734| -------- | --------------------------------------- |
3735| 5400102  | Operate not permit. Return by callback. |
3736| 5400103  | IO error. Return by callback.           |
3737| 5400105  | Service died. Return by callback.       |
3738
3739**Example**
3740
3741```ts
3742import { BusinessError } from '@kit.BasicServicesKit';
3743let surfaceID: string; // The surfaceID is transferred to the camera API to create a videoOutput instance.
3744
3745avRecorder.getInputSurface((err: BusinessError, surfaceId: string) => {
3746  if (err) {
3747    console.error('Failed to do getInputSurface and error is ' + err.message);
3748  } else {
3749    console.info('Succeeded in doing getInputSurface');
3750    surfaceID = surfaceId;
3751  }
3752});
3753
3754```
3755
3756### getInputSurface<sup>9+</sup>
3757
3758getInputSurface(): Promise\<string>
3759
3760Obtains 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.
3761
3762Note 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.
3763
3764This API can be called only after the [prepare()](#prepare9-3) API is called.
3765
3766**System capability**: SystemCapability.Multimedia.Media.AVRecorder
3767
3768**Return value**
3769
3770| Type            | Description                            |
3771| ---------------- | -------------------------------- |
3772| Promise\<string> | Promise used to return the result.|
3773
3774**Error codes**
3775
3776For details about the error codes, see [Media Error Codes](errorcode-media.md).
3777
3778| ID| Error Message                              |
3779| -------- | -------------------------------------- |
3780| 5400102  | Operate not permit. Return by promise. |
3781| 5400103  | IO error. Return by promise.           |
3782| 5400105  | Service died. Return by promise.       |
3783
3784**Example**
3785
3786```ts
3787import { BusinessError } from '@kit.BasicServicesKit';
3788let surfaceID: string; // The surfaceID is transferred to the camera API to create a videoOutput instance.
3789
3790avRecorder.getInputSurface().then((surfaceId: string) => {
3791  console.info('Succeeded in getting InputSurface');
3792  surfaceID = surfaceId;
3793}).catch((err: BusinessError) => {
3794  console.error('Failed to get InputSurface and catch error is ' + err.message);
3795});
3796```
3797
3798### updateRotation<sup>12+</sup>
3799
3800updateRotation(rotation: number): Promise\<void>
3801
3802Updates the video rotation angle. This API uses a promise to return the result.
3803
3804This API can be called only after the [prepare()](#prepare9-3) event is triggered and before the [start()](#start9) API is called.
3805
3806**System capability**: SystemCapability.Multimedia.Media.AVRecorder
3807
3808**Parameters**
3809
3810| Name  | Type                | Mandatory| Description                       |
3811| -------- | -------------------- | ---- | --------------------------- |
3812| rotation | number | Yes  | Rotation angle, which can only be 0, 90, 180, or 270 degrees.|
3813
3814**Return value**
3815
3816| Type            | Description                            |
3817| ---------------- | -------------------------------- |
3818| Promise\<void> | Promise that returns no value.|
3819
3820**Error codes**
3821
3822For details about the error codes, see [Media Error Codes](errorcode-media.md).
3823
3824| ID| Error Message                              |
3825| -------- | -------------------------------------- |
3826|   401    | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed.   |
3827| 5400102  | Operation not allowed. Return by promise. |
3828| 5400103  | IO error. Return by promise.           |
3829| 5400105  | Service died. Return by promise.       |
3830
3831**Example**
3832
3833```ts
3834import { BusinessError } from '@kit.BasicServicesKit';
3835
3836let rotation = 90;
3837
3838avRecorder.updateRotation(rotation).then(() => {
3839  console.info('Succeeded in updateRotation');
3840}).catch((err: BusinessError) => {
3841  console.error('Failed to updateRotation and catch error is ' + err.message);
3842});
3843```
3844
3845### setWillMuteWhenInterrupted<sup>20+</sup>
3846
3847setWillMuteWhenInterrupted(muteWhenInterrupted: boolean): Promise&lt;void&gt;
3848
3849Sets whether to mute the current audio recording stream when an audio interruption occurs. This API uses a promise to return the result.
3850
3851**System capability**: SystemCapability.Multimedia.Media.AVRecorder
3852
3853**Parameters**
3854
3855| Name    | Type            | Mandatory  | Description                                                     |
3856| ---------- |---------------- | ------ |---------------------------------------------------------|
3857| muteWhenInterrupted | boolean | Yes | Whether to mute the current audio recording stream during an audio interruption. The value **true** means to mute it, and **false** (default value) means the opposite.|
3858
3859**Return value**
3860
3861| Type               | Description                         |
3862| ------------------- | ----------------------------- |
3863| Promise&lt;void&gt;| 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  | Operation not allowed. Return by promise. |
3872| 5400105  | Service died. Return by promise.       |
3873
3874**Example**
3875
3876```ts
3877import { BusinessError } from '@kit.BasicServicesKit';
3878
3879avRecorder.setWillMuteWhenInterrupted(true).then(() => {
3880  console.info('setWillMuteWhenInterrupted Success!');
3881}).catch((err: BusinessError) => {
3882  console.error(`setWillMuteWhenInterrupted Fail: ${err}`);
3883});
3884```
3885
3886### start<sup>9+</sup>
3887
3888start(callback: AsyncCallback\<void>): void
3889
3890Starts recording. This API uses an asynchronous callback to return the result.
3891
3892For 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.
3893
3894**System capability**: SystemCapability.Multimedia.Media.AVRecorder
3895
3896**Parameters**
3897
3898| Name  | Type                | Mandatory| Description                        |
3899| -------- | -------------------- | ---- | ---------------------------- |
3900| callback | AsyncCallback\<void> | Yes  |Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
3901
3902**Error codes**
3903
3904For details about the error codes, see [Media Error Codes](errorcode-media.md).
3905
3906| ID| Error Message                               |
3907| -------- | --------------------------------------- |
3908| 5400102  | Operate not permit. Return by callback. |
3909| 5400103  | IO error. Return by callback.           |
3910| 5400105  | Service died. Return by callback.       |
3911
3912**Example**
3913
3914```ts
3915import { BusinessError } from '@kit.BasicServicesKit';
3916
3917avRecorder.start((err: BusinessError) => {
3918  if (err) {
3919    console.error('Failed to start AVRecorder and error is ' + err.message);
3920  } else {
3921    console.info('Succeeded in starting AVRecorder');
3922  }
3923});
3924```
3925
3926### start<sup>9+</sup>
3927
3928start(): Promise\<void>
3929
3930Starts recording. This API uses a promise to return the result.
3931
3932For 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.
3933
3934**Atomic service API**: This API can be used in atomic services since API version 12.
3935
3936**System capability**: SystemCapability.Multimedia.Media.AVRecorder
3937
3938**Return value**
3939
3940| Type          | Description                                 |
3941| -------------- | ------------------------------------- |
3942| Promise\<void> | Promise that returns no value.|
3943
3944**Error codes**
3945
3946For details about the error codes, see [Media Error Codes](errorcode-media.md).
3947
3948| ID| Error Message                              |
3949| -------- | -------------------------------------- |
3950| 5400102  | Operate not permit. Return by promise. |
3951| 5400103  | IO error. Return by promise.           |
3952| 5400105  | Service died. Return by promise.       |
3953
3954**Example**
3955
3956```ts
3957import { BusinessError } from '@kit.BasicServicesKit';
3958
3959avRecorder.start().then(() => {
3960  console.info('Succeeded in starting AVRecorder');
3961}).catch((err: BusinessError) => {
3962  console.error('Failed to start AVRecorder and catch error is ' + err.message);
3963});
3964```
3965
3966### pause<sup>9+</sup>
3967
3968pause(callback: AsyncCallback\<void>): void
3969
3970Pauses recording. This API uses an asynchronous callback to return the result.
3971
3972This API can be called only after the [start()](#start9) API is called. You can call [resume()](#resume9) to resume recording.
3973
3974**System capability**: SystemCapability.Multimedia.Media.AVRecorder
3975
3976**Parameters**
3977
3978| Name  | Type                | Mandatory| Description                       |
3979| -------- | -------------------- | ---- | --------------------------- |
3980| callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
3981
3982**Error codes**
3983
3984For details about the error codes, see [Media Error Codes](errorcode-media.md).
3985
3986| ID| Error Message                               |
3987| -------- | --------------------------------------- |
3988| 5400102  | Operate not permit. Return by callback. |
3989| 5400103  | IO error. Return by callback.           |
3990| 5400105  | Service died. Return by callback.       |
3991
3992**Example**
3993
3994```ts
3995import { BusinessError } from '@kit.BasicServicesKit';
3996
3997avRecorder.pause((err: BusinessError) => {
3998  if (err) {
3999    console.error('Failed to pause AVRecorder and error is ' + err.message);
4000  } else {
4001    console.info('Succeeded in pausing');
4002  }
4003});
4004```
4005
4006### pause<sup>9+</sup>
4007
4008pause(): Promise\<void>
4009
4010Pauses recording. This API uses a promise to return the result.
4011
4012This API can be called only after the [start()](#start9-1) API is called. You can call [resume()](#resume9-1) to resume recording.
4013
4014**Atomic service API**: This API can be used in atomic services since API version 12.
4015
4016**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4017
4018**Return value**
4019
4020| Type          | Description                                 |
4021| -------------- | ------------------------------------- |
4022| Promise\<void> | Promise that returns no value.|
4023
4024**Error codes**
4025
4026For details about the error codes, see [Media Error Codes](errorcode-media.md).
4027
4028| ID| Error Message                              |
4029| -------- | -------------------------------------- |
4030| 5400102  | Operate not permit. Return by promise. |
4031| 5400103  | IO error. Return by promise.           |
4032| 5400105  | Service died. Return by promise.       |
4033
4034**Example**
4035
4036```ts
4037import { BusinessError } from '@kit.BasicServicesKit';
4038
4039avRecorder.pause().then(() => {
4040  console.info('Succeeded in pausing');
4041}).catch((err: BusinessError) => {
4042  console.error('Failed to pause AVRecorder and catch error is ' + err.message);
4043});
4044```
4045
4046### resume<sup>9+</sup>
4047
4048resume(callback: AsyncCallback\<void>): void
4049
4050Resumes recording. This API uses an asynchronous callback to return the result.
4051
4052This API can be called only after the [pause()](#pause9-2) API is called.
4053
4054**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4055
4056**Parameters**
4057
4058| Name  | Type                | Mandatory| Description                        |
4059| -------- | -------------------- | ---- | ---------------------------- |
4060| callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
4061
4062**Error codes**
4063
4064For details about the error codes, see [Media Error Codes](errorcode-media.md).
4065
4066| ID| Error Message                               |
4067| -------- | --------------------------------------- |
4068| 5400102  | Operate not permit. Return by callback. |
4069| 5400103  | IO error. Return by callback.           |
4070| 5400105  | Service died. Return by callback.       |
4071
4072**Example**
4073
4074```ts
4075import { BusinessError } from '@kit.BasicServicesKit';
4076
4077avRecorder.resume((err: BusinessError) => {
4078  if (err) {
4079    console.error('Failed to resume AVRecorder and error is ' + err.message);
4080  } else {
4081    console.info('Succeeded in resuming AVRecorder');
4082  }
4083});
4084```
4085
4086### resume<sup>9+</sup>
4087
4088resume(): Promise\<void>
4089
4090Resumes recording. This API uses a promise to return the result.
4091
4092This API can be called only after the [pause()](#pause9-3) API is called.
4093
4094**Atomic service API**: This API can be used in atomic services since API version 12.
4095
4096**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4097
4098**Return value**
4099
4100| Type          | Description                                 |
4101| -------------- | ------------------------------------- |
4102| Promise\<void> | Promise that returns no value.|
4103
4104**Error codes**
4105
4106For details about the error codes, see [Media Error Codes](errorcode-media.md).
4107
4108| ID| Error Message                              |
4109| -------- | -------------------------------------- |
4110| 5400102  | Operate not permit. Return by promise. |
4111| 5400103  | IO error. Return by promise.           |
4112| 5400105  | Service died. Return by promise.       |
4113
4114**Example**
4115
4116```ts
4117import { BusinessError } from '@kit.BasicServicesKit';
4118
4119avRecorder.resume().then(() => {
4120  console.info('Succeeded in resuming AVRecorder');
4121}).catch((err: BusinessError) => {
4122  console.error('Failed to resume  AVRecorder failed and catch error is ' + err.message);
4123});
4124```
4125
4126### stop<sup>9+</sup>
4127
4128stop(callback: AsyncCallback\<void>): void
4129
4130Stops recording. This API uses an asynchronous callback to return the result.
4131
4132This API can be called only after the [start()](#start9) or [pause()](#pause9-2) API is called.
4133
4134For 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.
4135
4136**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4137
4138**Parameters**
4139
4140| Name  | Type                | Mandatory| Description                        |
4141| -------- | -------------------- | ---- | ---------------------------- |
4142| callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
4143
4144**Error codes**
4145
4146For details about the error codes, see [Media Error Codes](errorcode-media.md).
4147
4148| ID| Error Message                               |
4149| -------- | --------------------------------------- |
4150| 5400102  | Operate not permit. Return by callback. |
4151| 5400103  | IO error. Return by callback.           |
4152| 5400105  | Service died. Return by callback.       |
4153
4154**Example**
4155
4156```ts
4157import { BusinessError } from '@kit.BasicServicesKit';
4158
4159avRecorder.stop((err: BusinessError) => {
4160  if (err) {
4161    console.error('Failed to stop AVRecorder and error is ' + err.message);
4162  } else {
4163    console.info('Succeeded in stopping AVRecorder');
4164  }
4165});
4166```
4167
4168### stop<sup>9+</sup>
4169
4170stop(): Promise\<void>
4171
4172Stops recording. This API uses a promise to return the result.
4173
4174This API can be called only after the [start()](#start9-1) or [pause()](#pause9-3) API is called.
4175
4176For 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.
4177
4178**Atomic service API**: This API can be used in atomic services since API version 12.
4179
4180**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4181
4182**Return value**
4183
4184| Type          | Description                                 |
4185| -------------- | ------------------------------------- |
4186| Promise\<void> | Promise that returns no value.|
4187
4188**Error codes**
4189
4190For details about the error codes, see [Media Error Codes](errorcode-media.md).
4191
4192| ID| Error Message                              |
4193| -------- | -------------------------------------- |
4194| 5400102  | Operate not permit. Return by promise. |
4195| 5400103  | IO error. Return by promise.           |
4196| 5400105  | Service died. Return by promise.       |
4197
4198**Example**
4199
4200```ts
4201import { BusinessError } from '@kit.BasicServicesKit';
4202
4203avRecorder.stop().then(() => {
4204  console.info('Succeeded in stopping AVRecorder');
4205}).catch((err: BusinessError) => {
4206  console.error('Failed to stop AVRecorder and catch error is ' + err.message);
4207});
4208```
4209
4210### reset<sup>9+</sup>
4211
4212reset(callback: AsyncCallback\<void>): void
4213
4214Resets audio and video recording. This API uses an asynchronous callback to return the result.
4215
4216For 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.
4217
4218**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4219
4220**Parameters**
4221
4222| Name  | Type                | Mandatory| Description                          |
4223| -------- | -------------------- | ---- | ------------------------------ |
4224| callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
4225
4226**Error codes**
4227
4228For details about the error codes, see [Media Error Codes](errorcode-media.md).
4229
4230| ID| Error Message                         |
4231| -------- | --------------------------------- |
4232| 5400103  | IO error. Return by callback.     |
4233| 5400105  | Service died. Return by callback. |
4234
4235**Example**
4236
4237```ts
4238import { BusinessError } from '@kit.BasicServicesKit';
4239
4240avRecorder.reset((err: BusinessError) => {
4241  if (err) {
4242    console.error('Failed to reset AVRecorder and error is ' + err.message);
4243  } else {
4244    console.info('Succeeded in resetting AVRecorder');
4245  }
4246});
4247```
4248
4249### reset<sup>9+</sup>
4250
4251reset(): Promise\<void>
4252
4253Resets audio and video recording. This API uses a promise to return the result.
4254
4255For 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.
4256
4257**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4258
4259**Return value**
4260
4261| Type          | Description                                   |
4262| -------------- | --------------------------------------- |
4263| Promise\<void> | Promise that returns no value.|
4264
4265**Error codes**
4266
4267For details about the error codes, see [Media Error Codes](errorcode-media.md).
4268
4269| ID| Error Message                        |
4270| -------- | -------------------------------- |
4271| 5400103  | IO error. Return by promise.     |
4272| 5400105  | Service died. Return by promise. |
4273
4274**Example**
4275
4276```ts
4277import { BusinessError } from '@kit.BasicServicesKit';
4278
4279avRecorder.reset().then(() => {
4280  console.info('Succeeded in resetting AVRecorder');
4281}).catch((err: BusinessError) => {
4282  console.error('Failed to reset and catch error is ' + err.message);
4283});
4284```
4285
4286### release<sup>9+</sup>
4287
4288release(callback: AsyncCallback\<void>): void
4289
4290Releases the audio and video recording resources. This API uses an asynchronous callback to return the result.
4291
4292After the resources are released, you can no longer perform any operation on the AVRecorder instance.
4293
4294**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4295
4296**Parameters**
4297
4298| Name  | Type                | Mandatory| Description                              |
4299| -------- | -------------------- | ---- | ---------------------------------- |
4300| callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
4301
4302**Error codes**
4303
4304For details about the error codes, see [Media Error Codes](errorcode-media.md).
4305
4306| ID| Error Message                         |
4307| -------- | --------------------------------- |
4308| 5400105  | Service died. Return by callback. |
4309
4310**Example**
4311
4312```ts
4313import { BusinessError } from '@kit.BasicServicesKit';
4314
4315avRecorder.release((err: BusinessError) => {
4316  if (err) {
4317    console.error('Failed to release AVRecorder and error is ' + err.message);
4318  } else {
4319    console.info('Succeeded in releasing AVRecorder');
4320  }
4321});
4322```
4323
4324### release<sup>9+</sup>
4325
4326release(): Promise\<void>
4327
4328Releases the audio and video recording resources. This API uses a promise to return the result.
4329
4330After the resources are released, you can no longer perform any operation on the AVRecorder instance.
4331
4332**Atomic service API**: This API can be used in atomic services since API version 12.
4333
4334**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4335
4336**Return value**
4337
4338| Type          | Description                                       |
4339| -------------- | ------------------------------------------- |
4340| Promise\<void> | Promise that returns no value.|
4341
4342**Error codes**
4343
4344For details about the error codes, see [Media Error Codes](errorcode-media.md).
4345
4346| ID| Error Message                         |
4347| -------- | --------------------------------- |
4348| 5400105  | Service died. Return by callback. |
4349
4350**Example**
4351
4352```ts
4353import { BusinessError } from '@kit.BasicServicesKit';
4354
4355avRecorder.release().then(() => {
4356  console.info('Succeeded in releasing AVRecorder');
4357}).catch((err: BusinessError) => {
4358  console.error('Failed to release AVRecorder and catch error is ' + err.message);
4359});
4360```
4361
4362### getCurrentAudioCapturerInfo<sup>11+</sup>
4363
4364getCurrentAudioCapturerInfo(callback: AsyncCallback\<audio.AudioCapturerChangeInfo>): void
4365
4366Obtains the information about the current audio capturer. This API uses an asynchronous callback to return the result.
4367
4368This 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.
4369
4370**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4371
4372**Parameters**
4373
4374| Name  | Type                                                        | Mandatory| Description                                |
4375| -------- | ------------------------------------------------------------ | ---- | ------------------------------------ |
4376| 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.|
4377
4378**Error codes**
4379
4380For details about the error codes, see [Media Error Codes](errorcode-media.md).
4381
4382| ID| Error Message                                  |
4383| -------- | ------------------------------------------ |
4384| 5400102  | Operation not allowed. |
4385| 5400103  | I/O error.             |
4386| 5400105  | Service died. Return by callback.          |
4387
4388**Example**
4389
4390```ts
4391import { audio } from '@kit.AudioKit';
4392
4393let currentCapturerInfo: audio.AudioCapturerChangeInfo;
4394
4395avRecorder.getCurrentAudioCapturerInfo((err: BusinessError, capturerInfo: audio.AudioCapturerChangeInfo) => {
4396  if (err) {
4397    console.error('Failed to get CurrentAudioCapturerInfo and error is ' + err.message);
4398  } else {
4399    console.info('Succeeded in getting CurrentAudioCapturerInfo');
4400    currentCapturerInfo = capturerInfo;
4401  }
4402});
4403```
4404
4405### getCurrentAudioCapturerInfo<sup>11+</sup>
4406
4407getCurrentAudioCapturerInfo(): Promise\<audio.AudioCapturerChangeInfo>
4408
4409Obtains the information about the current audio capturer. This API uses a promise to return the result.
4410
4411This 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.
4412
4413**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4414
4415**Return value**
4416
4417| Type                                                        | Description                                             |
4418| ------------------------------------------------------------ | ------------------------------------------------- |
4419| Promise\<[audio.AudioCapturerChangeInfo](../apis-audio-kit/js-apis-audio.md#audiocapturerchangeinfo9)> | Promise used to return the audio capturer information.|
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| 5400103  | I/O error.                       |
4429| 5400105  | Service died. Return by promise. |
4430
4431**Example**
4432
4433```ts
4434import { audio } from '@kit.AudioKit';
4435
4436let currentCapturerInfo: audio.AudioCapturerChangeInfo;
4437
4438avRecorder.getCurrentAudioCapturerInfo().then((capturerInfo: audio.AudioCapturerChangeInfo) => {
4439  console.info('Succeeded in getting CurrentAudioCapturerInfo');
4440  currentCapturerInfo = capturerInfo;
4441}).catch((err: BusinessError) => {
4442  console.error('Failed to get CurrentAudioCapturerInfo and catch error is ' + err.message);
4443});
4444```
4445
4446### getAudioCapturerMaxAmplitude<sup>11+</sup>
4447
4448getAudioCapturerMaxAmplitude(callback: AsyncCallback\<number>): void
4449
4450Obtains the maximum amplitude of the current audio capturer. This API uses an asynchronous callback to return the result.
4451
4452This 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.
4453
4454The 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.
4455
4456**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4457
4458**Parameters**
4459
4460| Name  | Type                  | Mandatory| Description                                |
4461| -------- | ---------------------- | ---- | ------------------------------------ |
4462| 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.|
4463
4464**Error codes**
4465
4466For details about the error codes, see [Media Error Codes](errorcode-media.md).
4467
4468| ID| Error Message                                  |
4469| -------- | ------------------------------------------ |
4470| 5400102  | Operation not allowed. |
4471| 5400105  | Service died. Return by callback.          |
4472
4473**Example**
4474
4475```ts
4476let maxAmplitude: number;
4477
4478avRecorder.getAudioCapturerMaxAmplitude((err: BusinessError, amplitude: number) => {
4479  if (err) {
4480    console.error('Failed to get AudioCapturerMaxAmplitude and error is ' + err.message);
4481  } else {
4482    console.info('Succeeded in getting AudioCapturerMaxAmplitude');
4483    maxAmplitude = amplitude;
4484  }
4485});
4486```
4487
4488### getAudioCapturerMaxAmplitude<sup>11+</sup>
4489
4490getAudioCapturerMaxAmplitude(): Promise\<number>
4491
4492Obtains the maximum amplitude of the current audio capturer. This API uses a promise to return the result.
4493
4494This 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.
4495
4496The 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.
4497
4498**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4499
4500**Return value**
4501
4502| Type            | Description                                             |
4503| ---------------- | ------------------------------------------------- |
4504| Promise\<number>| Promise used to return the maximum amplitude obtained.|
4505
4506**Error codes**
4507
4508For details about the error codes, see [Media Error Codes](errorcode-media.md).
4509
4510| ID| Error Message                        |
4511| -------- | -------------------------------- |
4512| 5400102  | Operation not allowed.           |
4513| 5400105  | Service died. Return by promise. |
4514
4515**Example**
4516
4517```ts
4518let maxAmplitude: number;
4519
4520avRecorder.getAudioCapturerMaxAmplitude().then((amplitude: number) => {
4521  console.info('Succeeded in getting AudioCapturerMaxAmplitude');
4522  maxAmplitude = amplitude;
4523}).catch((err: BusinessError) => {
4524  console.error('Failed to get AudioCapturerMaxAmplitude and catch error is ' + err.message);
4525});
4526```
4527
4528### getAvailableEncoder<sup>11+</sup>
4529
4530getAvailableEncoder(callback: AsyncCallback\<Array\<EncoderInfo>>): void
4531
4532Obtains available encoders. This API uses an asynchronous callback to return the result.
4533
4534**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4535
4536**Parameters**
4537
4538| Name  | Type                                                 | Mandatory| Description                                |
4539| -------- | ----------------------------------------------------- | ---- | ------------------------------------ |
4540| 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.|
4541
4542**Error codes**
4543
4544For details about the error codes, see [Media Error Codes](errorcode-media.md).
4545
4546| ID| Error Message                                  |
4547| -------- | ------------------------------------------ |
4548| 5400102  | Operation not allowed. |
4549| 5400105  | Service died. Return by callback.          |
4550
4551**Example**
4552
4553```ts
4554let encoderInfo: media.EncoderInfo;
4555
4556avRecorder.getAvailableEncoder((err: BusinessError, info: media.EncoderInfo[]) => {
4557  if (err) {
4558    console.error('Failed to get AvailableEncoder and error is ' + err.message);
4559  } else {
4560    console.info('Succeeded in getting AvailableEncoder');
4561    encoderInfo = info[0];
4562  }
4563});
4564```
4565
4566### getAvailableEncoder<sup>11+</sup>
4567
4568getAvailableEncoder(): Promise\<Array\<EncoderInfo>>
4569
4570Obtains available encoders. This API uses an asynchronous callback to return the result.
4571
4572**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4573
4574**Return value**
4575
4576| Type                                           | Description                                           |
4577| ----------------------------------------------- | ----------------------------------------------- |
4578| Promise\<Array\<[EncoderInfo](#encoderinfo11)>> | Promise used to return the information about the available encoders.|
4579
4580**Error codes**
4581
4582For details about the error codes, see [Media Error Codes](errorcode-media.md).
4583
4584| ID| Error Message                        |
4585| -------- | -------------------------------- |
4586| 5400102  | Operation not allowed.           |
4587| 5400105  | Service died. Return by promise. |
4588
4589**Example**
4590
4591```ts
4592let encoderInfo: media.EncoderInfo;
4593
4594avRecorder.getAvailableEncoder().then((info: media.EncoderInfo[]) => {
4595  console.info('Succeeded in getting AvailableEncoder');
4596  encoderInfo = info[0];
4597}).catch((err: BusinessError) => {
4598  console.error('Failed to get AvailableEncoder and catch error is ' + err.message);
4599});
4600```
4601
4602### getAVRecorderConfig<sup>11+</sup>
4603
4604getAVRecorderConfig(callback: AsyncCallback\<AVRecorderConfig>): void
4605
4606Obtains the real-time configuration of this AVRecorder. This API uses an asynchronous callback to return the result.
4607
4608This API can be called only after [prepare()](#prepare9-2) is called.
4609
4610**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4611
4612**Parameters**
4613
4614| Name  | Type                  | Mandatory| Description                       |
4615| -------- | ---------------------- | ---- | --------------------------- |
4616| 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.|
4617
4618**Error codes**
4619
4620For details about the error codes, see [Media Error Codes](errorcode-media.md).
4621
4622| ID| Error Message                                  |
4623| -------- | ------------------------------------------ |
4624| 5400102  | Operate not permit. Return by callback. |
4625| 5400103  | IO error. Return by callback.             |
4626| 5400105  | Service died. Return by callback.          |
4627
4628**Example**
4629
4630```ts
4631import { BusinessError } from '@kit.BasicServicesKit';
4632
4633let avConfig: media.AVRecorderConfig;
4634
4635avRecorder.getAVRecorderConfig((err: BusinessError, config: media.AVRecorderConfig) => {
4636  if (err) {
4637    console.error('Failed to get avConfig and error is ' + err.message);
4638  } else {
4639    console.info('Succeeded in getting AVRecorderConfig');
4640    avConfig = config;
4641  }
4642});
4643```
4644
4645### getAVRecorderConfig<sup>11+</sup>
4646
4647getAVRecorderConfig(): Promise\<AVRecorderConfig>;
4648
4649Obtains the real-time configuration of this AVRecorder. This API uses a promise to return the result.
4650
4651This API can be called only after [prepare()](#prepare9-3) is called.
4652
4653**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4654
4655**Return value**
4656
4657| Type            | Description                            |
4658| ---------------- | -------------------------------- |
4659| Promise\<[AVRecorderConfig](#avrecorderconfig9)> | Promise used to return the real-time configuration.|
4660
4661**Error codes**
4662
4663For details about the error codes, see [Media Error Codes](errorcode-media.md).
4664
4665| ID| Error Message                                 |
4666| -------- | ----------------------------------------- |
4667| 5400102  | Operate not permit. Return by promise. |
4668| 5400103  | IO error. Return by promise.             |
4669| 5400105  | Service died. Return by promise.          |
4670
4671**Example**
4672
4673```ts
4674import { BusinessError } from '@kit.BasicServicesKit';
4675
4676let avConfig: media.AVRecorderConfig;
4677
4678avRecorder.getAVRecorderConfig().then((config: media.AVRecorderConfig) => {
4679  console.info('Succeeded in getting AVRecorderConfig');
4680  avConfig = config;
4681}).catch((err: BusinessError) => {
4682  console.error('Failed to get AVRecorderConfig and catch error is ' + err.message);
4683});
4684```
4685
4686### on('stateChange')<sup>9+</sup>
4687
4688on(type: 'stateChange', callback: OnAVRecorderStateChangeHandler): void
4689
4690Subscribes 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.
4691
4692**Atomic service API**: This API can be used in atomic services since API version 12.
4693
4694**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4695
4696**Parameters**
4697
4698| Name  | Type    | Mandatory| Description                                                        |
4699| -------- | -------- | ---- | ------------------------------------------------------------ |
4700| type     | string   | Yes  | Event type, which is **'stateChange'** in this case. This event can be triggered by both user operations and the system.|
4701| callback | [OnAVRecorderStateChangeHandler](#onavrecorderstatechangehandler12) | Yes  | Callback invoked when the event is triggered.|
4702
4703**Error codes**
4704
4705For details about the error codes, see [Media Error Codes](errorcode-media.md).
4706
4707| ID| Error Message                         |
4708| -------- | --------------------------------- |
4709| 5400103  | IO error. Return by callback.     |
4710| 5400105  | Service died. Return by callback. |
4711
4712**Example**
4713
4714```ts
4715avRecorder.on('stateChange', async (state: media.AVRecorderState, reason: media.StateChangeReason) => {
4716  console.info('case state has changed, new state is :' + state + ',and new reason is : ' + reason);
4717});
4718```
4719
4720### off('stateChange')<sup>9+</sup>
4721
4722off(type: 'stateChange', callback?: OnAVRecorderStateChangeHandler): void
4723
4724Unsubscribes from AVRecorder state changes.
4725
4726**Atomic service API**: This API can be used in atomic services since API version 12.
4727
4728**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4729
4730**Parameters**
4731
4732| Name| Type  | Mandatory| Description                                                        |
4733| ------ | ------ | ---- | ------------------------------------------------------------ |
4734| type   | string | Yes  | Event type, which is **'stateChange'** in this case. This event can be triggered by both user operations and the system.|
4735| callback | [OnAVRecorderStateChangeHandler](#onavrecorderstatechangehandler12) | No  | Callback invoked when the event is triggered.<br>This parameter is supported since API version 12.|
4736
4737**Example**
4738
4739```ts
4740avRecorder.off('stateChange');
4741```
4742
4743### on('error')<sup>9+</sup>
4744
4745on(type: 'error', callback: ErrorCallback): void
4746
4747Subscribes 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.
4748
4749An application can subscribe to only one AVRecorder error event. When the application initiates multiple subscriptions to this event, the last subscription is applied.
4750
4751**Atomic service API**: This API can be used in atomic services since API version 12.
4752
4753**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4754
4755**Parameters**
4756
4757| Name  | Type         | Mandatory| Description                                                        |
4758| -------- | ------------- | ---- | ------------------------------------------------------------ |
4759| type     | string        | Yes  | Event type, which is **'error'** in this case.<br>This event is triggered when an error occurs during recording.|
4760| callback | [ErrorCallback](../apis-basic-services-kit/js-apis-base.md#errorcallback) | Yes  | Callback invoked when the event is triggered.                                      |
4761
4762**Error codes**
4763
4764For details about the error codes, see [Media Error Codes](errorcode-media.md).
4765
4766| ID| Error Message                                  |
4767| -------- | ------------------------------------------ |
4768| 201      | Permission denied.     |
4769| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. |
4770| 801      | Capability not supported. |
4771| 5400101  | No memory.             |
4772| 5400102  | Operation not allowed. |
4773| 5400103  | I/O error.             |
4774| 5400104  | Time out.              |
4775| 5400105  | Service died.          |
4776| 5400106  | Unsupported format.    |
4777| 5400107  | Audio interrupted.     |
4778
4779**Example**
4780
4781```ts
4782import { BusinessError } from '@kit.BasicServicesKit';
4783
4784avRecorder.on('error', (err: BusinessError) => {
4785  console.info('case avRecorder.on(error) called, errMessage is ' + err.message);
4786});
4787```
4788
4789### off('error')<sup>9+</sup>
4790
4791off(type: 'error', callback?: ErrorCallback): void
4792
4793Unsubscribes from AVRecorder errors. After the unsubscription, your application can no longer receive AVRecorder errors.
4794
4795**Atomic service API**: This API can be used in atomic services since API version 12.
4796
4797**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4798
4799**Parameters**
4800
4801| Name| Type  | Mandatory| Description                                                        |
4802| ------ | ------ | ---- | ------------------------------------------------------------ |
4803| type   | string | Yes  | Event type, which is **'error'** in this case.<br>This event is triggered when an error occurs during recording.|
4804| 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.                  |
4805
4806**Example**
4807
4808```ts
4809avRecorder.off('error');
4810```
4811
4812### on('audioCapturerChange')<sup>11+</sup>
4813
4814on(type: 'audioCapturerChange', callback: Callback<audio.AudioCapturerChangeInfo>): void
4815
4816Subscribes to audio capturer configuration changes. Any configuration change triggers the callback that returns the entire configuration information.
4817
4818When the application initiates multiple subscriptions to this event, the last subscription is applied.
4819
4820**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4821
4822**Parameters**
4823
4824| Name  | Type    | Mandatory| Description                                                        |
4825| -------- | -------- | ---- | ------------------------------------------------------------ |
4826| type     | string   | Yes  |Event type, which is **'audioCapturerChange'** in this case.|
4827| 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.|
4828
4829**Error codes**
4830
4831| ID| Error Message                                  |
4832| -------- | ------------------------------------------ |
4833| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed.      |
4834
4835**Example**
4836
4837```ts
4838import { audio } from '@kit.AudioKit'
4839
4840let capturerChangeInfo: audio.AudioCapturerChangeInfo;
4841
4842avRecorder.on('audioCapturerChange',  (audioCapturerChangeInfo: audio.AudioCapturerChangeInfo) => {
4843  console.info('audioCapturerChange called');
4844  capturerChangeInfo = audioCapturerChangeInfo;
4845});
4846```
4847
4848### off('audioCapturerChange')<sup>11+</sup>
4849
4850off(type: 'audioCapturerChange', callback?: Callback<audio.AudioCapturerChangeInfo>): void
4851
4852Subscribes to audio capturer configuration changes.
4853
4854**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4855
4856**Parameters**
4857
4858| Name| Type  | Mandatory| Description                                                        |
4859| ------ | ------ | ---- | ------------------------------------------------------------ |
4860| type   | string | Yes  | Event type, which is **'audioCapturerChange'** in this case.|
4861| 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.|
4862
4863**Example**
4864
4865```ts
4866avRecorder.off('audioCapturerChange');
4867```
4868
4869### on('photoAssetAvailable')<sup>12+</sup>
4870
4871on(type: 'photoAssetAvailable', callback: Callback\<photoAccessHelper.PhotoAsset>): void
4872
4873Subscribes 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.
4874
4875When the application initiates multiple subscriptions to this event, the last subscription is applied.
4876
4877**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4878
4879**Parameters**
4880
4881| Name  | Type    | Mandatory| Description                                                        |
4882| -------- | -------- | ---- | ------------------------------------------------------------ |
4883| type     | string   | Yes  |Event type, which is **'photoAssetAvailable'** in this case. The event is triggered when a photo asset is available.|
4884| 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.|
4885
4886**Error codes**
4887
4888| ID| Error Message                                  |
4889| -------- | ------------------------------------------ |
4890| 5400103  | IO error. Return by callback.             |
4891| 5400105  | Service died. Return by callback.          |
4892
4893**Example**
4894
4895<!--code_no_check-->
4896```ts
4897import { photoAccessHelper } from '@kit.MediaLibraryKit';
4898import { common } from '@kit.AbilityKit'
4899let photoAsset: photoAccessHelper.PhotoAsset;
4900private context: Context | undefined;
4901constructor(context: Context) {
4902  this.context = context; // this.getUIContext().getHostContext();
4903}
4904
4905// Example: Process the photoAsset callback and save the video.
4906async function saveVideo(asset: photoAccessHelper.PhotoAsset) {
4907  console.info("saveVideo called");
4908  try {
4909    let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(this.context);
4910    let assetChangeRequest: photoAccessHelper.MediaAssetChangeRequest = new photoAccessHelper.MediaAssetChangeRequest(asset);
4911    assetChangeRequest.saveCameraPhoto();
4912    await phAccessHelper.applyChanges(assetChangeRequest);
4913    console.info('apply saveVideo successfully');
4914  } catch (err) {
4915    console.error(`apply saveVideo failed with error: ${err.code}, ${err.message}`);
4916  }
4917}
4918// Subscribe to the photoAsset event.
4919avRecorder.on('photoAssetAvailable',  (asset: photoAccessHelper.PhotoAsset) => {
4920  console.info('photoAssetAvailable called');
4921  if (asset != undefined) {
4922    photoAsset = asset;
4923    // Process the photoAsset callback.
4924    // Example: this.saveVideo (asset);
4925  } else {
4926    console.error('photoAsset is undefined');
4927  }
4928});
4929```
4930
4931### off('photoAssetAvailable')<sup>12+</sup>
4932
4933off(type: 'photoAssetAvailable', callback?: Callback<photoAccessHelper.PhotoAsset>): void
4934
4935Unsubscribes from media asset callback events.
4936
4937**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4938
4939**Parameters**
4940
4941| Name| Type  | Mandatory| Description                                                        |
4942| ------ | ------ | ---- | ------------------------------------------------------------ |
4943| type   | string | Yes  | Event type, which is **'photoAssetAvailable'** in this case.|
4944| 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.|
4945
4946**Example**
4947
4948```ts
4949avRecorder.off('photoAssetAvailable');
4950```
4951
4952## AVRecorderState<sup>9+</sup>
4953
4954type AVRecorderState = 'idle' | 'prepared' | 'started' | 'paused' | 'stopped' | 'released' | 'error'
4955
4956Enumerates the AVRecorder states. You can obtain the state through the **state** property.
4957
4958**Atomic service API**: This API can be used in atomic services since API version 12.
4959
4960**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4961
4962| Type    | Description                                                        |
4963| -------- | ------------------------------------------------------------ |
4964| '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.  |
4965| 'prepared' | The AVRecorder enters this state when the parameters are set. In this state, you can call [AVRecorder.start()](#start9) to start recording.|
4966| '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.|
4967| '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.|
4968| '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.|
4969| '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.|
4970| '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.|
4971
4972## OnAVRecorderStateChangeHandler<sup>12+</sup>
4973
4974type OnAVRecorderStateChangeHandler = (state: AVRecorderState, reason: StateChangeReason) => void
4975
4976Describes the callback invoked for the AVRecorder state change event.
4977
4978**Atomic service API**: This API can be used in atomic services since API version 12.
4979
4980**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4981
4982| Name  | Type  | Mandatory| Description                                                        |
4983| ------ | ------ | ------ | ------------------------------------------------------------ |
4984| state  | [AVRecorderState](#avrecorderstate9) | Yes| AVRecorder state.    |
4985| reason | [StateChangeReason](#statechangereason9) | Yes| Reason for the state change.|
4986
4987## AVRecorderConfig<sup>9+</sup>
4988
4989Describes the audio and video recording parameters.
4990
4991The **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**.
4992
4993**System capability**: SystemCapability.Multimedia.Media.AVRecorder
4994
4995| Name           | Type                                    | Mandatory| Description                                                        |
4996| --------------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
4997| 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.|
4998| videoSourceType | [VideoSourceType](#videosourcetype9)     | No  | Type of the video source to record. This parameter is mandatory for video recording.                  |
4999| 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.|
5000| 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.|
5001|fileGenerationMode<sup>12+</sup> | [FileGenerationMode](#filegenerationmode12)  | No  |  Mode for creating the file, which is used together with [on('photoAssetAvailable')](#onphotoassetavailable12).|
5002| 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.    |
5003| 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.|
5004| metadata<sup>12+</sup>        | [AVMetadata](#avmetadata11)              | No  | Metadata. For details, see [AVMetadata](#avmetadata11).                 |
5005| 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.|
5006
5007## AVRecorderProfile<sup>9+</sup>
5008
5009Describes the audio and video recording profile.
5010
5011> **NOTE**
5012>
5013> The following table lists the audio parameters. For details about each parameter, see the field description below.
5014>
5015> | Encoding Format | Container Format | Sampling Rate | Bit Rate | Audio Channel Count |
5016> |----|----|----|----|----|
5017> |AUDIO_AAC|MP4,M4A|[8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000, 64000, 88200, 96000]|[32000-500000]|[1-8]|
5018> |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]|
5019> |AUDIO_G711MU|WAV|[8000]|[64000]|[1]|
5020> |AUDIO_AMR_NB<sup>18+</sup> |AMR|[8000]|[4750, 5150, 5900, 6700, 7400, 7950, 10200, 12200]|[1]|
5021> |AUDIO_AMR_WB<sup>18+</sup> |AMR|[16000]|[6600, 8850, 12650, 14250, 15850, 18250, 19850, 23050, 23850]|[1]|
5022
5023**System capability**: SystemCapability.Multimedia.Media.AVRecorder
5024
5025| Name            | Type                                        | Mandatory| Description                                                        |
5026| ---------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ |
5027| 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.|
5028| 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.      |
5029| 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.    |
5030| 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.|
5031| fileFormat       | [ContainerFormatType](#containerformattype8) | Yes  | Container format of a file. This parameter is mandatory. Currently, the MP4, M4A, MP3, WAV, AMR, and AAC container formats are supported. The default container format for AAC audio is ADTS frame format. The AUDIO_MP3 encoding format is not supported within the MP4 container format.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
5032| videoBitrate     | number                                       | No  | Video encoding bit rate. This parameter is mandatory for video recording. The value range is [10000 - 100000000]. |
5033| videoCodec       | [CodecMimeType](#codecmimetype8)             | No  | Video encoding format. This parameter is mandatory for video recording. Currently, VIDEO_AVC is supported.|
5034| videoFrameWidth  | number                                       | No  | Width of a video frame. This parameter is mandatory for video recording. The value range is [176 - 4096].        |
5035| videoFrameHeight | number                                       | No  | Height of a video frame. This parameter is mandatory for video recording. The value range is [144 - 4096].        |
5036| videoFrameRate   | number                                       | No  | Video frame rate. This parameter is mandatory for video recording. The recommended value range is [1 - 60].            |
5037| 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**.|
5038| 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.|
5039
5040## AudioSourceType<sup>9+</sup>
5041
5042Enumerates the audio source types for video recording.
5043
5044**System capability**: SystemCapability.Multimedia.Media.AVRecorder
5045
5046| Name                     | Value  | Description                  |
5047| ------------------------- | ---- | ---------------------- |
5048| AUDIO_SOURCE_TYPE_DEFAULT | 0    | Default audio input source.|
5049| 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.|
5050| AUDIO_SOURCE_TYPE_VOICE_RECOGNITION<sup>12+</sup> | 2    | Audio source in speech recognition scenarios.|
5051| AUDIO_SOURCE_TYPE_VOICE_COMMUNICATION<sup>12+</sup>     | 7    | Voice communication source.|
5052| AUDIO_SOURCE_TYPE_VOICE_MESSAGE<sup>12+</sup> | 10    | Voice message source.|
5053| AUDIO_SOURCE_TYPE_CAMCORDER<sup>12+</sup>     | 13    | Audio source in camera recording scenarios.|
5054
5055## VideoSourceType<sup>9+</sup>
5056
5057Enumerates the video source types for video recording.
5058
5059**System capability**: SystemCapability.Multimedia.Media.AVRecorder
5060
5061| Name                         | Value  | Description                           |
5062| ----------------------------- | ---- | ------------------------------- |
5063| VIDEO_SOURCE_TYPE_SURFACE_YUV | 0    | The input surface carries raw data.|
5064| VIDEO_SOURCE_TYPE_SURFACE_ES  | 1    | The input surface carries ES data. |
5065
5066## ContainerFormatType<sup>8+</sup>
5067
5068Enumerates the container format types (CFTs).
5069
5070**System capability**: SystemCapability.Multimedia.Media.Core
5071
5072| Name       | Value   | Description                 |
5073| ----------- | ----- | --------------------- |
5074| CFT_MPEG_4  | 'mp4' | Video container format MP4.|
5075| CFT_MPEG_4A | 'm4a' | Audio container format M4A.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
5076| CFT_MP3<sup>12+</sup>  | 'mp3' | Audio container format MP3.|
5077| CFT_WAV<sup>12+</sup>  | 'wav' | Audio container format WAV.|
5078| CFT_AMR<sup>18+</sup>  | 'amr' | Audio container format AMR.|
5079| CFT_AAC<sup>20+</sup>  | 'aac' | Audio container format AAC. The default format is ADTS frame header.|
5080
5081## Location
5082
5083Describes the geographical location of the recorded video.
5084
5085**System capability**: SystemCapability.Multimedia.Media.Core
5086
5087| Name     | Type  | Mandatory| Description            |
5088| --------- | ------ | ---- | ---------------- |
5089| latitude  | number | Yes  | Latitude of the geographical location. The value range is [-90, 90].|
5090| longitude | number | Yes  | Longitude of the geographical location. The value range is [-180, 180].|
5091
5092## EncoderInfo<sup>11+</sup>
5093
5094Describes the information about an encoder.
5095
5096**System capability**: SystemCapability.Multimedia.Media.AVRecorder
5097
5098| Name      | Type                            | Readable| Writable| Description                                                        |
5099| ---------- | -------------------------------- | ---- | ---- | ------------------------------------------------------------ |
5100| mimeType   | [CodecMimeType](#codecmimetype8) | Yes  | No  | MIME type of the encoder.                                          |
5101| type       | string                           | Yes  | No  | Encoder type. The value **audio** means an audio encoder, and **video** means a video encoder.        |
5102| bitRate    | [Range](#range11)                | Yes  | No  | Bit rate range of the encoder, with the minimum and maximum bit rates specified.                          |
5103| 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.         |
5104| width      | [Range](#range11)                | Yes  | No  | Video frame width range, with the minimum and maximum widths specified. This parameter is available only for video encoders.      |
5105| height     | [Range](#range11)                | Yes  | No  | Video frame height range, with the minimum and maximum heights specified. This parameter is available only for video encoders.      |
5106| 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.  |
5107| 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.|
5108
5109## Range<sup>11+</sup>
5110
5111Describes a range.
5112
5113**System capability**: SystemCapability.Multimedia.Media.AVRecorder
5114
5115| Name| Type  | Readable| Writable| Description        |
5116| ---- | ------ | ---- | ---- | ------------ |
5117| min  | number | Yes  | No  | Minimum value.|
5118| max  | number | Yes  | No  | Maximum value.|
5119
5120## FileGenerationMode<sup>12+</sup>
5121
5122Enumerates the modes for creating media files.
5123
5124**System capability**: SystemCapability.Multimedia.Media.AVRecorder
5125
5126| Name                         | Value  | Description                           |
5127| ----------------------------- | ---- | ------------------------------- |
5128| APP_CREATE  | 0    | The application creates a media file in the sandbox.|
5129| 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.|
5130
5131## AVTranscoder<sup>12+</sup>
5132
5133A transcoding management class that provides APIs to transcode videos. Before calling any API in AVTranscoder, you must use [createAVTranscoder()](#mediacreateavtranscoder12) to create an AVTranscoder instance.
5134
5135For details about the AVTranscoder demo, see [Using AVTranscoder for Transcoding](../../media/media/using-avtranscoder-for-transcodering.md).
5136
5137### Properties
5138
5139**System capability**: SystemCapability.Multimedia.Media.AVTranscoder
5140
5141| Name   | Type                                | Read-Only| Optional| Description              |
5142| ------- | ------------------------------------ | ---- | ---- | ------------------ |
5143| 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.|
5144| 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.|
5145
5146### prepare<sup>12+</sup>
5147
5148prepare(config: AVTranscoderConfig): Promise\<void>
5149
5150Sets video transcoding parameters. This API uses a promise to return the result.
5151
5152**System capability**: SystemCapability.Multimedia.Media.AVTranscoder
5153
5154**Parameters**
5155
5156| Name| Type                                  | Mandatory| Description                      |
5157| ------ | -------------------------------------- | ---- | -------------------------- |
5158| config | [AVTranscoderConfig](#avtranscoderconfig12) | Yes  | Video transcoding parameters to set.<!--RP1--><!--RP1End-->|
5159
5160**Return value**
5161
5162| Type          | Description                                      |
5163| -------------- | ------------------------------------------ |
5164| Promise\<void> | Promise that returns no value.|
5165
5166**Error codes**
5167
5168For details about the error codes, see [Media Error Codes](errorcode-media.md).
5169
5170| ID| Error Message                              |
5171| -------- | -------------------------------------- |
5172| 401  | The parameter check failed. Return by promise. |
5173| 5400102  | Operation not allowed. Return by promise. |
5174| 5400103  | IO error. Return by promise.              |
5175| 5400105  | Service died. Return by promise.       |
5176| 5400106  | Unsupported format. Returned by promise.  |
5177
5178**Example**
5179
5180```ts
5181import { BusinessError } from '@kit.BasicServicesKit';
5182
5183// Configure the parameters based on those supported by the hardware device.
5184let avTranscoderConfig: media.AVTranscoderConfig = {
5185  audioBitrate : 200000,
5186  audioCodec : media.CodecMimeType.AUDIO_AAC,
5187  fileFormat : media.ContainerFormatType.CFT_MPEG_4,
5188  videoBitrate : 3000000,
5189  videoCodec : media.CodecMimeType.VIDEO_AVC,
5190};
5191
5192avTranscoder.prepare(avTranscoderConfig).then(() => {
5193  console.info('prepare success');
5194}).catch((err: BusinessError) => {
5195  console.error('prepare failed and catch error is ' + err.message);
5196});
5197```
5198
5199### start<sup>12+</sup>
5200
5201start(): Promise\<void>
5202
5203Starts transcoding. This API uses a promise to return the result.
5204
5205This API can be called only after the [prepare()](#prepare12) API is called.
5206
5207**System capability**: SystemCapability.Multimedia.Media.AVTranscoder
5208
5209**Return value**
5210
5211| Type          | Description                                 |
5212| -------------- | ------------------------------------- |
5213| Promise\<void> | Promise that returns no value.|
5214
5215**Error codes**
5216
5217For details about the error codes, see [Media Error Codes](errorcode-media.md).
5218
5219| ID| Error Message                              |
5220| -------- | -------------------------------------- |
5221| 5400102  | Operation not allowed. Return by promise. |
5222| 5400103  | IO error. Return by promise.           |
5223| 5400105  | Service died. Return by promise.       |
5224
5225**Example**
5226
5227```ts
5228import { BusinessError } from '@kit.BasicServicesKit';
5229
5230avTranscoder.start().then(() => {
5231  console.info('start AVTranscoder success');
5232}).catch((err: BusinessError) => {
5233  console.error('start AVTranscoder failed and catch error is ' + err.message);
5234});
5235```
5236
5237### pause<sup>12+</sup>
5238
5239pause(): Promise\<void>
5240
5241Pauses transcoding. This API uses a promise to return the result.
5242
5243This API can be called only after the [start()](#start12) API is called. You can call [resume()](#resume12) to resume transcoding.
5244
5245**System capability**: SystemCapability.Multimedia.Media.AVTranscoder
5246
5247**Return value**
5248
5249| Type          | Description                                 |
5250| -------------- | ------------------------------------- |
5251| Promise\<void> | Promise that returns no value.|
5252
5253**Error codes**
5254
5255For details about the error codes, see [Media Error Codes](errorcode-media.md).
5256
5257| ID| Error Message                              |
5258| -------- | -------------------------------------- |
5259| 5400102  | Operation not allowed. Return by promise. |
5260| 5400103  | IO error. Return by promise.           |
5261| 5400105  | Service died. Return by promise.       |
5262
5263**Example**
5264
5265```ts
5266import { BusinessError } from '@kit.BasicServicesKit';
5267
5268avTranscoder.pause().then(() => {
5269  console.info('pause AVTranscoder success');
5270}).catch((err: BusinessError) => {
5271  console.error('pause AVTranscoder failed and catch error is ' + err.message);
5272});
5273```
5274
5275### resume<sup>12+</sup>
5276
5277resume(): Promise\<void>
5278
5279Resumes transcoding. This API uses a promise to return the result.
5280
5281This API can be called only after the [pause()](#pause12) API is called.
5282
5283**System capability**: SystemCapability.Multimedia.Media.AVTranscoder
5284
5285**Return value**
5286
5287| Type          | Description                                 |
5288| -------------- | ------------------------------------- |
5289| Promise\<void> | Promise that returns no value.|
5290
5291**Error codes**
5292
5293For details about the error codes, see [Media Error Codes](errorcode-media.md).
5294
5295| ID| Error Message                              |
5296| -------- | -------------------------------------- |
5297| 5400102  | Operation not allowed. Return by promise. |
5298| 5400103  | IO error. Return by promise.           |
5299| 5400105  | Service died. Return by promise.       |
5300
5301**Example**
5302
5303```ts
5304import { BusinessError } from '@kit.BasicServicesKit';
5305
5306avTranscoder.resume().then(() => {
5307  console.info('resume AVTranscoder success');
5308}).catch((err: BusinessError) => {
5309  console.error('resume AVTranscoder failed and catch error is ' + err.message);
5310});
5311```
5312
5313### cancel<sup>12+</sup>
5314
5315cancel(): Promise\<void>
5316
5317Cancels transcoding. This API uses a promise to return the result.
5318
5319This API can be called only after the [prepare()](#prepare12), [start()](#start12), [pause()](#pause12), or [resume()](#resume12) API is called.
5320
5321**System capability**: SystemCapability.Multimedia.Media.AVTranscoder
5322
5323**Return value**
5324
5325| Type          | Description                                 |
5326| -------------- | ------------------------------------- |
5327| Promise\<void> | Promise that returns no value.|
5328
5329**Error codes**
5330
5331For details about the error codes, see [Media Error Codes](errorcode-media.md).
5332
5333| ID| Error Message                              |
5334| -------- | -------------------------------------- |
5335| 5400102  | Operation not allowed. Return by promise. |
5336| 5400103  | IO error. Return by promise.           |
5337| 5400105  | Service died. Return by promise.       |
5338
5339**Example**
5340
5341```ts
5342import { BusinessError } from '@kit.BasicServicesKit';
5343
5344avTranscoder.cancel().then(() => {
5345  console.info('cancel AVTranscoder success');
5346}).catch((err: BusinessError) => {
5347  console.error('cancel AVTranscoder failed and catch error is ' + err.message);
5348});
5349```
5350
5351### release<sup>12+</sup>
5352
5353release(): Promise\<void>
5354
5355Releases the video transcoding resources. This API uses a promise to return the result.
5356
5357After the resources are released, you can no longer perform any operation on the AVTranscoder instance.
5358
5359**System capability**: SystemCapability.Multimedia.Media.AVTranscoder
5360
5361**Return value**
5362
5363| Type          | Description                                       |
5364| -------------- | ------------------------------------------- |
5365| Promise\<void> | Promise that returns no value.|
5366
5367**Error codes**
5368
5369For details about the error codes, see [Media Error Codes](errorcode-media.md).
5370
5371| ID| Error Message                         |
5372| -------- | --------------------------------- |
5373| 5400102  | Operation not allowed. Return by promise. |
5374| 5400105  | Service died. Return by promise. |
5375
5376**Example**
5377
5378```ts
5379import { BusinessError } from '@kit.BasicServicesKit';
5380
5381avTranscoder.release().then(() => {
5382  console.info('release AVTranscoder success');
5383}).catch((err: BusinessError) => {
5384  console.error('release AVTranscoder failed and catch error is ' + err.message);
5385});
5386```
5387
5388### on('progressUpdate')<sup>12+</sup>
5389
5390on(type: 'progressUpdate', callback: Callback\<number>): void
5391
5392Subscribes 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.
5393
5394**System capability**: SystemCapability.Multimedia.Media.AVTranscoder
5395
5396**Parameters**
5397
5398| Name  | Type    | Mandatory| Description                                                        |
5399| -------- | -------- | ---- | ------------------------------------------------------------ |
5400| type     | string   | Yes  | Event type, which is **'progressUpdate'** in this case. This event is triggered by the system during transcoding.|
5401| 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.|
5402
5403**Example**
5404
5405```ts
5406avTranscoder.on('progressUpdate', (progress: number) => {
5407  console.info('avTranscoder progressUpdate = ' + progress);
5408});
5409```
5410
5411### off('progressUpdate')<sup>12+</sup>
5412
5413off(type:'progressUpdate', callback?: Callback\<number>): void
5414
5415Unsubscribes from transcoding progress updates.
5416
5417**System capability**: SystemCapability.Multimedia.Media.AVTranscoder
5418
5419**Parameters**
5420
5421| Name| Type  | Mandatory| Description                                                        |
5422| ------ | ------ | ---- | ------------------------------------------------------------ |
5423| type   | string | Yes  | Event type, which is **'progressUpdate'** in this case.|
5424| 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.|
5425
5426**Example**
5427
5428```ts
5429avTranscoder.off('progressUpdate');
5430```
5431
5432### on('error')<sup>12+</sup>
5433
5434on(type: 'error', callback: ErrorCallback): void
5435
5436Subscribes to AVTranscoder errors. If this event is reported, call [release()](#release12) to exit the transcoding.
5437
5438An application can subscribe to only one AVTranscoder error event. When the application initiates multiple subscriptions to this event, the last subscription is applied.
5439
5440**System capability**: SystemCapability.Multimedia.Media.AVTranscoder
5441
5442**Parameters**
5443
5444| Name  | Type         | Mandatory| Description                                                        |
5445| -------- | ------------- | ---- | ------------------------------------------------------------ |
5446| type     | string        | Yes  | Event type, which is **'error'** in this case.<br>This event is triggered when an error occurs during recording.|
5447| callback | [ErrorCallback](../apis-basic-services-kit/js-apis-base.md#errorcallback) | Yes  | Callback invoked when the event is triggered.                                      |
5448
5449**Error codes**
5450
5451For details about the error codes, see [Media Error Codes](errorcode-media.md).
5452
5453| ID| Error Message                                  |
5454| -------- | ------------------------------------------ |
5455| 401      | The parameter check failed. |
5456| 801      | Capability not supported. |
5457| 5400101  | No memory.            |
5458| 5400102  | Operation not allowed. |
5459| 5400103  | I/O error.              |
5460| 5400104  | Time out.            |
5461| 5400105  | Service died.           |
5462| 5400106  | Unsupported format.      |
5463
5464**Example**
5465
5466```ts
5467import { BusinessError } from '@kit.BasicServicesKit';
5468
5469avTranscoder.on('error', (err: BusinessError) => {
5470  console.info('case avTranscoder.on(error) called, errMessage is ' + err.message);
5471});
5472```
5473
5474### off('error')<sup>12+</sup>
5475
5476off(type:'error', callback?: ErrorCallback): void
5477
5478Unsubscribes from AVTranscoder errors. After the unsubscription, your application can no longer receive AVTranscoder errors.
5479
5480**System capability**: SystemCapability.Multimedia.Media.AVTranscoder
5481
5482**Parameters**
5483
5484| Name| Type  | Mandatory| Description                                                        |
5485| ------ | ------ | ---- | ------------------------------------------------------------ |
5486| type   | string | Yes  | Event type, which is **'error'** in this case.<br>This event is triggered when an error occurs during transcoding.|
5487| callback | [ErrorCallback](../apis-basic-services-kit/js-apis-base.md#errorcallback) | No  | Callback that has been registered to listen for AVTranscoder errors.|
5488
5489**Example**
5490
5491```ts
5492avTranscoder.off('error');
5493```
5494
5495### on('complete')<sup>12+</sup>
5496
5497on(type: 'complete', callback: Callback\<void>): void
5498
5499Subscribes 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.
5500
5501When this event is reported, the current transcoding operation is complete. You need to call [release()](#release12) to exit the transcoding.
5502
5503**System capability**: SystemCapability.Multimedia.Media.AVTranscoder
5504
5505**Parameters**
5506
5507| Name  | Type    | Mandatory| Description                                                        |
5508| -------- | -------- | ---- | ------------------------------------------------------------ |
5509| type     | string   | Yes  | Event type, which is **'complete'** in this case. This event is triggered by the system during transcoding.|
5510| callback | [Callback\<void>](../apis-basic-services-kit/js-apis-base.md#callback) | Yes  | Callback that has been registered to listen for transcoding completion events.|
5511
5512**Example**
5513
5514```ts
5515avTranscoder.on('complete', async () => {
5516  console.info('avTranscoder complete');
5517  // Listen for transcoding completion events.
5518  // Wait until avTranscoder.release() is complete and then forward, upload, or save the transcoded file.
5519  await avTranscoder.release();
5520  avTranscoder = undefined;
5521});
5522```
5523
5524### off('complete')<sup>12+</sup>
5525
5526off(type:'complete', callback?: Callback\<void>): void
5527
5528Unsubscribes from the event indicating that transcoding is complete.
5529
5530**System capability**: SystemCapability.Multimedia.Media.AVTranscoder
5531
5532**Parameters**
5533
5534| Name| Type  | Mandatory| Description                                                        |
5535| ------ | ------ | ---- | ------------------------------------------------------------ |
5536| type   | string | Yes  | Event type, which is **'complete'** in this case.|
5537| callback | [Callback\<void>](../apis-basic-services-kit/js-apis-base.md#callback) | No  | Callback that has been registered to listen for transcoding completion events.|
5538
5539**Example**
5540
5541```ts
5542avTranscoder.off('complete');
5543```
5544
5545## AVTranscoderConfig<sup>12+</sup>
5546
5547Describes the video transcoding parameters.
5548
5549**System capability**: SystemCapability.Multimedia.Media.AVTranscoder
5550
5551| Name           | Type                                   | Read-Only| Optional| Description                                                        |
5552| --------------- | ---------------------------------------- |---- | ---- | ------------------------------------------------------------ |
5553| 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.|
5554| audioCodec | [CodecMimeType](#codecmimetype8)     | No| Yes | Encoding format of the output audio. Currently, only AAC is supported. The default value is **AAC**.                  |
5555| fileFormat         | [ContainerFormatType](#containerformattype8) | No| No  | Container format of the output video file. Currently, only MP4 is supported.|
5556| 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.|
5557| 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**.|
5558| 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.|
5559| 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.|
5560
5561
5562
5563## AVMetadataExtractor<sup>11+</sup>
5564
5565Provides APIs to obtain metadata from media resources. Before calling any API of AVMetadataExtractor, you must use [createAVMetadataExtractor()](#mediacreateavmetadataextractor11) to create an AVMetadataExtractor instance.
5566
5567For details about the demo for obtaining audio or video metadata, see [Obtaining Audio/Video Metadata](../../media/media/avmetadataextractor.md).
5568
5569### Properties
5570
5571**System capability**: SystemCapability.Multimedia.Media.AVMetadataExtractor
5572
5573| Name                                               | Type                                                        | Readable| Writable| Description                                                        |
5574| --------------------------------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ |
5575| 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.|
5576| 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.|
5577
5578### fetchMetadata<sup>11+</sup>
5579
5580fetchMetadata(callback: AsyncCallback\<AVMetadata>): void
5581
5582Obtains media metadata. This API uses an asynchronous callback to return the result.
5583
5584**System capability**: SystemCapability.Multimedia.Media.AVMetadataExtractor
5585
5586**Parameters**
5587
5588| Name  | Type                                        | Mandatory| Description                               |
5589| -------- | -------------------------------------------- | ---- | ----------------------------------- |
5590| callback | AsyncCallback\<[AVMetadata](#avmetadata11)>       | Yes  | Callback used to return the result, which is an AVMetadata instance.|
5591
5592**Error codes**
5593
5594For details about the error codes, see [Media Error Codes](errorcode-media.md).
5595
5596| ID| Error Message                                  |
5597| -------- | ------------------------------------------ |
5598| 5400102  | Operation not allowed. Returned by callback. |
5599| 5400106  | Unsupported format. Returned by callback.  |
5600
5601**Example**
5602
5603```ts
5604import { BusinessError } from '@kit.BasicServicesKit';
5605
5606avMetadataExtractor.fetchMetadata((error: BusinessError, metadata: media.AVMetadata) => {
5607  if (error) {
5608    console.error(`Failed to fetch Metadata, err = ${JSON.stringify(error)}`);
5609    return;
5610  }
5611  console.info(`Succeeded in fetching Metadata, genre: ${metadata.genre}`);
5612});
5613```
5614
5615### fetchMetadata<sup>11+</sup>
5616
5617fetchMetadata(): Promise\<AVMetadata>
5618
5619Obtains media metadata. This API uses a promise to return the result.
5620
5621**System capability**: SystemCapability.Multimedia.Media.AVMetadataExtractor
5622
5623**Return value**
5624
5625| Type          | Description                                    |
5626| -------------- | ---------------------------------------- |
5627| Promise\<[AVMetadata](#avmetadata11)>  | Promise used to return the result, which is an AVMetadata instance.|
5628
5629**Error codes**
5630
5631For details about the error codes, see [Media Error Codes](errorcode-media.md).
5632
5633| ID| Error Message                                 |
5634| -------- | ----------------------------------------- |
5635| 5400102  | Operation not allowed. Returned by promise. |
5636| 5400106  | Unsupported format. Returned by promise.  |
5637
5638**Example**
5639
5640```ts
5641import { BusinessError } from '@kit.BasicServicesKit';
5642
5643avMetadataExtractor.fetchMetadata().then((metadata: media.AVMetadata) => {
5644  console.info(`Succeeded in fetching Metadata, genre: ${metadata.genre}`);
5645}).catch((error: BusinessError) => {
5646  console.error(`Failed to fetch Metadata, error message:${error.message}`);
5647});
5648```
5649
5650### fetchAlbumCover<sup>11+</sup>
5651
5652fetchAlbumCover(callback: AsyncCallback\<image.PixelMap>): void
5653
5654Obtains the cover of the audio album. This API uses an asynchronous callback to return the result.
5655
5656**System capability**: SystemCapability.Multimedia.Media.AVMetadataExtractor
5657
5658**Parameters**
5659
5660| Name  | Type                                        | Mandatory| Description                               |
5661| -------- | -------------------------------------------- | ---- | ----------------------------------- |
5662| callback | AsyncCallback\<[image.PixelMap](../apis-image-kit/arkts-apis-image-PixelMap.md)>    | Yes  | Callback used to return the album cover.|
5663
5664**Error codes**
5665
5666For details about the error codes, see [Media Error Codes](errorcode-media.md).
5667
5668| ID| Error Message                                  |
5669| -------- | ------------------------------------------ |
5670| 5400102  | Operation not allowed. Return by callback. |
5671| 5400106  | Unsupported format. Returned by callback.  |
5672
5673**Example**
5674
5675```ts
5676import { BusinessError } from '@kit.BasicServicesKit';
5677import { image } from '@kit.ImageKit';
5678
5679let pixel_map : image.PixelMap | undefined = undefined;
5680
5681avMetadataExtractor.fetchAlbumCover((error: BusinessError, pixelMap: image.PixelMap) => {
5682  if (error) {
5683    console.error(`Failed to fetch AlbumCover, error = ${JSON.stringify(error)}`);
5684    return;
5685  }
5686  pixel_map = pixelMap;
5687});
5688```
5689
5690### fetchAlbumCover<sup>11+</sup>
5691
5692fetchAlbumCover(): Promise\<image.PixelMap>
5693
5694Obtains the cover of the audio album. This API uses a promise to return the result.
5695
5696**System capability**: SystemCapability.Multimedia.Media.AVMetadataExtractor
5697
5698**Return value**
5699
5700| Type          | Description                                    |
5701| -------------- | ---------------------------------------- |
5702| Promise\<[image.PixelMap](../apis-image-kit/arkts-apis-image-PixelMap.md)> |  Promise used to return the album cover.|
5703
5704**Error codes**
5705
5706For details about the error codes, see [Media Error Codes](errorcode-media.md).
5707
5708| ID| Error Message                                 |
5709| -------- | ----------------------------------------- |
5710| 5400102  | Operation not allowed. Returned by promise. |
5711| 5400106  | Unsupported format. Returned by promise.  |
5712
5713**Example**
5714
5715```ts
5716import { BusinessError } from '@kit.BasicServicesKit';
5717import { image } from '@kit.ImageKit';
5718
5719let pixel_map : image.PixelMap | undefined = undefined;
5720
5721avMetadataExtractor.fetchAlbumCover().then((pixelMap: image.PixelMap) => {
5722  pixel_map = pixelMap;
5723}).catch((error: BusinessError) => {
5724  console.error(`Failed to fetch AlbumCover, error message:${error.message}`);
5725});
5726```
5727
5728### release<sup>11+</sup>
5729
5730release(callback: AsyncCallback\<void>): void
5731
5732Releases this AVMetadataExtractor instance. This API uses an asynchronous callback to return the result.
5733
5734**System capability**: SystemCapability.Multimedia.Media.AVMetadataExtractor
5735
5736**Parameters**
5737
5738| Name  | Type                                        | Mandatory| Description                               |
5739| -------- | -------------------------------------------- | ---- | ----------------------------------- |
5740| callback | AsyncCallback\<void>                   | Yes  |Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
5741
5742**Error codes**
5743
5744For details about the error codes, see [Media Error Codes](errorcode-media.md).
5745
5746| ID| Error Message                                  |
5747| -------- | ------------------------------------------ |
5748| 5400102  | Operation not allowed. Returned by callback. |
5749
5750**Example**
5751
5752```ts
5753import { BusinessError } from '@kit.BasicServicesKit';
5754
5755avMetadataExtractor.release((error: BusinessError) => {
5756  if (error) {
5757    console.error(`Failed to release, err = ${JSON.stringify(error)}`);
5758    return;
5759  }
5760  console.info(`Succeeded in releasing.`);
5761});
5762```
5763
5764### release<sup>11+</sup>
5765
5766release(): Promise\<void>
5767
5768Releases this AVMetadataExtractor instance. This API uses a promise to return the result.
5769
5770**System capability**: SystemCapability.Multimedia.Media.AVMetadataExtractor
5771
5772**Return value**
5773
5774| Type          | Description                                    |
5775| -------------- | ---------------------------------------- |
5776| Promise\<void> | Promise that returns no value.|
5777
5778**Error codes**
5779
5780For details about the error codes, see [Media Error Codes](errorcode-media.md).
5781
5782| ID| Error Message                                 |
5783| -------- | ----------------------------------------- |
5784| 5400102  | Operation not allowed. Returned by promise. |
5785
5786**Example**
5787
5788```ts
5789import { BusinessError } from '@kit.BasicServicesKit';
5790
5791avMetadataExtractor.release().then(() => {
5792  console.info(`Succeeded in releasing.`);
5793}).catch((error: BusinessError) => {
5794  console.error(`Failed to release, error message:${error.message}`);
5795});
5796```
5797
5798## AVMetadata<sup>11+</sup>
5799
5800Defines 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).
5801
5802**System capability**: SystemCapability.Multimedia.Media.AVMetadataExtractor
5803
5804| Name  | Type  | Mandatory| Description                                                        |
5805| ------ | ------ | ---- | ------------------------------------------------------------ |
5806| album     | string | No  | Title of the album. This parameter is read-only in the current version.    |
5807| albumArtist | string | No  | Artist of the album. This parameter is read-only in the current version.|
5808| artist | string | No  | Artist of the media asset. This parameter is read-only in the current version.|
5809| author | string | No  | Author of the media asset. This parameter is read-only in the current version.|
5810| dateTime | string | No  | Time when the media asset is created. This parameter is read-only in the current version.|
5811| 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.|
5812| composer | string | No  | Composer of the media asset. This parameter is read-only in the current version.|
5813| duration | string | No  | Duration of the media asset. This parameter is read-only in the current version.|
5814| genre | string | No  | Type or genre of the media asset.|
5815| hasAudio | string | No  | Whether the media asset contains audio. This parameter is read-only in the current version.|
5816| hasVideo | string | No  | Whether the media asset contains a video. This parameter is read-only in the current version.|
5817| mimeType | string | No  | MIME type of the media asset. This parameter is read-only in the current version.|
5818| trackCount | string | No  | Number of tracks of the media asset. This parameter is read-only in the current version.|
5819| sampleRate | string | No  | Audio sampling rate, in Hz. This parameter is read-only in the current version.|
5820| 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.|
5821| videoHeight | string | No  | Video height, in px. This parameter is read-only in the current version.|
5822| videoWidth | string | No  | Video width, in px. This parameter is read-only in the current version.|
5823| videoOrientation | string | No  | Video rotation direction, in degrees.|
5824| hdrType<sup>12+</sup> | [HdrType](#hdrtype12) | No  | HDR type of the media asset. This parameter is read-only in the current version.|
5825| location<sup>12+</sup> | [Location](#location) | No| Geographical location of the media asset.|
5826| customInfo<sup>12+</sup> | Record<string, string> | No| Custom key-value mappings obtained from **moov.meta.list**.|
5827
5828## HdrType<sup>12+</sup>
5829
5830Enumerates the HDR types.
5831
5832**System capability**: SystemCapability.Multimedia.Media.Core
5833
5834| Name                     | Value  | Description                  |
5835| ------------------------- | ---- | ---------------------- |
5836| AV_HDR_TYPE_NONE          | 0    | No HDR.|
5837| AV_HDR_TYPE_VIVID         | 1    | HDR VIVID.|
5838
5839## media.createAudioPlayer<sup>(deprecated)</sup>
5840
5841createAudioPlayer(): AudioPlayer
5842
5843Creates an AudioPlayer instance in synchronous mode.
5844
5845> **NOTE**
5846>
5847> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [createAVPlayer](#mediacreateavplayer9) instead.
5848
5849**System capability**: SystemCapability.Multimedia.Media.AudioPlayer
5850
5851**Return value**
5852
5853| Type                       | Description                                                        |
5854| --------------------------- | ------------------------------------------------------------ |
5855| [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.|
5856
5857**Example**
5858
5859```ts
5860let audioPlayer: media.AudioPlayer = media.createAudioPlayer();
5861```
5862
5863## media.createVideoPlayer<sup>(deprecated)</sup>
5864
5865createVideoPlayer(callback: AsyncCallback\<VideoPlayer>): void
5866
5867Creates a VideoPlayer instance. This API uses an asynchronous callback to return the result.
5868
5869> **NOTE**
5870>
5871> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [createAVPlayer](#mediacreateavplayer9) instead.
5872
5873**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
5874
5875**Parameters**
5876
5877| Name  | Type                                      | Mandatory| Description                                                        |
5878| -------- | ------------------------------------------ | ---- | ------------------------------------------------------------ |
5879| 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.|
5880
5881**Example**
5882
5883```ts
5884import { BusinessError } from '@kit.BasicServicesKit';
5885
5886let videoPlayer: media.VideoPlayer;
5887media.createVideoPlayer((error: BusinessError, video: media.VideoPlayer) => {
5888  if (video != null) {
5889    videoPlayer = video;
5890    console.info('Succeeded in creating VideoPlayer');
5891  } else {
5892    console.error(`Failed to create VideoPlayer, error:${error}`);
5893  }
5894});
5895```
5896
5897## media.createVideoPlayer<sup>(deprecated)</sup>
5898
5899createVideoPlayer(): Promise\<VideoPlayer>
5900
5901Creates a VideoPlayer instance. This API uses a promise to return the result.
5902
5903> **NOTE**
5904>
5905> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [createAVPlayer](#mediacreateavplayer9-1) instead.
5906
5907**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
5908
5909**Return value**
5910
5911| Type                                | Description                                                        |
5912| ------------------------------------ | ------------------------------------------------------------ |
5913| 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.|
5914
5915**Example**
5916
5917```ts
5918import { BusinessError } from '@kit.BasicServicesKit';
5919
5920let videoPlayer: media.VideoPlayer;
5921media.createVideoPlayer().then((video: media.VideoPlayer) => {
5922  if (video != null) {
5923    videoPlayer = video;
5924    console.info('Succeeded in creating VideoPlayer');
5925  } else {
5926    console.error('Failed to create VideoPlayer');
5927  }
5928}).catch((error: BusinessError) => {
5929  console.error(`Failed to create VideoPlayer, error:${error}`);
5930});
5931```
5932
5933## media.createAudioRecorder<sup>(deprecated)</sup>
5934
5935createAudioRecorder(): AudioRecorder
5936
5937Creates an AudioRecorder instance to control audio recording.
5938
5939Only one AudioRecorder instance can be created per device.
5940
5941> **NOTE**
5942>
5943> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [createAVRecorder](#mediacreateavrecorder9) instead.
5944
5945**System capability**: SystemCapability.Multimedia.Media.AudioRecorder
5946
5947**Return value**
5948
5949| Type                           | Description                                                        |
5950| ------------------------------- | ------------------------------------------------------------ |
5951| [AudioRecorder](#audiorecorderdeprecated) | If the operation is successful, an AudioRecorder instance is returned; otherwise, **null** is returned. The instance can be used to record audio.|
5952
5953**Example**
5954
5955```ts
5956let audioRecorder: media.AudioRecorder = media.createAudioRecorder();
5957```
5958
5959## MediaErrorCode<sup>(deprecated)</sup>
5960
5961Enumerates the media error codes.
5962
5963> **NOTE**
5964>
5965> This enum is supported since API version 8 and deprecated since API version 11. You are advised to use [Media Error Codes](#averrorcode9) instead.
5966
5967**System capability**: SystemCapability.Multimedia.Media.Core
5968
5969| Name                      | Value  | Description                                  |
5970| -------------------------- | ---- | -------------------------------------- |
5971| MSERR_OK                   | 0    | The operation is successful.                        |
5972| MSERR_NO_MEMORY            | 1    | Failed to allocate memory. The system may have no available memory.|
5973| MSERR_OPERATION_NOT_PERMIT | 2    | No permission to perform the operation.                |
5974| MSERR_INVALID_VAL          | 3    | Invalid input parameter.                    |
5975| MSERR_IO                   | 4    | An I/O error occurs.                      |
5976| MSERR_TIMEOUT              | 5    | The operation times out.                        |
5977| MSERR_UNKNOWN              | 6    | An unknown error occurs.                        |
5978| MSERR_SERVICE_DIED         | 7    | Invalid server.                      |
5979| MSERR_INVALID_STATE        | 8    | The operation is not allowed in the current state.  |
5980| MSERR_UNSUPPORTED          | 9    | The operation is not supported in the current version.      |
5981
5982## AudioPlayer<sup>(deprecated)</sup>
5983
5984> **NOTE**
5985>
5986> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayer](#avplayer9) instead.
5987
5988Provides APIs to manage and play audio. Before calling any API in AudioPlayer, you must use [createAudioPlayer()](#mediacreateaudioplayerdeprecated) to create an AudioPlayer instance.
5989
5990### Properties<sup>(deprecated)</sup>
5991
5992**System capability**: SystemCapability.Multimedia.Media.AudioPlayer
5993
5994| Name                           | Type                                                  | Read-Only| Optional| Description                                                        |
5995| ------------------------------- | ------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ |
5996| 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|
5997| fdSrc<sup>9+</sup>              | [AVFileDescriptor](#avfiledescriptor9)                 | No  | No  | Description of the audio file. This property 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>|
5998| loop                            | boolean                                                | No  | No | Whether to loop audio playback. The value **true** means to loop audio playback, and **false** means the opposite.                |
5999| audioInterruptMode<sup>9+</sup> | [audio.InterruptMode](../apis-audio-kit/js-apis-audio.md#interruptmode9) | Yes  | Yes  | Audio interruption mode.                                              |
6000| currentTime                     | number                                                 | Yes  | No  | Current audio playback position, in ms.                      |
6001| duration                        | number                                                 | Yes  | No  | Audio duration, in ms.                                |
6002| 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()**.|
6003
6004### play<sup>(deprecated)</sup>
6005
6006play(): void
6007
6008Starts to play an audio asset. This API can be called only after the **'dataLoad'** event is triggered.
6009
6010> **NOTE**
6011>
6012> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayer.play](#play9) instead.
6013
6014**System capability**: SystemCapability.Multimedia.Media.AudioPlayer
6015
6016**Example**
6017
6018```ts
6019audioPlayer.on('play', () => {    // Set the 'play' event callback.
6020  console.info('audio play called');
6021});
6022audioPlayer.play();
6023```
6024
6025### pause<sup>(deprecated)</sup>
6026
6027pause(): void
6028
6029Pauses audio playback.
6030
6031> **NOTE**
6032>
6033> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayer.pause](#pause9) instead.
6034
6035**System capability**: SystemCapability.Multimedia.Media.AudioPlayer
6036
6037**Example**
6038
6039```ts
6040audioPlayer.on('pause', () => {    // Set the 'pause' event callback.
6041  console.info('audio pause called');
6042});
6043audioPlayer.pause();
6044```
6045
6046### stop<sup>(deprecated)</sup>
6047
6048stop(): void
6049
6050Stops audio playback.
6051
6052> **NOTE**
6053>
6054> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayer.stop](#stop9) instead.
6055
6056**System capability**: SystemCapability.Multimedia.Media.AudioPlayer
6057
6058**Example**
6059
6060```ts
6061audioPlayer.on('stop', () => {    // Set the 'stop' event callback.
6062  console.info('audio stop called');
6063});
6064audioPlayer.stop();
6065```
6066
6067### reset<sup>(deprecated)</sup>
6068
6069reset(): void
6070
6071Resets the audio asset to be played.
6072
6073> **NOTE**
6074>
6075> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [AVPlayer.reset](#reset9) instead.
6076
6077**System capability**: SystemCapability.Multimedia.Media.AudioPlayer
6078
6079**Example**
6080
6081```ts
6082audioPlayer.on('reset', () => {    // Set the 'reset' event callback.
6083  console.info('audio reset called');
6084});
6085audioPlayer.reset();
6086```
6087
6088### seek<sup>(deprecated)</sup>
6089
6090seek(timeMs: number): void
6091
6092Seeks to the specified playback position.
6093
6094> **NOTE**
6095>
6096> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayer.seek](#seek9) instead.
6097
6098**System capability**: SystemCapability.Multimedia.Media.AudioPlayer
6099
6100**Parameters**
6101
6102| Name| Type  | Mandatory| Description                                                       |
6103| ------ | ------ | ---- | ----------------------------------------------------------- |
6104| timeMs | number | Yes  | Position to seek to, in ms. The value range is [0, duration].|
6105
6106**Example**
6107
6108```ts
6109audioPlayer.on('timeUpdate', (seekDoneTime: number) => {    // Set the 'timeUpdate' event callback.
6110  if (seekDoneTime == null) {
6111    console.error('Failed to seek');
6112    return;
6113  }
6114  console.info('Succeeded in seek. seekDoneTime: ' + seekDoneTime);
6115});
6116audioPlayer.seek(30000); // Seek to 30000 ms.
6117```
6118
6119### setVolume<sup>(deprecated)</sup>
6120
6121setVolume(vol: number): void
6122
6123Sets the volume.
6124
6125> **NOTE**
6126>
6127> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayer.setVolume](#setvolume9) instead.
6128
6129**System capability**: SystemCapability.Multimedia.Media.AudioPlayer
6130
6131**Parameters**
6132
6133| Name| Type  | Mandatory| Description                                                        |
6134| ------ | ------ | ---- | ------------------------------------------------------------ |
6135| vol    | number | Yes  | Relative volume. The value ranges from 0.00 to 1.00. The value **1.00** indicates the maximum volume (100%).|
6136
6137**Example**
6138
6139```ts
6140audioPlayer.on('volumeChange', () => {    // Set the 'volumeChange' event callback.
6141  console.info('audio volumeChange called');
6142});
6143audioPlayer.setVolume(1);    // Set the volume to 100%.
6144```
6145
6146### release<sup>(deprecated)</sup>
6147
6148release(): void
6149
6150Releases the audio playback resources.
6151
6152> **NOTE**
6153>
6154> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayer.release](#release9) instead.
6155
6156**System capability**: SystemCapability.Multimedia.Media.AudioPlayer
6157
6158**Example**
6159
6160```ts
6161audioPlayer.release();
6162audioPlayer = undefined;
6163```
6164
6165### getTrackDescription<sup>(deprecated)</sup>
6166
6167getTrackDescription(callback: AsyncCallback\<Array\<MediaDescription>>): void
6168
6169Obtains 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.
6170
6171> **NOTE**
6172>
6173> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.getTrackDescription](#gettrackdescription9) instead.
6174
6175**System capability**: SystemCapability.Multimedia.Media.AudioPlayer
6176
6177**Parameters**
6178
6179| Name  | Type                                                        | Mandatory| Description                                      |
6180| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------ |
6181| 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.|
6182
6183**Example**
6184
6185```ts
6186import { BusinessError } from '@kit.BasicServicesKit';
6187
6188audioPlayer.getTrackDescription((error: BusinessError, arrList: Array<media.MediaDescription>) => {
6189  if (arrList != null) {
6190    console.info('Succeeded in getting TrackDescription');
6191  } else {
6192    console.error(`Failed to get TrackDescription, error:${error}`);
6193  }
6194});
6195```
6196
6197### getTrackDescription<sup>(deprecated)</sup>
6198
6199getTrackDescription(): Promise\<Array\<MediaDescription>>
6200
6201Obtains the audio track information. It can be called only after the **'dataLoad'** event is triggered. This API uses a promise to return the result.
6202
6203> **NOTE**
6204>
6205> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.getTrackDescription](#gettrackdescription9-1) instead.
6206
6207**System capability**: SystemCapability.Multimedia.Media.AudioPlayer
6208
6209**Return value**
6210
6211| Type                                                  | Description                                           |
6212| ------------------------------------------------------ | ----------------------------------------------- |
6213| Promise<Array<[MediaDescription](#mediadescription8)>> | Promise used to return a **MediaDescription** array, which records the audio track information.|
6214
6215**Example**
6216
6217```ts
6218import { BusinessError } from '@kit.BasicServicesKit';
6219
6220audioPlayer.getTrackDescription().then((arrList: Array<media.MediaDescription>) => {
6221  console.info('Succeeded in getting TrackDescription');
6222}).catch((error: BusinessError) => {
6223  console.error(`Failed to get TrackDescription, error:${error}`);
6224});
6225```
6226
6227### on('bufferingUpdate')<sup>(deprecated)</sup>
6228
6229on(type: 'bufferingUpdate', callback: (infoType: BufferingInfoType, value: number) => void): void
6230
6231Subscribes to the audio buffering update event. This API works only under online playback.
6232
6233> **NOTE**
6234>
6235> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.on('bufferingUpdate')](#onbufferingupdate9) instead.
6236
6237**System capability**: SystemCapability.Multimedia.Media.AudioPlayer
6238
6239**Parameters**
6240
6241| Name  | Type    | Mandatory| Description                                                        |
6242| -------- | -------- | ---- | ------------------------------------------------------------ |
6243| type     | string   | Yes  | Event type, which is **'bufferingUpdate'** in this case.       |
6244| callback | function | Yes  | Callback invoked when the event is triggered.<br>The value of [BufferingInfoType](#bufferinginfotype8) is fixed at **0**.|
6245
6246**Example**
6247
6248```ts
6249audioPlayer.on('bufferingUpdate', (infoType: media.BufferingInfoType, value: number) => {
6250  console.info('audio bufferingInfo type: ' + infoType);
6251  console.info('audio bufferingInfo value: ' + value);
6252});
6253```
6254
6255### on('play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange')<sup>(deprecated)</sup>
6256
6257on(type: 'play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange', callback: () => void): void
6258
6259Subscribes to the audio playback events.
6260
6261> **NOTE**
6262>
6263> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayer.on('stateChange')](#onstatechange9) instead.
6264
6265**System capability**: SystemCapability.Multimedia.Media.AudioPlayer
6266
6267**Parameters**
6268
6269| Name  | Type      | Mandatory| Description                                                        |
6270| -------- | ---------- | ---- | ------------------------------------------------------------ |
6271| 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** property 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.|
6272| callback | () => void | Yes  | Callback invoked when the event is triggered.                                          |
6273
6274**Example**
6275
6276```ts
6277import { fileIo as fs } from '@kit.CoreFileKit';
6278import { BusinessError } from '@kit.BasicServicesKit';
6279
6280let audioPlayer: media.AudioPlayer = media.createAudioPlayer();  // Create an AudioPlayer instance.
6281audioPlayer.on('dataLoad', () => {            // Set the 'dataLoad' event callback, which is triggered when the src property is set successfully.
6282  console.info('audio set source called');
6283  audioPlayer.play();                       // Start the playback and trigger the 'play' event callback.
6284});
6285audioPlayer.on('play', () => {                // Set the 'play' event callback.
6286  console.info('audio play called');
6287  audioPlayer.seek(30000);                  // Call the seek() API and trigger the 'timeUpdate' event callback.
6288});
6289audioPlayer.on('pause', () => {               // Set the 'pause' event callback.
6290  console.info('audio pause called');
6291  audioPlayer.stop();                       // Stop the playback and trigger the 'stop' event callback.
6292});
6293audioPlayer.on('reset', () => {               // Set the 'reset' event callback.
6294  console.info('audio reset called');
6295  audioPlayer.release();                    // Release the AudioPlayer instance.
6296  audioPlayer = undefined;
6297});
6298audioPlayer.on('timeUpdate', (seekDoneTime: number) => {  // Set the 'timeUpdate' event callback.
6299  if (seekDoneTime == null) {
6300    console.error('Failed to seek');
6301    return;
6302  }
6303  console.info('Succeeded in seek, and seek time is ' + seekDoneTime);
6304  audioPlayer.setVolume(0.5);                // Set the volume to 50% and trigger the 'volumeChange' event callback.
6305});
6306audioPlayer.on('volumeChange', () => {         // Set the 'volumeChange' event callback.
6307  console.info('audio volumeChange called');
6308  audioPlayer.pause();                       // Pause the playback and trigger the 'pause' event callback.
6309});
6310audioPlayer.on('finish', () => {               // Set the 'finish' event callback.
6311  console.info('audio play finish');
6312  audioPlayer.stop();                        // Stop the playback and trigger the 'stop' event callback.
6313});
6314audioPlayer.on('error', (error: BusinessError) => {  // Set the 'error' event callback.
6315  console.error(`audio error called, error: ${error}`);
6316});
6317
6318// Set the FD (local playback) of the audio file selected by the user.
6319let fdPath = 'fd://';
6320// 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.
6321let path = '/data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3';
6322fs.open(path).then((file) => {
6323  fdPath = fdPath + '' + file.fd;
6324  console.info('Succeeded in opening fd, fd is' + fdPath);
6325  audioPlayer.src = fdPath;  // Set the src property and trigger the 'dataLoad' event callback.
6326}, (err: BusinessError) => {
6327  console.error('Failed to open fd, err is' + err);
6328}).catch((err: BusinessError) => {
6329  console.error('Failed to open fd, err is' + err);
6330});
6331```
6332
6333### on('timeUpdate')<sup>(deprecated)</sup>
6334
6335on(type: 'timeUpdate', callback: Callback\<number>): void
6336
6337Subscribes to the **'timeUpdate'** event. This event is reported every second when the audio playback is in progress.
6338
6339> **NOTE**
6340>
6341> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayer.on('timeUpdate')](#ontimeupdate9) instead.
6342
6343**System capability**: SystemCapability.Multimedia.Media.AudioPlayer
6344
6345**Parameters**
6346
6347| Name  | Type             | Mandatory| Description                                                        |
6348| -------- | ----------------- | ---- | ------------------------------------------------------------ |
6349| 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.|
6350| callback | Callback\<number> | Yes  | Callback invoked when the event is triggered. The input parameter is the updated timestamp.            |
6351
6352**Example**
6353
6354```ts
6355audioPlayer.on('timeUpdate', (newTime: number) => {    // Set the 'timeUpdate' event callback.
6356  if (newTime == null) {
6357    console.error('Failed to do timeUpadate');
6358    return;
6359  }
6360  console.info('Succeeded in doing timeUpadate. seekDoneTime: ' + newTime);
6361});
6362audioPlayer.play();    // The 'timeUpdate' event is triggered when the playback starts.
6363```
6364
6365### on('audioInterrupt')<sup>(deprecated)</sup>
6366
6367on(type: 'audioInterrupt', callback: (info: audio.InterruptEvent) => void): void
6368
6369Subscribes to the audio interruption event. For details, see [audio.InterruptEvent](../apis-audio-kit/js-apis-audio.md#interruptevent9).
6370
6371> **NOTE**
6372>
6373> This API is supported in API version 9 and deprecated since API version 9. You are advised to use [AVPlayer.on('audioInterrupt')](#onaudiointerrupt9) instead.
6374
6375**System capability**: SystemCapability.Multimedia.Media.AudioPlayer
6376
6377**Parameters**
6378
6379| Name  | Type                                                        | Mandatory| Description                                                    |
6380| -------- | ------------------------------------------------------------ | ---- | -------------------------------------------------------- |
6381| type     | string                                                       | Yes  | Event type, which is **'audioInterrupt'** in this case.|
6382| callback | function  | Yes  | Callback invoked when the event is triggered.                              |
6383
6384**Example**
6385
6386```ts
6387import { audio } from '@kit.AudioKit';
6388
6389audioPlayer.on('audioInterrupt', (info: audio.InterruptEvent) => {
6390  console.info('audioInterrupt called,and InterruptEvent info is:' + info);
6391});
6392```
6393
6394### on('error')<sup>(deprecated)</sup>
6395
6396on(type: 'error', callback: ErrorCallback): void
6397
6398Subscribes to audio playback error events. After an error event is reported, you must handle the event and exit the playback.
6399
6400> **NOTE**
6401>
6402> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayer.on('error')](#onerror9) instead.
6403
6404**System capability**: SystemCapability.Multimedia.Media.AudioPlayer
6405
6406**Parameters**
6407
6408| Name  | Type         | Mandatory| Description                                                        |
6409| -------- | ------------- | ---- | ------------------------------------------------------------ |
6410| type     | string        | Yes  | Event type, which is **'error'** in this case.<br>This event is triggered when an error occurs during audio playback.|
6411| callback | [ErrorCallback](../apis-basic-services-kit/js-apis-base.md#errorcallback) | Yes  | Callback invoked when the event is triggered.                                      |
6412
6413**Example**
6414
6415```ts
6416import { BusinessError } from '@kit.BasicServicesKit';
6417
6418audioPlayer.on('error', (error: BusinessError) => {  // Set the 'error' event callback.
6419  console.error(`audio error called, error: ${error}`);
6420});
6421audioPlayer.setVolume(3); // Set volume to an invalid value to trigger the 'error' event.
6422```
6423
6424## AudioState<sup>(deprecated)</sup>
6425
6426type AudioState = 'idle' | 'playing' | 'paused' | 'stopped' | 'error'
6427
6428Describes the audio playback state. You can obtain the state through the **state** property.
6429
6430> **NOTE**
6431>
6432> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVPlayerState](#avplayerstate9) instead.
6433
6434**System capability**: SystemCapability.Multimedia.Media.AudioPlayer
6435
6436| Type   | Description                                          |
6437| ------- | ---------------------------------------------- |
6438| 'idle'    | No audio playback is in progress. The audio player is in this state after the **'dataload'** or **'reset'** event is triggered.|
6439| 'playing' | Audio playback is in progress. The audio player is in this state after the **'play'** event is triggered.          |
6440| 'paused'  | Audio playback is paused. The audio player is in this state after the **'pause'** event is triggered.         |
6441| 'stopped' | Audio playback is stopped. The audio player is in this state after the **'stop'** event is triggered.     |
6442| 'error'   | Audio playback is in the error state.                                    |
6443
6444## VideoPlayer<sup>(deprecated)</sup>
6445
6446> **NOTE**
6447>
6448> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer](#avplayer9) instead.
6449
6450Provides APIs to manage and play video. Before calling any API of VideoPlayer, you must use [createVideoPlayer()](#mediacreatevideoplayerdeprecated) to create a VideoPlayer instance.
6451
6452### Properties
6453
6454**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
6455
6456| Name                           | Type                                                  | Read-Only| Optional| Description                                                        |
6457| ------------------------------- | ------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ |
6458| 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.|
6459| fdSrc<sup>9+</sup>              | [AVFileDescriptor](#avfiledescriptor9)                 | No  | No  | Description of a video file. This property 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>|
6460| 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.                |
6461| videoScaleType<sup>9+</sup>     | [VideoScaleType](#videoscaletype9)                     | No  | Yes  | Video scale type. The default value is **VIDEO_SCALE_TYPE_FIT**.                                              |
6462| audioInterruptMode<sup>9+</sup> | [audio.InterruptMode](../apis-audio-kit/js-apis-audio.md#interruptmode9) | No  | Yes  | Audio interruption mode.                                              |
6463| currentTime<sup>8+</sup>        | number                                                 | Yes  | No  | Current video playback position, in ms.                      |
6464| duration<sup>8+</sup>           | number                                                 | Yes  | No  | Video duration, in ms. The value **-1** indicates the live mode.            |
6465| state<sup>8+</sup>              | [VideoPlayState](#videoplaystatedeprecated)                    | Yes  | No  | Video playback state.                                            |
6466| width<sup>8+</sup>              | number                                                 | Yes  | No  | Video width, in px.                                  |
6467| height<sup>8+</sup>             | number                                                 | Yes  | No  | Video height, in px.                                  |
6468
6469### setDisplaySurface<sup>(deprecated)</sup>
6470
6471setDisplaySurface(surfaceId: string, callback: AsyncCallback\<void>): void
6472
6473Sets a surface ID. This API uses an asynchronous callback to return the result.
6474
6475*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.
6476
6477> **NOTE**
6478>
6479> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.surfaceId](#properties) instead.
6480
6481**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
6482
6483**Parameters**
6484
6485| Name   | Type                | Mandatory| Description                     |
6486| --------- | -------------------- | ---- | ------------------------- |
6487| surfaceId | string               | Yes  | Surface ID.                |
6488| callback  | AsyncCallback\<void> | Yes  | Callback used to return the result. If the setting is successful, **err** is **undefined**. Otherwise, **err** is an error object.|
6489
6490**Example**
6491
6492```ts
6493import { BusinessError } from '@kit.BasicServicesKit';
6494
6495let surfaceId: string = '';
6496videoPlayer.setDisplaySurface(surfaceId, (err: BusinessError) => {
6497  if (err) {
6498    console.error('Failed to set DisplaySurface!');
6499  } else {
6500    console.info('Succeeded in setting DisplaySurface!');
6501  }
6502});
6503```
6504
6505### setDisplaySurface<sup>(deprecated)</sup>
6506
6507setDisplaySurface(surfaceId: string): Promise\<void>
6508
6509Sets a surface ID. This API uses a promise to return the result.
6510
6511*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.
6512
6513> **NOTE**
6514>
6515> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.surfaceId](#properties) instead.
6516
6517**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
6518
6519**Parameters**
6520
6521| Name   | Type  | Mandatory| Description     |
6522| --------- | ------ | ---- | --------- |
6523| surfaceId | string | Yes  | Surface ID.|
6524
6525**Return value**
6526
6527| Type          | Description                          |
6528| -------------- | ------------------------------ |
6529| Promise\<void> | Promise that returns no value.|
6530
6531**Example**
6532
6533```ts
6534import { BusinessError } from '@kit.BasicServicesKit';
6535
6536let surfaceId: string = '';
6537videoPlayer.setDisplaySurface(surfaceId).then(() => {
6538  console.info('Succeeded in setting DisplaySurface');
6539}).catch((error: BusinessError) => {
6540  console.error(`video catchCallback, error:${error}`);
6541});
6542```
6543
6544### prepare<sup>(deprecated)</sup>
6545
6546prepare(callback: AsyncCallback\<void>): void
6547
6548Prepares for video playback. This API uses an asynchronous callback to return the result.
6549
6550> **NOTE**
6551>
6552> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.prepare](#prepare9) instead.
6553
6554**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
6555
6556**Parameters**
6557
6558| Name  | Type                | Mandatory| Description                    |
6559| -------- | -------------------- | ---- | ------------------------ |
6560| callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
6561
6562**Example**
6563
6564```ts
6565import { BusinessError } from '@kit.BasicServicesKit';
6566
6567videoPlayer.prepare((err: BusinessError) => {
6568  if (err) {
6569    console.error('Failed to prepare!');
6570  } else {
6571    console.info('Succeeded in preparing!');
6572  }
6573});
6574```
6575
6576### prepare<sup>(deprecated)</sup>
6577
6578prepare(): Promise\<void>
6579
6580Prepares for video playback. This API uses a promise to return the result.
6581
6582> **NOTE**
6583>
6584> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.prepare](#prepare9-1) instead.
6585
6586**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
6587
6588**Return value**
6589
6590| Type          | Description                         |
6591| -------------- | ----------------------------- |
6592| Promise\<void> | Promise that returns no value.|
6593
6594**Example**
6595
6596```ts
6597import { BusinessError } from '@kit.BasicServicesKit';
6598
6599videoPlayer.prepare().then(() => {
6600  console.info('Succeeded in preparing');
6601}).catch((error: BusinessError) => {
6602  console.error(`video catchCallback, error:${error}`);
6603});
6604```
6605
6606### play<sup>(deprecated)</sup>
6607
6608play(callback: AsyncCallback\<void>): void
6609
6610Starts video playback. This API uses an asynchronous callback to return the result.
6611
6612> **NOTE**
6613>
6614> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.play](#play9) instead.
6615
6616**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
6617
6618**Parameters**
6619
6620| Name  | Type                | Mandatory| Description                    |
6621| -------- | -------------------- | ---- | ------------------------ |
6622| callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
6623
6624**Example**
6625
6626```ts
6627import { BusinessError } from '@kit.BasicServicesKit';
6628
6629videoPlayer.play((err: BusinessError) => {
6630  if (err) {
6631    console.error('Failed to play!');
6632  } else {
6633    console.info('Succeeded in playing!');
6634  }
6635});
6636```
6637
6638### play<sup>(deprecated)</sup>
6639
6640play(): Promise\<void>
6641
6642Starts video playback. This API uses a promise to return the result.
6643
6644> **NOTE**
6645>
6646> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.play](#play9-1) instead.
6647
6648**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
6649
6650**Return value**
6651
6652| Type          | Description                         |
6653| -------------- | ----------------------------- |
6654| Promise\<void> | Promise that returns no value.|
6655
6656**Example**
6657
6658```ts
6659import { BusinessError } from '@kit.BasicServicesKit';
6660
6661videoPlayer.play().then(() => {
6662  console.info('Succeeded in playing');
6663}).catch((error: BusinessError) => {
6664  console.error(`video catchCallback, error:${error}`);
6665});
6666```
6667
6668### pause<sup>(deprecated)</sup>
6669
6670pause(callback: AsyncCallback\<void>): void
6671
6672Pauses video playback. This API uses an asynchronous callback to return the result.
6673
6674> **NOTE**
6675> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.pause](#pause9) instead.
6676
6677**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
6678
6679**Parameters**
6680
6681| Name  | Type                | Mandatory| Description                    |
6682| -------- | -------------------- | ---- | ------------------------ |
6683| callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
6684
6685**Example**
6686
6687```ts
6688import { BusinessError } from '@kit.BasicServicesKit';
6689
6690videoPlayer.pause((err: BusinessError) => {
6691  if (err) {
6692    console.error('Failed to pause!');
6693  } else {
6694    console.info('Succeeded in pausing!');
6695  }
6696});
6697```
6698
6699### pause<sup>(deprecated)</sup>
6700
6701pause(): Promise\<void>
6702
6703Pauses video playback. This API uses a promise to return the result.
6704
6705> **NOTE**
6706>
6707> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.pause](#pause9-1) instead.
6708
6709**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
6710
6711**Return value**
6712
6713| Type          | Description                         |
6714| -------------- | ----------------------------- |
6715| Promise\<void> | Promise that returns no value.|
6716
6717**Example**
6718
6719```ts
6720import { BusinessError } from '@kit.BasicServicesKit';
6721
6722videoPlayer.pause().then(() => {
6723  console.info('Succeeded in pausing');
6724}).catch((error: BusinessError) => {
6725  console.error(`video catchCallback, error:${error}`);
6726});
6727```
6728
6729### stop<sup>(deprecated)</sup>
6730
6731stop(callback: AsyncCallback\<void>): void
6732
6733Stops video playback. This API uses an asynchronous callback to return the result.
6734
6735> **NOTE**
6736>
6737> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.stop](#stop9) instead.
6738
6739**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
6740
6741**Parameters**
6742
6743| Name  | Type                | Mandatory| Description                    |
6744| -------- | -------------------- | ---- | ------------------------ |
6745| callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
6746
6747**Example**
6748
6749```ts
6750import { BusinessError } from '@kit.BasicServicesKit';
6751
6752videoPlayer.stop((err: BusinessError) => {
6753  if (err) {
6754    console.error('Failed to stop!');
6755  } else {
6756    console.info('Succeeded in stopping!');
6757  }
6758});
6759```
6760
6761### stop<sup>(deprecated)</sup>
6762
6763stop(): Promise\<void>
6764
6765Stops video playback. This API uses a promise to return the result.
6766
6767> **NOTE**
6768>
6769> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.stop](#stop9-1) instead.
6770
6771**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
6772
6773**Return value**
6774
6775| Type          | Description                         |
6776| -------------- | ----------------------------- |
6777| Promise\<void> | Promise that returns no value.|
6778
6779**Example**
6780
6781```ts
6782import { BusinessError } from '@kit.BasicServicesKit';
6783
6784videoPlayer.stop().then(() => {
6785  console.info('Succeeded in stopping');
6786}).catch((error: BusinessError) => {
6787  console.error(`video catchCallback, error:${error}`);
6788});
6789```
6790
6791### reset<sup>(deprecated)</sup>
6792
6793reset(callback: AsyncCallback\<void>): void
6794
6795Resets video playback. This API uses an asynchronous callback to return the result.
6796
6797> **NOTE**
6798>
6799> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.reset](#reset9) instead.
6800
6801**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
6802
6803**Parameters**
6804
6805| Name  | Type                | Mandatory| Description                    |
6806| -------- | -------------------- | ---- | ------------------------ |
6807| callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
6808
6809**Example**
6810
6811```ts
6812import { BusinessError } from '@kit.BasicServicesKit';
6813
6814videoPlayer.reset((err: BusinessError) => {
6815  if (err) {
6816    console.error('Failed to reset!');
6817  } else {
6818    console.info('Succeeded in resetting!');
6819  }
6820});
6821```
6822
6823### reset<sup>(deprecated)</sup>
6824
6825reset(): Promise\<void>
6826
6827Resets video playback. This API uses a promise to return the result.
6828
6829> **NOTE**
6830>
6831> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.reset](#reset9-1) instead.
6832
6833**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
6834
6835**Return value**
6836
6837| Type          | Description                         |
6838| -------------- | ----------------------------- |
6839| Promise\<void> | Promise that returns no value.|
6840
6841**Example**
6842
6843```ts
6844import { BusinessError } from '@kit.BasicServicesKit';
6845
6846videoPlayer.reset().then(() => {
6847  console.info('Succeeded in resetting');
6848}).catch((error: BusinessError) => {
6849  console.error(`video catchCallback, error:${error}`);
6850});
6851```
6852
6853### seek<sup>(deprecated)</sup>
6854
6855seek(timeMs: number, callback: AsyncCallback\<number>): void
6856
6857Seeks 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.
6858
6859> **NOTE**
6860>
6861> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.seek](#seek9) instead.
6862
6863**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
6864
6865**Parameters**
6866
6867| Name  | Type                  | Mandatory| Description                                                        |
6868| -------- | ---------------------- | ---- | ------------------------------------------------------------ |
6869| timeMs   | number                 | Yes  | Position to seek to, in ms. The value range is [0, duration].|
6870| 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.                              |
6871
6872**Example**
6873
6874```ts
6875import { BusinessError } from '@kit.BasicServicesKit';
6876
6877let videoPlayer: media.VideoPlayer;
6878media.createVideoPlayer((error: BusinessError, video: media.VideoPlayer) => {
6879  if (video != null) {
6880    videoPlayer = video;
6881    console.info('Succeeded in creating VideoPlayer');
6882  } else {
6883    console.error(`Failed to create VideoPlayer, error:${error}`);
6884  }
6885});
6886
6887let seekTime: number = 5000;
6888videoPlayer.seek(seekTime, (err: BusinessError, result: number) => {
6889  if (err) {
6890    console.error('Failed to do seek!');
6891  } else {
6892    console.info('Succeeded in doing seek!');
6893  }
6894});
6895```
6896
6897### seek<sup>(deprecated)</sup>
6898
6899seek(timeMs: number, mode:SeekMode, callback: AsyncCallback\<number>): void
6900
6901Seeks to the specified playback position. This API uses an asynchronous callback to return the result.
6902
6903> **NOTE**
6904>
6905> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.seek](#seek9) instead.
6906
6907**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
6908
6909**Parameters**
6910
6911| Name  | Type                  | Mandatory| Description                                                        |
6912| -------- | ---------------------- | ---- | ------------------------------------------------------------ |
6913| timeMs   | number                 | Yes  | Position to seek to, in ms. The value range is [0, duration].|
6914| mode     | [SeekMode](#seekmode8) | Yes  | Seek mode.                                                  |
6915| 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.                              |
6916
6917**Example**
6918
6919```ts
6920import { BusinessError } from '@kit.BasicServicesKit';
6921
6922let videoPlayer: media.VideoPlayer | null = null;
6923media.createVideoPlayer((error: BusinessError, video: media.VideoPlayer) => {
6924  if (video != null) {
6925    videoPlayer = video;
6926    console.info('Succeeded in creating VideoPlayer');
6927  } else {
6928    console.error(`Failed to create VideoPlayer, error:${error}`);
6929  }
6930});
6931let seekTime: number = 5000;
6932if (videoPlayer) {
6933  (videoPlayer as media.VideoPlayer).seek(seekTime, media.SeekMode.SEEK_NEXT_SYNC, (err: BusinessError, result: number) => {
6934    if (err) {
6935      console.error('Failed to do seek!');
6936    } else {
6937      console.info('Succeeded in doing seek!');
6938    }
6939  });
6940}
6941```
6942
6943### seek<sup>(deprecated)</sup>
6944
6945seek(timeMs: number, mode?:SeekMode): Promise\<number>
6946
6947Seeks 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.
6948
6949> **NOTE**
6950>
6951> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.seek](#seek9) instead.
6952
6953**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
6954
6955**Parameters**
6956
6957| Name| Type                  | Mandatory| Description                                                        |
6958| ------ | ---------------------- | ---- | ------------------------------------------------------------ |
6959| timeMs | number                 | Yes  | Position to seek to, in ms. The value range is [0, duration].|
6960| mode   | [SeekMode](#seekmode8) | No  | Seek mode based on the video I frame. The default value is **SEEK_PREV_SYNC**.           |
6961
6962**Return value**
6963
6964| Type            | Description                                       |
6965| ---------------- | ------------------------------------------- |
6966| Promise\<number>| Promise used to return the playback position, in ms.|
6967
6968**Example**
6969
6970```ts
6971import { BusinessError } from '@kit.BasicServicesKit';
6972
6973let videoPlayer: media.VideoPlayer | null = null;
6974media.createVideoPlayer((error: BusinessError, video: media.VideoPlayer) => {
6975  if (video != null) {
6976    videoPlayer = video;
6977    console.info('Succeeded in creating VideoPlayer');
6978  } else {
6979    console.error(`Failed to create VideoPlayer, error:${error}`);
6980  }
6981});
6982let seekTime: number = 5000;
6983if (videoPlayer) {
6984  (videoPlayer as media.VideoPlayer).seek(seekTime).then((seekDoneTime: number) => { // seekDoneTime indicates the position after the seek operation is complete.
6985    console.info('Succeeded in doing seek');
6986  }).catch((error: BusinessError) => {
6987    console.error(`video catchCallback, error:${error}`);
6988  });
6989
6990  (videoPlayer as media.VideoPlayer).seek(seekTime, media.SeekMode.SEEK_NEXT_SYNC).then((seekDoneTime: number) => {
6991    console.info('Succeeded in doing seek');
6992  }).catch((error: BusinessError) => {
6993    console.error(`video catchCallback, error:${error}`);
6994  });
6995}
6996```
6997
6998### setVolume<sup>(deprecated)</sup>
6999
7000setVolume(vol: number, callback: AsyncCallback\<void>): void
7001
7002Sets the volume. This API uses an asynchronous callback to return the result.
7003
7004> **NOTE**
7005>
7006> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.setVolume](#setvolume9) instead.
7007
7008**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
7009
7010**Parameters**
7011
7012| Name  | Type                | Mandatory| Description                                                        |
7013| -------- | -------------------- | ---- | ------------------------------------------------------------ |
7014| vol      | number               | Yes  | Relative volume. The value ranges from 0.00 to 1.00. The value **1.00** indicates the maximum volume (100%).|
7015| callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the setting is successful, **err** is **undefined**. Otherwise, **err** is an error object.|
7016
7017**Example**
7018
7019```ts
7020import { BusinessError } from '@kit.BasicServicesKit';
7021
7022let vol: number = 0.5;
7023videoPlayer.setVolume(vol, (err: BusinessError) => {
7024  if (err) {
7025    console.error('Failed to set Volume!');
7026  } else {
7027    console.info('Succeeded in setting Volume!');
7028  }
7029});
7030```
7031
7032### setVolume<sup>(deprecated)</sup>
7033
7034setVolume(vol: number): Promise\<void>
7035
7036Sets the volume. This API uses a promise to return the result.
7037
7038> **NOTE**
7039>
7040> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.setVolume](#setvolume9) instead.
7041
7042**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
7043
7044**Parameters**
7045
7046| Name| Type  | Mandatory| Description                                                        |
7047| ------ | ------ | ---- | ------------------------------------------------------------ |
7048| vol    | number | Yes  | Relative volume. The value ranges from 0.00 to 1.00. The value **1.00** indicates the maximum volume (100%).|
7049
7050**Return value**
7051
7052| Type          | Description                     |
7053| -------------- | ------------------------- |
7054| Promise\<void> | Promise that returns no value.|
7055
7056**Example**
7057
7058```ts
7059import { BusinessError } from '@kit.BasicServicesKit';
7060
7061let vol: number = 0.5;
7062videoPlayer.setVolume(vol).then(() => {
7063  console.info('Succeeded in setting Volume');
7064}).catch((error: BusinessError) => {
7065  console.error(`video catchCallback, error:${error}`);
7066});
7067```
7068
7069### release<sup>(deprecated)</sup>
7070
7071release(callback: AsyncCallback\<void>): void
7072
7073Releases the video playback resources. This API uses an asynchronous callback to return the result.
7074
7075> **NOTE**
7076>
7077> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.release](#release9) instead.
7078
7079**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
7080
7081**Parameters**
7082
7083| Name  | Type                | Mandatory| Description                    |
7084| -------- | -------------------- | ---- | ------------------------ |
7085| callback | AsyncCallback\<void> | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
7086
7087**Example**
7088
7089```ts
7090import { BusinessError } from '@kit.BasicServicesKit';
7091
7092videoPlayer.release((err: BusinessError) => {
7093  if (err) {
7094    console.error('Failed to release!');
7095  } else {
7096    console.info('Succeeded in releasing!');
7097  }
7098});
7099```
7100
7101### release<sup>(deprecated)</sup>
7102
7103release(): Promise\<void>
7104
7105Releases the video playback resources. This API uses a promise to return the result.
7106
7107> **NOTE**
7108>
7109> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.release](#release9-1) instead.
7110
7111**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
7112
7113**Return value**
7114
7115| Type          | Description                         |
7116| -------------- | ----------------------------- |
7117| Promise\<void> | Promise that returns no value.|
7118
7119**Example**
7120
7121```ts
7122import { BusinessError } from '@kit.BasicServicesKit';
7123
7124videoPlayer.release().then(() => {
7125  console.info('Succeeded in releasing');
7126}).catch((error: BusinessError) => {
7127  console.error(`video catchCallback, error:${error}`);
7128});
7129```
7130
7131### getTrackDescription<sup>(deprecated)</sup>
7132
7133getTrackDescription(callback: AsyncCallback\<Array\<MediaDescription>>): void
7134
7135Obtains the video track information. This API uses an asynchronous callback to return the result.
7136
7137> **NOTE**
7138>
7139> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.getTrackDescription](#gettrackdescription9) instead.
7140
7141**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
7142
7143**Parameters**
7144
7145| Name  | Type                                                        | Mandatory| Description                                      |
7146| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------ |
7147| 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.|
7148
7149**Example**
7150
7151```ts
7152import { BusinessError } from '@kit.BasicServicesKit';
7153
7154videoPlayer.getTrackDescription((error: BusinessError, arrList: Array<media.MediaDescription>) => {
7155  if ((arrList) != null) {
7156    console.info('Succeeded in getting TrackDescription');
7157  } else {
7158    console.error(`Failed to get TrackDescription, error:${error}`);
7159  }
7160});
7161```
7162
7163### getTrackDescription<sup>(deprecated)</sup>
7164
7165getTrackDescription(): Promise\<Array\<MediaDescription>>
7166
7167Obtains the video track information. This API uses a promise to return the result.
7168
7169> **NOTE**
7170>
7171> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.getTrackDescription](#gettrackdescription9-1) instead.
7172
7173**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
7174
7175**Return value**
7176
7177| Type                                                  | Description                                           |
7178| ------------------------------------------------------ | ----------------------------------------------- |
7179| Promise<Array<[MediaDescription](#mediadescription8)>> | Promise used to return the MediaDescription array that holds the video track information.|
7180
7181**Example**
7182
7183```ts
7184import { BusinessError } from '@kit.BasicServicesKit';
7185
7186videoPlayer.getTrackDescription().then((arrList: Array<media.MediaDescription>) => {
7187  if (arrList != null) {
7188    console.info('Succeeded in getting TrackDescription');
7189  } else {
7190    console.error('Failed to get TrackDescription');
7191  }
7192}).catch((error: BusinessError) => {
7193  console.error(`video catchCallback, error:${error}`);
7194});
7195```
7196
7197### setSpeed<sup>(deprecated)</sup>
7198
7199setSpeed(speed: number, callback: AsyncCallback\<number>): void
7200
7201Sets the playback speed. This API uses an asynchronous callback to return the result.
7202
7203> **NOTE**
7204>
7205> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.setSpeed](#setspeed9) instead.
7206
7207**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
7208
7209**Parameters**
7210
7211| Name  | Type                  | Mandatory| Description                                                      |
7212| -------- | ---------------------- | ---- | ---------------------------------------------------------- |
7213| speed    | number                 | Yes  | Video playback speed. For details, see [PlaybackSpeed](#playbackspeed8).|
7214| 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.                                  |
7215
7216**Example**
7217
7218```ts
7219import { BusinessError } from '@kit.BasicServicesKit';
7220
7221let videoPlayer: media.VideoPlayer | null = null;
7222media.createVideoPlayer((error: BusinessError, video: media.VideoPlayer) => {
7223  if (video != null) {
7224    videoPlayer = video;
7225    console.info('Succeeded in creating VideoPlayer');
7226  } else {
7227    console.error(`Failed to create VideoPlayer, error:${error}`);
7228  }
7229});
7230let speed = media.PlaybackSpeed.SPEED_FORWARD_2_00_X;
7231if (videoPlayer) {
7232  (videoPlayer as media.VideoPlayer).setSpeed(speed, (err: BusinessError, result: number) => {
7233    if (err) {
7234      console.error('Failed to set Speed!');
7235    } else {
7236      console.info('Succeeded in setting Speed!');
7237    }
7238  });
7239}
7240```
7241
7242### setSpeed<sup>(deprecated)</sup>
7243
7244setSpeed(speed: number): Promise\<number>
7245
7246Sets the playback speed. This API uses a promise to return the result.
7247
7248> **NOTE**
7249>
7250> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.setSpeed](#setspeed9) instead.
7251
7252**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
7253
7254**Parameters**
7255
7256| Name| Type  | Mandatory| Description                                                      |
7257| ------ | ------ | ---- | ---------------------------------------------------------- |
7258| speed  | number | Yes  | Video playback speed. For details, see [PlaybackSpeed](#playbackspeed8).|
7259
7260**Return value**
7261
7262| Type            | Description                                                        |
7263| ---------------- | ------------------------------------------------------------ |
7264| Promise\<number>| Promise used to return the playback speed. For details, see [PlaybackSpeed](#playbackspeed8).|
7265
7266**Example**
7267
7268```ts
7269import { BusinessError } from '@kit.BasicServicesKit';
7270
7271let videoPlayer: media.VideoPlayer | null = null;
7272media.createVideoPlayer((error: BusinessError, video: media.VideoPlayer) => {
7273  if (video != null) {
7274    videoPlayer = video;
7275    console.info('Succeeded in creating VideoPlayer');
7276  } else {
7277    console.error(`Failed to create VideoPlayer, error:${error}`);
7278  }
7279});
7280let speed = media.PlaybackSpeed.SPEED_FORWARD_2_00_X;
7281if (videoPlayer) {
7282  (videoPlayer as media.VideoPlayer).setSpeed(speed).then((result: number) => {
7283    console.info('Succeeded in setting Speed');
7284  }).catch((error: BusinessError) => {
7285    console.error(`Failed to set Speed, error:${error}`);//todo:: error.
7286  });
7287}
7288```
7289
7290### on('playbackCompleted')<sup>(deprecated)</sup>
7291
7292on(type: 'playbackCompleted', callback: Callback\<void>): void
7293
7294Subscribes to the video playback completion event.
7295
7296> **NOTE**
7297>
7298> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.on('stateChange')](#onstatechange9) instead.
7299
7300**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
7301
7302**Parameters**
7303
7304| Name  | Type    | Mandatory| Description                                                       |
7305| -------- | -------- | ---- | ----------------------------------------------------------- |
7306| type     | string   | Yes  | Event type, which is **'playbackCompleted'** in this case.|
7307| callback | Callback\<void> | Yes  | Callback invoked when the event is triggered.                                 |
7308
7309**Example**
7310
7311```ts
7312videoPlayer.on('playbackCompleted', () => {
7313  console.info('playbackCompleted called!');
7314});
7315```
7316
7317### on('bufferingUpdate')<sup>(deprecated)</sup>
7318
7319on(type: 'bufferingUpdate', callback: (infoType: BufferingInfoType, value: number) => void): void
7320
7321Subscribes to the video buffering update event. This API works only under online playback.
7322
7323> **NOTE**
7324>
7325> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.on('bufferingUpdate')](#onbufferingupdate9) instead.
7326
7327**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
7328
7329**Parameters**
7330
7331| Name  | Type    | Mandatory| Description                                                        |
7332| -------- | -------- | ---- | ------------------------------------------------------------ |
7333| type     | string   | Yes  | Event type, which is **'bufferingUpdate'** in this case.       |
7334| callback | function | Yes  | Callback invoked when the event is triggered.<br>The value of [BufferingInfoType](#bufferinginfotype8) is fixed at **0**.|
7335
7336**Example**
7337
7338```ts
7339videoPlayer.on('bufferingUpdate', (infoType: media.BufferingInfoType, value: number) => {
7340  console.info('video bufferingInfo type: ' + infoType);
7341  console.info('video bufferingInfo value: ' + value);
7342});
7343```
7344
7345### on('startRenderFrame')<sup>(deprecated)</sup>
7346
7347on(type: 'startRenderFrame', callback: Callback\<void>): void
7348
7349Subscribes to the frame rendering start event.
7350
7351> **NOTE**
7352>
7353> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.on('startRenderFrame')](#onstartrenderframe9) instead.
7354
7355**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
7356
7357**Parameters**
7358
7359| Name  | Type           | Mandatory| Description                                                        |
7360| -------- | --------------- | ---- | ------------------------------------------------------------ |
7361| type     | string          | Yes  | Event type, which is **'startRenderFrame'** in this case.|
7362| callback | Callback\<void> | Yes  | Callback invoked when the event is triggered.                          |
7363
7364**Example**
7365
7366```ts
7367videoPlayer.on('startRenderFrame', () => {
7368  console.info('startRenderFrame called!');
7369});
7370```
7371
7372### on('videoSizeChanged')<sup>(deprecated)</sup>
7373
7374on(type: 'videoSizeChanged', callback: (width: number, height: number) => void): void
7375
7376Subscribes to the video width and height change event.
7377
7378> **NOTE**
7379> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.on('videoSizeChange')](#onvideosizechange9) instead.
7380
7381**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
7382
7383**Parameters**
7384
7385| Name  | Type    | Mandatory| Description                                                        |
7386| -------- | -------- | ---- | ------------------------------------------------------------ |
7387| type     | string   | Yes  | Event type, which is **'videoSizeChanged'** in this case.|
7388| callback | function | Yes  | Callback invoked when the event is triggered. **width** indicates the video width, and **height** indicates the video height.   |
7389
7390**Example**
7391
7392```ts
7393videoPlayer.on('videoSizeChanged', (width: number, height: number) => {
7394  console.info('video width is: ' + width);
7395  console.info('video height is: ' + height);
7396});
7397```
7398### on('audioInterrupt')<sup>(deprecated)</sup>
7399
7400on(type: 'audioInterrupt', callback: (info: audio.InterruptEvent) => void): void
7401
7402Subscribes to the audio interruption event. For details, see [audio.InterruptEvent](../apis-audio-kit/js-apis-audio.md#interruptevent9).
7403
7404> **NOTE**
7405>
7406> This API is supported in API version 9 and deprecated since API version 9. You are advised to use [AVPlayer.on('audioInterrupt')](#onaudiointerrupt9) instead.
7407
7408**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
7409
7410**Parameters**
7411
7412| Name  | Type                                                        | Mandatory| Description                                                    |
7413| -------- | ------------------------------------------------------------ | ---- | -------------------------------------------------------- |
7414| type     | string                                                       | Yes  | Event type, which is **'audioInterrupt'** in this case.|
7415| callback | function | Yes  | Callback invoked when the event is triggered.                              |
7416
7417**Example**
7418
7419```ts
7420import { audio } from '@kit.AudioKit';
7421
7422videoPlayer.on('audioInterrupt', (info: audio.InterruptEvent) => {
7423  console.info('audioInterrupt called,and InterruptEvent info is:' + info);
7424});
7425```
7426
7427### on('error')<sup>(deprecated)</sup>
7428
7429on(type: 'error', callback: ErrorCallback): void
7430
7431Subscribes to video playback error events. After an error event is reported, you must handle the event and exit the playback.
7432
7433> **NOTE**
7434>
7435> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayer.on('error')](#onerror9) instead.
7436
7437**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
7438
7439**Parameters**
7440
7441| Name  | Type         | Mandatory| Description                                                        |
7442| -------- | ------------- | ---- | ------------------------------------------------------------ |
7443| type     | string        | Yes  | Event type, which is **'error'** in this case.<br>This event is triggered when an error occurs during video playback.|
7444| callback | [ErrorCallback](../apis-basic-services-kit/js-apis-base.md#errorcallback) | Yes  | Callback invoked when the event is triggered.                                      |
7445
7446**Example**
7447
7448```ts
7449import { BusinessError } from '@kit.BasicServicesKit';
7450
7451videoPlayer.on('error', (error: BusinessError) => {  // Set the 'error' event callback.
7452  console.error(`video error called, error: ${error}`);
7453});
7454videoPlayer.url = 'fd://error';  // Set an incorrect URL to trigger the 'error' event.
7455```
7456
7457## VideoPlayState<sup>(deprecated)</sup>
7458
7459type VideoPlayState = 'idle' | 'prepared' | 'playing' | 'paused' | 'stopped' | 'error'
7460
7461Describes the video playback state. You can obtain the state through the **state** property.
7462
7463> **NOTE**
7464>
7465> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AVPlayerState](#avplayerstate9) instead.
7466
7467**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
7468
7469| Type    | Description          |
7470| -------- | -------------- |
7471| 'idle'     | The video player is idle.|
7472| 'prepared' | Video playback is being prepared.|
7473| 'playing'  | Video playback is in progress.|
7474| 'paused'   | Video playback is paused.|
7475| 'stopped'  | Video playback is stopped.|
7476| 'error'    | Video playback is in the error state.    |
7477
7478## AudioRecorder<sup>(deprecated)</sup>
7479
7480> **NOTE**
7481>
7482> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVRecorder](#avrecorder9) instead.
7483
7484Implements audio recording. Before calling any API of AudioRecorder, you must use [createAudioRecorder()](#mediacreateaudiorecorderdeprecated) to create an AudioRecorder instance.
7485
7486### prepare<sup>(deprecated)</sup>
7487
7488prepare(config: AudioRecorderConfig): void
7489
7490Prepares for recording.
7491
7492> **NOTE**
7493>
7494> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVRecorder.prepare](#prepare9-2) instead.
7495
7496**Required permissions:** ohos.permission.MICROPHONE
7497
7498**System capability**: SystemCapability.Multimedia.Media.AudioRecorder
7499
7500**Parameters**
7501
7502| Name| Type                                       | Mandatory| Description                                                        |
7503| ------ | ------------------------------------------- | ---- | ------------------------------------------------------------ |
7504| config | [AudioRecorderConfig](#audiorecorderconfigdeprecated) | Yes  | Audio recording parameters, including the audio output URI, encoding format, sampling rate, number of audio channels, and output format.|
7505
7506**Error codes**
7507
7508For details about the error codes, see [Media Error Codes](errorcode-media.md).
7509
7510| ID| Error Message             |
7511| -------- | --------------------- |
7512| 201      | permission denied     |
7513
7514**Example**
7515
7516```ts
7517let audioRecorderConfig: media.AudioRecorderConfig = {
7518  audioEncoder : media.AudioEncoder.AAC_LC,
7519  audioEncodeBitRate : 22050,
7520  audioSampleRate : 22050,
7521  numberOfChannels : 2,
7522  format : media.AudioOutputFormat.AAC_ADTS,
7523  uri : 'fd://1',       // The file must be created by the caller and granted with proper permissions.
7524  location : { latitude : 30, longitude : 130},
7525};
7526audioRecorder.on('prepare', () => {    // Set the 'prepare' event callback.
7527  console.info('prepare called');
7528});
7529audioRecorder.prepare(audioRecorderConfig);
7530```
7531
7532### start<sup>(deprecated)</sup>
7533
7534start(): void
7535
7536Starts audio recording. This API can be called only after the **'prepare'** event is triggered.
7537
7538> **NOTE**
7539>
7540> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVRecorder.start](#start9) instead.
7541
7542**System capability**: SystemCapability.Multimedia.Media.AudioRecorder
7543
7544**Example**
7545
7546```ts
7547audioRecorder.on('start', () => {    // Set the 'start' event callback.
7548  console.info('audio recorder start called');
7549});
7550audioRecorder.start();
7551```
7552
7553### pause<sup>(deprecated)</sup>
7554
7555pause():void
7556
7557Pauses audio recording. This API can be called only after the **'start'** event is triggered.
7558
7559> **NOTE**
7560>
7561> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVRecorder.pause](#pause9-2) instead.
7562
7563**System capability**: SystemCapability.Multimedia.Media.AudioRecorder
7564
7565**Example**
7566
7567```ts
7568audioRecorder.on('pause', () => {    // Set the 'pause' event callback.
7569  console.info('audio recorder pause called');
7570});
7571audioRecorder.pause();
7572```
7573
7574### resume<sup>(deprecated)</sup>
7575
7576resume():void
7577
7578Resumes audio recording. This API can be called only after the **'pause'** event is triggered.
7579
7580> **NOTE**
7581>
7582> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVRecorder.resume](#resume9) instead.
7583
7584**System capability**: SystemCapability.Multimedia.Media.AudioRecorder
7585
7586**Example**
7587
7588```ts
7589audioRecorder.on('resume', () => { // Set the 'resume' event callback.
7590  console.info('audio recorder resume called');
7591});
7592audioRecorder.resume();
7593```
7594
7595### stop<sup>(deprecated)</sup>
7596
7597stop(): void
7598
7599Stops audio recording.
7600
7601> **NOTE**
7602>
7603> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVRecorder.stop](#stop9-2) instead.
7604
7605**System capability**: SystemCapability.Multimedia.Media.AudioRecorder
7606
7607**Example**
7608
7609```ts
7610audioRecorder.on('stop', () => {    // Set the 'stop' event callback.
7611  console.info('audio recorder stop called');
7612});
7613audioRecorder.stop();
7614```
7615
7616### release<sup>(deprecated)</sup>
7617
7618release(): void
7619
7620Releases the audio recording resources.
7621
7622> **NOTE**
7623>
7624> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVRecorder.release](#release9-2) instead.
7625
7626**System capability**: SystemCapability.Multimedia.Media.AudioRecorder
7627
7628**Example**
7629
7630```ts
7631audioRecorder.on('release', () => {    // Set the 'release' event callback.
7632  console.info('audio recorder release called');
7633});
7634audioRecorder.release();
7635audioRecorder = undefined;
7636```
7637
7638### reset<sup>(deprecated)</sup>
7639
7640reset(): void
7641
7642Resets audio recording.
7643
7644Before 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.
7645
7646> **NOTE**
7647>
7648> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVRecorder.reset](#reset9-2) instead.
7649
7650**System capability**: SystemCapability.Multimedia.Media.AudioRecorder
7651
7652**Example**
7653
7654```ts
7655audioRecorder.on('reset', () => {    // Set the 'reset' event callback.
7656  console.info('audio recorder reset called');
7657});
7658audioRecorder.reset();
7659```
7660
7661### on('prepare' | 'start' | 'pause' | 'resume' | 'stop' | 'release' | 'reset')<sup>(deprecated)</sup>
7662
7663on(type: 'prepare' | 'start' | 'pause' | 'resume' | 'stop' | 'release' | 'reset', callback: () => void): void
7664
7665Subscribes to the audio recording events.
7666
7667> **NOTE**
7668>
7669> 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.
7670
7671**System capability**: SystemCapability.Multimedia.Media.AudioRecorder
7672
7673**Parameters**
7674
7675| Name  | Type    | Mandatory| Description                                                        |
7676| -------- | -------- | ---- | ------------------------------------------------------------ |
7677| 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.|
7678| callback | ()=>void | Yes  | Callback invoked when the event is triggered.                                          |
7679
7680**Example**
7681
7682```ts
7683import { BusinessError } from '@kit.BasicServicesKit';
7684
7685let audioRecorder: media.AudioRecorder = media.createAudioRecorder(); // Create an AudioRecorder instance.
7686let audioRecorderConfig: media.AudioRecorderConfig = {
7687  audioEncoder : media.AudioEncoder.AAC_LC,
7688  audioEncodeBitRate : 22050,
7689  audioSampleRate : 22050,
7690  numberOfChannels : 2,
7691  format : media.AudioOutputFormat.AAC_ADTS,
7692  uri : 'fd://xx',  // The file must be created by the caller and granted with proper permissions.
7693  location : { latitude : 30, longitude : 130}
7694};
7695audioRecorder.on('error', (error: BusinessError) => {  // Set the 'error' event callback.
7696  console.error(`audio error called, error: ${error}`);
7697});
7698audioRecorder.on('prepare', () => {  // Set the 'prepare' event callback.
7699  console.info('prepare called');
7700  audioRecorder.start();  // // Start recording and trigger the 'start' event callback.
7701});
7702audioRecorder.on('start', () => {  // Set the 'start' event callback.
7703  console.info('audio recorder start called');
7704});
7705audioRecorder.on('pause', () => {  // Set the 'pause' event callback.
7706  console.info('audio recorder pause called');
7707});
7708audioRecorder.on('resume', () => {  // Set the 'resume' event callback.
7709  console.info('audio recorder resume called');
7710});
7711audioRecorder.on('stop', () => {  // Set the 'stop' event callback.
7712  console.info('audio recorder stop called');
7713});
7714audioRecorder.on('release', () => {  // Set the 'release' event callback.
7715  console.info('audio recorder release called');
7716});
7717audioRecorder.on('reset', () => {  // Set the 'reset' event callback.
7718  console.info('audio recorder reset called');
7719});
7720audioRecorder.prepare(audioRecorderConfig)  // // Set recording parameters and trigger the 'prepare' event callback.
7721```
7722
7723### on('error')<sup>(deprecated)</sup>
7724
7725on(type: 'error', callback: ErrorCallback): void
7726
7727Subscribes to audio recording error events. After an error event is reported, you must handle the event and exit the recording.
7728
7729> **NOTE**
7730>
7731> 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.
7732
7733**System capability**: SystemCapability.Multimedia.Media.AudioRecorder
7734
7735**Parameters**
7736
7737| Name  | Type         | Mandatory| Description                                                        |
7738| -------- | ------------- | ---- | ------------------------------------------------------------ |
7739| type     | string        | Yes  | Event type, which is **'error'** in this case.<br>This event is triggered when an error occurs during audio recording.|
7740| callback | [ErrorCallback](../apis-basic-services-kit/js-apis-base.md#errorcallback) | Yes  | Callback invoked when the event is triggered.                                      |
7741
7742**Example**
7743
7744```ts
7745import { BusinessError } from '@kit.BasicServicesKit';
7746
7747let audioRecorderConfig: media.AudioRecorderConfig = {
7748  audioEncoder : media.AudioEncoder.AAC_LC,
7749  audioEncodeBitRate : 22050,
7750  audioSampleRate : 22050,
7751  numberOfChannels : 2,
7752  format : media.AudioOutputFormat.AAC_ADTS,
7753  uri : 'fd://xx',   // The file must be created by the caller and granted with proper permissions.
7754  location : { latitude : 30, longitude : 130}
7755};
7756audioRecorder.on('error', (error: BusinessError) => {  // Set the 'error' event callback.
7757  console.error(`audio error called, error: ${error}`);
7758});
7759audioRecorder.prepare(audioRecorderConfig);  // // Do not set any parameter in prepare and trigger the 'error' event callback.
7760```
7761
7762## AudioRecorderConfig<sup>(deprecated)</sup>
7763
7764> **NOTE**
7765>
7766> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [AVRecorderConfig](#avrecorderconfig9) instead.
7767
7768Describes audio recording configurations.
7769
7770**System capability**: SystemCapability.Multimedia.Media.AudioRecorder
7771
7772| Name                               | Type                                        | Mandatory| Description                                                        |
7773| ----------------------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ |
7774| 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.|
7775| audioEncodeBitRate                  | number                                       | No  | Audio encoding bit rate. The default value is **48000**.                             |
7776| audioSampleRate                     | number                                       | No  | Audio sampling rate. The default value is **48000**.<br>Variable bit rate. The bit rate is for reference only.                             |
7777| numberOfChannels                    | number                                       | No  | Number of audio channels. The default value is **2**.                                 |
7778| 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.|
7779| location                            | [Location](#location)                        | No  | Geographical location of the recorded audio.                                        |
7780| 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.|
7781| audioEncoderMime<sup>8+</sup>       | [CodecMimeType](#codecmimetype8)             | No  | Container encoding format.                                              |
7782| fileFormat<sup>8+</sup>             | [ContainerFormatType](#containerformattype8) | No  | Audio encoding format.                                              |
7783
7784## AudioEncoder<sup>(deprecated)</sup>
7785
7786> **NOTE**
7787>
7788> This API is supported since API version 6 and deprecated since API version 8. You are advised to use [CodecMimeType](#codecmimetype8) instead.
7789
7790Enumerates the audio encoding formats.
7791
7792**System capability**: SystemCapability.Multimedia.Media.AudioRecorder
7793
7794| Name   | Value  | Description                                                        |
7795| ------- | ---- | ------------------------------------------------------------ |
7796| DEFAULT | 0    | Default encoding format.<br>This API is defined but not implemented yet.             |
7797| AMR_NB  | 1    | AMR-NB.<br>This API is defined but not implemented yet.|
7798| AMR_WB  | 2    | Adaptive Multi Rate-Wide Band Speech Codec (AMR-WB).<br>This API is defined but not implemented yet.|
7799| AAC_LC  | 3    | Advanced Audio Coding Low Complexity (AAC-LC).|
7800| HE_AAC  | 4    | High-Efficiency Advanced Audio Coding (HE_AAC).<br>This API is defined but not implemented yet.|
7801
7802## AudioOutputFormat<sup>(deprecated)</sup>
7803
7804> **NOTE**
7805>
7806> This API is supported since API version 6 and deprecated since API version 8. You are advised to use [ContainerFormatType](#containerformattype8) instead.
7807
7808Enumerates the audio output formats.
7809
7810**System capability**: SystemCapability.Multimedia.Media.AudioRecorder
7811
7812| Name    | Value  | Description                                                        |
7813| -------- | ---- | ------------------------------------------------------------ |
7814| DEFAULT  | 0    | Default output format.<br>This API is defined but not implemented yet.             |
7815| MPEG_4   | 2    | MPEG-4.                                          |
7816| AMR_NB   | 3    | AMR_NB.<br>This API is defined but not implemented yet.         |
7817| AMR_WB   | 4    | AMR_WB.<br>This API is defined but not implemented yet.         |
7818| AAC_ADTS | 6    | Audio Data Transport Stream (ADTS), which is a transport stream format of AAC-based audio.|
7819
7820
7821## media.createAVImageGenerator<sup>12+</sup>
7822
7823createAVImageGenerator(callback: AsyncCallback\<AVImageGenerator>): void
7824
7825Creates an AVImageGenerator instance. This API uses an asynchronous callback to return the result.
7826
7827**System capability**: SystemCapability.Multimedia.Media.AVImageGenerator
7828
7829**Parameters**
7830
7831| Name  | Type                                 | Mandatory| Description                                                        |
7832| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ |
7833| 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.|
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| 5400101  | No memory. Returned by callback. |
7842
7843**Example**
7844
7845```ts
7846import { BusinessError } from '@kit.BasicServicesKit';
7847
7848let avImageGenerator: media.AVImageGenerator;
7849media.createAVImageGenerator((error: BusinessError, generator: media.AVImageGenerator) => {
7850  if (generator != null) {
7851    avImageGenerator = generator;
7852    console.info('Succeeded in creating AVImageGenerator');
7853  } else {
7854    console.error(`Failed to creat AVImageGenerator, error message:${error.message}`);
7855  }
7856});
7857```
7858
7859## media.createAVImageGenerator<sup>12+</sup>
7860
7861createAVImageGenerator(): Promise\<AVImageGenerator>
7862
7863Creates an AVImageGenerator instance. This API uses a promise to return the result.
7864
7865**System capability**: SystemCapability.Multimedia.Media.AVImageGenerator
7866
7867**Return value**
7868
7869| Type                           | Description                                                        |
7870| ------------------------------- | ------------------------------------------------------------ |
7871| 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.|
7872
7873**Error codes**
7874
7875For details about the error codes, see [Media Error Codes](errorcode-media.md).
7876
7877| ID| Error Message                     |
7878| -------- | ----------------------------- |
7879| 5400101  | No memory. Returned by promise. |
7880
7881**Example**
7882
7883```ts
7884import { BusinessError } from '@kit.BasicServicesKit';
7885
7886let avImageGenerator: media.AVImageGenerator;
7887media.createAVImageGenerator().then((generator: media.AVImageGenerator) => {
7888  if (generator != null) {
7889    avImageGenerator = generator;
7890    console.info('Succeeded in creating AVImageGenerator');
7891  } else {
7892    console.error('Failed to creat AVImageGenerator');
7893  }
7894}).catch((error: BusinessError) => {
7895  console.error(`Failed to creat AVImageGenerator, error message:${error.message}`);
7896});
7897```
7898
7899## AVImageGenerator<sup>12+</sup>
7900
7901Provides APIs to obtain a thumbnail from a video. Before calling any API of AVImageGenerator, you must use [createAVImageGenerator()](#mediacreateavimagegenerator12) to create an AVImageGenerator instance.
7902
7903For details about the demo for obtaining video thumbnails, see [Obtaining Video Thumbnails](../../media/media/avimagegenerator.md).
7904
7905### Properties
7906
7907**System capability**: SystemCapability.Multimedia.Media.AVImageGenerator
7908
7909| Name                                               | Type                                                        | Readable| Writable| Description                                                        |
7910| --------------------------------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ |
7911| 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.|
7912
7913### fetchFrameByTime<sup>12+</sup>
7914
7915fetchFrameByTime(timeUs: number, options: AVImageQueryOptions, param: PixelMapParams, callback: AsyncCallback\<image.PixelMap>): void
7916
7917Obtains a video thumbnail. This API uses an asynchronous callback to return the result.
7918
7919**System capability**: SystemCapability.Multimedia.Media.AVImageGenerator
7920
7921**Parameters**
7922
7923| Name  | Type                                        | Mandatory| Description                               |
7924| -------- | -------------------------------------------- | ---- | ----------------------------------- |
7925| timeUs | number                   | Yes  | Time of the video for which a thumbnail is to be obtained, in μs.|
7926| options | [AVImageQueryOptions](#avimagequeryoptions12)     | Yes  | Relationship between the time passed in and the video frame.|
7927| param | [PixelMapParams](#pixelmapparams12)     | Yes  | Format parameters of the thumbnail to be obtained.|
7928| callback | AsyncCallback\<[image.PixelMap](../apis-image-kit/arkts-apis-image-PixelMap.md)>   | 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.|
7929
7930**Error codes**
7931
7932For details about the error codes, see [Media Error Codes](errorcode-media.md).
7933
7934| ID| Error Message                                  |
7935| -------- | ------------------------------------------ |
7936| 5400102  | Operation not allowed. Returned by callback. |
7937| 5400106  | Unsupported format. Returned by callback.  |
7938
7939**Example**
7940
7941```ts
7942import { BusinessError } from '@kit.BasicServicesKit';
7943import { image } from '@kit.ImageKit';
7944
7945let avImageGenerator: media.AVImageGenerator | undefined = undefined;
7946let pixel_map : image.PixelMap | undefined = undefined;
7947
7948// Initialize input parameters.
7949let timeUs: number = 0;
7950
7951let queryOption: media.AVImageQueryOptions = media.AVImageQueryOptions.AV_IMAGE_QUERY_NEXT_SYNC;
7952
7953let param: media.PixelMapParams = {
7954  width : 300,
7955  height : 300,
7956};
7957
7958// Obtain the thumbnail.
7959media.createAVImageGenerator((err: BusinessError, generator: media.AVImageGenerator) => {
7960  if(generator != null){
7961    avImageGenerator = generator;
7962    console.info(`Succeeded in creating AVImageGenerator`);
7963    avImageGenerator.fetchFrameByTime(timeUs, queryOption, param, (error: BusinessError, pixelMap) => {
7964      if (error) {
7965        console.error(`Failed to fetch FrameByTime, err = ${JSON.stringify(error)}`);
7966        return;
7967      }
7968      pixel_map = pixelMap;
7969    });
7970  } else {
7971    console.error(`Failed to creat AVImageGenerator, error message:${err.message}`);
7972  };
7973});
7974```
7975
7976### fetchFrameByTime<sup>12+</sup>
7977
7978fetchFrameByTime(timeUs: number, options: AVImageQueryOptions, param: PixelMapParams): Promise<image.PixelMap>
7979
7980Obtains a video thumbnail. This API uses a promise to return the result.
7981
7982**System capability**: SystemCapability.Multimedia.Media.AVImageGenerator
7983
7984**Parameters**
7985
7986| Name  | Type                                        | Mandatory| Description                               |
7987| -------- | -------------------------------------------- | ---- | ----------------------------------- |
7988| timeUs | number                   | Yes  | Time of the video for which a thumbnail is to be obtained, in μs.|
7989| options | [AVImageQueryOptions](#avimagequeryoptions12)     | Yes  | Relationship between the time passed in and the video frame.|
7990| param | [PixelMapParams](#pixelmapparams12)    | Yes  | Format parameters of the thumbnail to be obtained.|
7991
7992**Return value**
7993
7994| Type          | Description                                    |
7995| -------------- | ---------------------------------------- |
7996| Promise\<[image.PixelMap](../apis-image-kit/arkts-apis-image-PixelMap.md)> | Promise used to return the video thumbnail.|
7997
7998**Error codes**
7999
8000For details about the error codes, see [Media Error Codes](errorcode-media.md).
8001
8002| ID| Error Message                                 |
8003| -------- | ----------------------------------------- |
8004| 5400102  | Operation not allowed. Returned by promise. |
8005| 5400106  | Unsupported format. Returned by promise.  |
8006
8007**Example**
8008
8009```ts
8010import { BusinessError } from '@kit.BasicServicesKit';
8011import { image } from '@kit.ImageKit';
8012
8013let avImageGenerator: media.AVImageGenerator | undefined = undefined;
8014let pixel_map : image.PixelMap | undefined = undefined;
8015
8016// Initialize input parameters.
8017let timeUs: number = 0;
8018
8019let queryOption: media.AVImageQueryOptions = media.AVImageQueryOptions.AV_IMAGE_QUERY_NEXT_SYNC;
8020
8021let param: media.PixelMapParams = {
8022  width : 300,
8023  height : 300,
8024};
8025
8026// Obtain the thumbnail.
8027media.createAVImageGenerator((err: BusinessError, generator: media.AVImageGenerator) => {
8028  if(generator != null){
8029    avImageGenerator = generator;
8030    console.info(`Succeeded in creating AVImageGenerator`);
8031    avImageGenerator.fetchFrameByTime(timeUs, queryOption, param).then((pixelMap: image.PixelMap) => {
8032      pixel_map = pixelMap;
8033    }).catch((error: BusinessError) => {
8034      console.error(`Failed to fetch FrameByTime, error message:${error.message}`);
8035    });
8036  } else {
8037    console.error(`Failed to creat AVImageGenerator, error message:${err.message}`);
8038  };
8039});
8040```
8041
8042### fetchScaledFrameByTime<sup>20+</sup>
8043
8044fetchScaledFrameByTime(timeUs: number, queryMode: AVImageQueryOptions, outputSize?: OutputSize):Promise\<image.PixelMap\>
8045
8046Fetches a scaled thumbnail from the video at a particular timestamp. This API uses a promise to return the result.
8047
8048**System capability**: SystemCapability.Multimedia.Media.AVImageGenerator
8049
8050**Parameters**
8051
8052| Name    | Type                                         | Mandatory| Description                                                |
8053| ---------- | --------------------------------------------- | ---- | ---------------------------------------------------- |
8054| timeUs     | number                                        | Yes  | Timestamp, in microseconds (μs), at which the thumbnail is to be fetched from the video.|
8055| queryMode  | [AVImageQueryOptions](#avimagequeryoptions12) | Yes  | Relationship between the thumbnail timestamp in and the video frame.          |
8056| outputSize | [OutputSize ](#outputsize20)                  | No  | Output size of the thumbnail. By default, the original image size is used.              |
8057
8058**Return value**
8059
8060| Type                                                        | Description                             |
8061| ------------------------------------------------------------ | --------------------------------- |
8062| Promise\<[image.PixelMap](../apis-image-kit/arkts-apis-image-PixelMap.md)> | Promise used to return the video thumbnail.|
8063
8064**Error codes**
8065
8066For details about the error codes, see [Media Error Codes](errorcode-media.md).
8067
8068| ID| Error Message                                   |
8069| -------- | ------------------------------------------- |
8070| 5400102  | Operation not allowed. Returned by promise. |
8071| 5400106  | Unsupported format. Returned by promise.    |
8072
8073**Example**
8074
8075```ts
8076import { BusinessError } from '@kit.BasicServicesKit';
8077import { image } from '@kit.ImageKit';
8078import { media } from '@kit.MediaKit';
8079let avImageGenerator: media.AVImageGenerator | undefined = undefined;
8080let pixel_map : image.PixelMap | undefined = undefined;
8081// Initialize input parameters.
8082let timeUs: number = 0;
8083let queryOption: media.AVImageQueryOptions = media.AVImageQueryOptions.AV_IMAGE_QUERY_NEXT_SYNC;
8084let outputSize: media.OutputSize = {
8085  width : 300,
8086  height : 300,
8087};
8088// Obtain the thumbnail.
8089media.createAVImageGenerator((err: BusinessError, generator: media.AVImageGenerator) => {
8090  if(generator != null){
8091    avImageGenerator = generator;
8092    console.info(`Succeeded in creating AVImageGenerator`);
8093    avImageGenerator.fetchScaledFrameByTime(timeUs, queryOption, outputSize).then((pixelMap: image.PixelMap) => {
8094      pixel_map = pixelMap;
8095    }).catch((error: BusinessError) => {
8096      console.error(`Failed to fetch ScaledFrameByTime, error message:${error.message}`);
8097    });
8098  } else {
8099    console.error(`Failed to creat AVImageGenerator, error message:${err.message}`);
8100  };
8101});
8102```
8103
8104### release<sup>12+</sup>
8105
8106release(callback: AsyncCallback\<void>): void
8107
8108Releases this AVMetadataExtractor instance. This API uses an asynchronous callback to return the result.
8109
8110**System capability**: SystemCapability.Multimedia.Media.AVImageGenerator
8111
8112**Parameters**
8113
8114| Name  | Type                                        | Mandatory| Description                               |
8115| -------- | -------------------------------------------- | ---- | ----------------------------------- |
8116| callback | AsyncCallback\<void>                   | Yes  | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.|
8117
8118**Error codes**
8119
8120For details about the error codes, see [Media Error Codes](errorcode-media.md).
8121
8122| ID| Error Message                                  |
8123| -------- | ------------------------------------------ |
8124| 5400102  | Operation not allowed. Returned by callback. |
8125
8126**Example**
8127
8128```ts
8129import { BusinessError } from '@kit.BasicServicesKit';
8130
8131let avImageGenerator: media.AVImageGenerator | undefined = undefined;
8132
8133// Release the resources.
8134media.createAVImageGenerator((err: BusinessError, generator: media.AVImageGenerator) => {
8135  if(generator != null){
8136    avImageGenerator = generator;
8137    console.info(`Succeeded in creating AVImageGenerator`);
8138    avImageGenerator.release((error: BusinessError) => {
8139      if (error) {
8140        console.error(`Failed to release, err = ${JSON.stringify(error)}`);
8141        return;
8142      }
8143      console.info(`Succeeded in releasing`);
8144    });
8145  } else {
8146    console.error(`Failed to creat AVImageGenerator, error message:${err.message}`);
8147  };
8148});
8149```
8150
8151### release<sup>12+</sup>
8152
8153release(): Promise\<void>
8154
8155Releases this AVMetadataExtractor instance. This API uses a promise to return the result.
8156
8157**System capability**: SystemCapability.Multimedia.Media.AVImageGenerator
8158
8159**Return value**
8160
8161| Type          | Description                                    |
8162| -------------- | ---------------------------------------- |
8163| Promise\<void> | Promise that returns no value.|
8164
8165**Error codes**
8166
8167For details about the error codes, see [Media Error Codes](errorcode-media.md).
8168
8169| ID| Error Message                                 |
8170| -------- | ----------------------------------------- |
8171| 5400102  | Operation not allowed. Returned by promise. |
8172
8173**Example**
8174
8175```ts
8176import { BusinessError } from '@kit.BasicServicesKit';
8177
8178let avImageGenerator: media.AVImageGenerator | undefined = undefined;
8179
8180// Release the instance.
8181media.createAVImageGenerator((err: BusinessError, generator: media.AVImageGenerator) => {
8182  if(generator != null){
8183    avImageGenerator = generator;
8184    console.info(`Succeeded in creating AVImageGenerator`);
8185    avImageGenerator.release().then(() => {
8186      console.info(`Succeeded in releasing.`);
8187    }).catch((error: BusinessError) => {
8188      console.error(`Failed to release, error message:${error.message}`);
8189    });
8190  } else {
8191    console.error(`Failed to creat AVImageGenerator, error message:${err.message}`);
8192  };
8193});
8194```
8195
8196## AVImageQueryOptions<sup>12+</sup>
8197
8198Enumerates the relationship between the video frame and the time at which the video thumbnail is obtained.
8199
8200The 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.
8201
8202**System capability**: SystemCapability.Multimedia.Media.AVImageGenerator
8203
8204| Name                    | Value             | Description                                                        |
8205| ------------------------ | --------------- | ------------------------------------------------------------ |
8206| AV_IMAGE_QUERY_NEXT_SYNC       | 0   | The key frame at or next to the specified time is selected.                      |
8207| AV_IMAGE_QUERY_PREVIOUS_SYNC        | 1    | The key frame at or prior to the specified time is selected.|
8208| AV_IMAGE_QUERY_CLOSEST_SYNC        | 2    | The key frame closest to the specified time is selected.                |
8209| AV_IMAGE_QUERY_CLOSEST             | 3    | The frame (not necessarily a key frame) closest to the specified time is selected.|
8210
8211## PixelMapParams<sup>12+</sup>
8212
8213Defines the format parameters of the video thumbnail to be obtained.
8214
8215**System capability**: SystemCapability.Multimedia.Media.AVImageGenerator
8216
8217| Name  | Type  | Readable| Writable| Description                                                                           |
8218|--------|--------|------|------|---------------------------------------------------------------------------------|
8219| 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.|
8220| 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.|
8221
8222## OutputSize<sup>20+</sup>
8223
8224Describes the output size of the video thumbnail fetched.
8225
8226**System capability**: SystemCapability.Multimedia.Media.AVImageGenerator
8227
8228| Name  | Type  | Read-Only| Optional| Description                                                        |
8229| ------ | ------ | ---- | ---- | ------------------------------------------------------------ |
8230| width  | number | No  | Yes  | Width of the thumbnail.<br>- If this parameter is set to a value less than 0, the width will be the original video width.<br>- If the value is **0** or is not assigned, the scaling ratio is the same as the height ratio.|
8231| height | number | No  | Yes  | Height of the thumbnail.<br>- If this parameter is set to a value less than 0, the height will be the original video height.<br>- If the value is **0** or is not assigned, the scaling ratio is the same as the width ratio.|
8232
8233## media.createMediaSourceWithUrl<sup>12+</sup>
8234
8235createMediaSourceWithUrl(url: string, headers?: Record\<string, string>): MediaSource
8236
8237Creates a media source for streaming media to be pre-downloaded.
8238
8239**Atomic service API**: This API can be used in atomic services since API version 13.
8240
8241**System capability**: SystemCapability.Multimedia.Media.Core
8242
8243**Parameters**
8244
8245| Name  | Type    | Mandatory| Description                |
8246| -------- | -------- | ---- | -------------------- |
8247| 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. |
8248| headers | Record\<string, string> | No  | HTTP header customized for streaming media pre-download.|
8249
8250**Return value**
8251
8252| Type          | Description                                      |
8253| -------------- | ------------------------------------------ |
8254| [MediaSource](#mediasource12) | MediaSource instance.|
8255
8256**Error codes**
8257
8258For details about the error codes, see [Media Error Codes](errorcode-media.md).
8259
8260| ID| Error Message                                 |
8261| -------- | ----------------------------------------- |
8262| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed.      |
8263| 5400101  | No memory.  |
8264
8265**Example 1**
8266
8267```ts
8268let headers: Record<string, string> = {"User-Agent" : "User-Agent-Value"};
8269let mediaSource : media.MediaSource = media.createMediaSourceWithUrl("http://xxx",  headers);
8270```
8271
8272**Example 2**
8273
8274<!--code_no_check-->
8275```ts
8276import { common } from '@kit.AbilityKit';
8277import { resourceManager } from '@kit.LocalizationKit';
8278
8279private context: Context | undefined;
8280constructor(context: Context) {
8281  this.context = context; // this.getUIContext().getHostContext();
8282}
8283let mgr = this.context.resourceManager;
8284let fileDescriptor = await mgr.getRawFd("xxx.m3u8");
8285
8286let fd:string = fileDescriptor.fd.toString();
8287let offset:string = fileDescriptor.offset.toString();
8288let length:string = fileDescriptor.length.toString();
8289let fdUrl:string = "fd://" + fd + "?offset=" + offset + "&size=" + length;
8290
8291let headers: Record<string, string> = {"User-Agent" : "User-Agent-Value"};
8292let mediaSource : media.MediaSource = media.createMediaSourceWithUrl(fdUrl,  headers);
8293
8294let mimeType : media.AVMimeTypes = media.AVMimeTypes.APPLICATION_M3U8;
8295mediaSource.setMimeType(mimeType);
8296
8297```
8298## media.createMediaSourceWithStreamData<sup>19+</sup>
8299
8300createMediaSourceWithStreamData(streams: Array\<MediaStream>): MediaSource
8301
8302Creates a multi-bitrate media source for streaming media. Currently, only the HTTP-FLV multi-bitrate media source is supported.
8303
8304**Atomic service API**: This API can be used in atomic services since API version 19.
8305
8306**System capability**: SystemCapability.Multimedia.Media.Core
8307
8308**Parameters**
8309
8310| Name | Type                                | Mandatory| Description                                                 |
8311| ------- | ------------------------------------ | ---- | ----------------------------------------------------- |
8312| streams | Array<[MediaStream](#mediastream19)> | Yes| Array of MediaStream objects. The supported streaming media format is HTTP-FLV.|
8313
8314**Return value**
8315
8316| Type                         | Description               |
8317| ----------------------------- | ------------------- |
8318| [MediaSource](#mediasource12) | MediaSource instance.|
8319
8320**Example 1**
8321
8322```ts
8323let streams : Array<media.MediaStream> = [];
8324streams.push({url: "http://xxx/480p.flv", width: 854, height: 480, bitrate: 800000});
8325streams.push({url: "http://xxx/720p.flv", width: 1280, height: 720, bitrate: 2000000});
8326streams.push({url: "http://xxx/1080p.flv", width: 1280, height: 720, bitrate: 2000000});
8327let mediaSource : media.MediaSource = media.createMediaSourceWithStreamData(streams);
8328```
8329
8330## MediaStream<sup>19+</sup>
8331
8332Defines the media stream data information.
8333
8334**Atomic service API**: This API can be used in atomic services since API version 19.
8335
8336**System capability**: SystemCapability.Multimedia.Media.Core
8337
8338| Name | Type  | Read-Only| Optional| Description                                                        |
8339| ------- | ------ | ---- | ---- | ------------------------------------------------------------ |
8340| url     | string | No  | No  | URL of the media resource. Only HTTP and HTTPS are supported.                                                |
8341| width   | number | No  | No  | Video width of the media resource. If the video width is unknown, set it to **0**. In this case, [PlaybackStrategy](#playbackstrategy12) cannot be used for optimal matching.|
8342| height  | number | No  | No  | Video height of the media resource. If the video width is unknown, set it to **0**. In this case, [PlaybackStrategy](#playbackstrategy12) cannot be used for optimal matching.|
8343| bitrate | number | No  | No  | Bit rate of media resources, in bit/s.                                       |
8344
8345## MediaSource<sup>12+</sup>
8346
8347Defines the media data information, which is from [createMediaSourceWithUrl](#mediacreatemediasourcewithurl12).
8348
8349**System capability**: SystemCapability.Multimedia.Media.Core
8350
8351### setMimeType<sup>12+</sup>
8352
8353setMimeType(mimeType: AVMimeTypes): void
8354
8355Sets the MIME type to help the player process extended media sources.
8356
8357**Atomic service API**: This API can be used in atomic services since API version 12.
8358
8359**System capability**: SystemCapability.Multimedia.Media.Core
8360
8361**Parameters**
8362
8363| Name  | Type    | Mandatory| Description                |
8364| -------- | -------- | ---- | -------------------- |
8365| mimeType | [AVMimeTypes](#mediasource12) | Yes  | MIME type.|
8366
8367### setMediaResourceLoaderDelegate<sup>18+</sup>
8368
8369setMediaResourceLoaderDelegate(resourceLoader: MediaSourceLoader): void
8370
8371Sets a MediaSourceLoader object, which is used to help the player request media data.
8372
8373**Atomic service API**: This API can be used in atomic services since API version 18.
8374
8375**System capability**: SystemCapability.Multimedia.Media.Core
8376
8377**Parameters**
8378
8379| Name  | Type    | Mandatory| Description                |
8380| -------- | -------- | ---- | -------------------- |
8381| resourceLoader | [MediaSourceLoader](#mediasourceloader18) | Yes  | MediaSourceLoader object used to obtain media data for the player.|
8382
8383**Example**
8384
8385```ts
8386import HashMap from '@ohos.util.HashMap';
8387
8388let headers: Record<string, string> = {"User-Agent" : "User-Agent-Value"};
8389let mediaSource : media.MediaSource = media.createMediaSourceWithUrl("http://xxx",  headers);
8390let uuid: number = 1;
8391let requests: HashMap<number, media.MediaSourceLoadingRequest> = new HashMap();
8392
8393let sourceOpenCallback: media.SourceOpenCallback = (request: media.MediaSourceLoadingRequest) => {
8394  console.log(`Opening resource: ${request.url}`);
8395  // Open the resource and return a unique handle, ensuring the mapping between the UUID and request.
8396  uuid += 1;
8397  requests.set(uuid, request);
8398  return uuid;
8399};
8400
8401let sourceReadCallback: media.SourceReadCallback = (uuid: number, requestedOffset: number, requestedLength: number) => {
8402  console.log(`Reading resource with handle ${uuid}, offset: ${requestedOffset}, length: ${requestedLength}`);
8403  // Check whether the UUID is valid and store the read request. Avoid blocking the request while pushing data and header information.
8404};
8405
8406let sourceCloseCallback: media.SourceCloseCallback = (uuid: number) => {
8407  console.log(`Closing resource with handle ${uuid}`);
8408  // Clear resources related to the current UUID.
8409  requests.remove(uuid);
8410};
8411
8412// Implemented by applications as required.
8413let resourceLoader: media.MediaSourceLoader = {
8414  open: sourceOpenCallback,
8415  read: sourceReadCallback,
8416  close: sourceCloseCallback
8417};
8418
8419mediaSource.setMediaResourceLoaderDelegate(resourceLoader);
8420```
8421
8422## SourceOpenCallback<sup>18+</sup>
8423
8424type SourceOpenCallback = (request: MediaSourceLoadingRequest) => number
8425
8426This callback function is implemented by applications to handle resource open requests and return a unique handle for the opened resource.
8427
8428> **NOTE**
8429>
8430> The client must return the handle immediately after processing the request.
8431
8432**Atomic service API**: This API can be used in atomic services since API version 18.
8433
8434**System capability**: SystemCapability.Multimedia.Media.Core
8435
8436**Parameters**
8437
8438| Name  | Type    | Mandatory| Description                |
8439| -------- | -------- | ---- | -------------------- |
8440| request | [MediaSourceLoadingRequest](#mediasourceloadingrequest18) | Yes | 	Parameters for the resource open request, including detailed information about the requested resource and the data push method.|
8441
8442**Return value**
8443
8444| Type  | Description                |
8445| -------- | -------------------- |
8446| 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.|
8447
8448**Example**
8449
8450```ts
8451import HashMap from '@ohos.util.HashMap';
8452
8453let uuid: number = 1;
8454let requests: HashMap<number, media.MediaSourceLoadingRequest> = new HashMap();
8455
8456let sourceOpenCallback: media.SourceOpenCallback = (request: media.MediaSourceLoadingRequest) => {
8457  console.log(`Opening resource: ${request.url}`);
8458  // Open the resource and return a unique handle, ensuring the mapping between the UUID and request.
8459  uuid += 1;
8460  requests.set(uuid, request);
8461  return uuid;
8462};
8463```
8464
8465## SourceReadCallback<sup>18+</sup>
8466
8467type SourceReadCallback = (uuid: number, requestedOffset: number, requestedLength: number) => void
8468
8469This 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.
8470
8471> **NOTE**
8472>
8473> The client must return the handle immediately after processing the request.
8474
8475**Atomic service API**: This API can be used in atomic services since API version 18.
8476
8477**System capability**: SystemCapability.Multimedia.Media.Core
8478
8479**Parameters**
8480
8481| Name  | Type    | Mandatory| Description                |
8482| -------- | -------- | ---- | -------------------- |
8483| uuid | number | Yes | 	ID for the resource handle.|
8484| requestedOffset | number | Yes | 	Offset of the current media data relative to the start of the resource.|
8485| 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.|
8486
8487**Example**
8488
8489```ts
8490let sourceReadCallback: media.SourceReadCallback = (uuid: number, requestedOffset: number, requestedLength: number) => {
8491  console.log(`Reading resource with handle ${uuid}, offset: ${requestedOffset}, length: ${requestedLength}`);
8492  // Check whether the UUID is valid and store the read request. Avoid blocking the request while pushing data and header information.
8493};
8494```
8495
8496## SourceCloseCallback<sup>18+</sup>
8497
8498type SourceCloseCallback = (uuid: number) => void
8499
8500This callback function is implemented by applications to release related resources.
8501
8502> **NOTE**
8503>
8504> The client must return the handle immediately after processing the request.
8505
8506**Atomic service API**: This API can be used in atomic services since API version 18.
8507
8508**System capability**: SystemCapability.Multimedia.Media.Core
8509
8510**Parameters**
8511
8512| Name  | Type    | Mandatory| Description                |
8513| -------- | -------- | ---- | -------------------- |
8514| uuid      | number | Yes | 	ID for the resource handle.|
8515
8516**Example**
8517
8518```ts
8519import HashMap from '@ohos.util.HashMap';
8520
8521let requests: HashMap<number, media.MediaSourceLoadingRequest> = new HashMap();
8522
8523let sourceCloseCallback: media.SourceCloseCallback = (uuid: number) => {
8524  console.log(`Closing resource with handle ${uuid}`);
8525  // Clear resources related to the current UUID.
8526  requests.remove(uuid);
8527};
8528```
8529
8530## MediaSourceLoader<sup>18+</sup>
8531
8532Defines a media data loader, which needs to be implemented by applications.
8533
8534**Atomic service API**: This API can be used in atomic services since API version 18.
8535
8536**System capability**: SystemCapability.Multimedia.Media.Core
8537
8538| Name  | Type    | Mandatory| Description                |
8539| -------- | -------- | ---- | -------------------- |
8540| open | [SourceOpenCallback](#sourceopencallback18) | Yes | Callback function implemented by applications to handle resource open requests.|
8541| read | [SourceReadCallback](#sourcereadcallback18) | Yes | Callback function implemented by applications to handle resource read requests.|
8542| close | [SourceCloseCallback](#sourceclosecallback18) | Yes | Callback function implemented by applications to handle resource close requests.|
8543
8544**Example**
8545
8546```ts
8547import HashMap from '@ohos.util.HashMap';
8548
8549let headers: Record<string, string> = {"User-Agent" : "User-Agent-Value"};
8550let mediaSource : media.MediaSource = media.createMediaSourceWithUrl("http://xxx",  headers);
8551let uuid: number = 1;
8552let requests: HashMap<number, media.MediaSourceLoadingRequest> = new HashMap();
8553let mediaSourceLoader: media.MediaSourceLoader = {
8554  open: (request: media.MediaSourceLoadingRequest) => {
8555    console.log(`Opening resource: ${request.url}`);
8556    // Open the resource and return a unique handle, ensuring the mapping between the UUID and request.
8557    uuid += 1;
8558    requests.set(uuid, request);
8559    return uuid;
8560  },
8561  read: (uuid: number, requestedOffset: number, requestedLength: number) => {
8562    console.log(`Reading resource with handle ${uuid}, offset: ${requestedOffset}, length: ${requestedLength}`);
8563    // Check whether the UUID is valid and store the read request. Avoid blocking the request while pushing data and header information.
8564  },
8565  close: (uuid: number) => {
8566    console.log(`Closing resource with handle ${uuid}`);
8567    // Clear resources related to the current UUID.
8568    requests.remove(uuid);
8569  }
8570};
8571
8572mediaSource.setMediaResourceLoaderDelegate(mediaSourceLoader);
8573let playStrategy : media.PlaybackStrategy = {
8574  preferredBufferDuration: 20,
8575};
8576
8577async function setupPlayer() {
8578  let player = await media.createAVPlayer();
8579  player.setMediaSource(mediaSource, playStrategy);
8580}
8581```
8582
8583## MediaSourceLoadingRequest<sup>18+</sup>
8584
8585Defines 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.
8586
8587**Atomic service API**: This API can be used in atomic services since API version 18.
8588
8589### Properties
8590
8591**System capability**: SystemCapability.Multimedia.Media.Core
8592
8593| Name  | Type   | Read-Only  | Optional  | Description               |
8594| --------------------------------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ |
8595| url        | string                        | No  | No  | Resource URL, which is the path to the resource that the application needs to open.|
8596| header     | 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.|
8597
8598### respondData<sup>18+</sup>
8599
8600respondData(uuid: number, offset: number, buffer: ArrayBuffer): number
8601
8602Sends data to the player.
8603
8604**Atomic service API**: This API can be used in atomic services since API version 18.
8605
8606**System capability**: SystemCapability.Multimedia.Media.Core
8607
8608**Parameters**
8609
8610| Name  | Type    | Mandatory| Description                |
8611| -------- | -------- | ---- | -------------------- |
8612| uuid | number | Yes | 	ID for the resource handle.|
8613| offset | number | Yes | 	Offset of the current media data relative to the start of the resource.|
8614| 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.|
8615
8616**Return value**
8617
8618| Type          | Description                               |
8619| -------------- | ----------------------------------- |
8620| 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.|
8621
8622**Example**
8623
8624```ts
8625import HashMap from '@ohos.util.HashMap';
8626let requests: HashMap<number, media.MediaSourceLoadingRequest> = new HashMap();
8627let uuid = 1;
8628
8629let request = requests.get(uuid);
8630let offset = 0; // Offset of the current media data relative to the start of the resource.
8631let buf = new ArrayBuffer(0); // Data defined by the application and pushed to the player.
8632let num = request.respondData(uuid, offset, buf);
8633```
8634
8635### respondHeader<sup>18+</sup>
8636
8637respondHeader(uuid: number, header?: Record<string, string>, redirectUrl?: string): void
8638
8639Sends response header information to the player. This API must be called before the first call to [respondData](#responddata18).
8640
8641**Atomic service API**: This API can be used in atomic services since API version 18.
8642
8643**System capability**: SystemCapability.Multimedia.Media.Core
8644
8645**Parameters**
8646
8647| Name  | Type    | Mandatory| Description                |
8648| -------- | -------- | ---- | -------------------- |
8649| uuid | number | Yes | 	ID for the resource handle.|
8650| 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.|
8651| redirectUrl | string | No | 	Redirect URL in the HTTP response.|
8652
8653**Example**
8654
8655```ts
8656import HashMap from '@ohos.util.HashMap';
8657let requests: HashMap<number, media.MediaSourceLoadingRequest> = new HashMap();
8658let uuid = 1;
8659
8660// The application fills this in as needed.
8661let header:Record<string, string> = {
8662  'Transfer-Encoding':'xxx',
8663  'Location' : 'xxx',
8664  'Content-Type' : 'xxx',
8665  'Content-Range' : 'xxx',
8666  'Content-Encode' : 'xxx',
8667  'Accept-Ranges' : 'xxx',
8668  'content-length' : 'xxx'
8669};
8670let request = requests.get(uuid);
8671request.respondHeader(uuid, header);
8672```
8673
8674### finishLoading<sup>18+</sup>
8675
8676finishLoading(uuid: number, state: LoadingRequestError): void
8677
8678Notifies 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.
8679
8680**Atomic service API**: This API can be used in atomic services since API version 18.
8681
8682**System capability**: SystemCapability.Multimedia.Media.Core
8683
8684**Parameters**
8685
8686| Name  | Type    | Mandatory| Description                |
8687| -------- | -------- | ---- | -------------------- |
8688| uuid | number | Yes | 	ID for the resource handle.|
8689| state  | [LoadingRequestError](#loadingrequesterror18) | Yes | Request status.|
8690
8691**Example**
8692
8693```ts
8694import HashMap from '@ohos.util.HashMap';
8695let requests: HashMap<number, media.MediaSourceLoadingRequest> = new HashMap();
8696let uuid = 1;
8697
8698let request = requests.get(uuid);
8699let loadingError = media.LoadingRequestError.LOADING_ERROR_SUCCESS;
8700request.finishLoading(uuid, loadingError);
8701```
8702
8703## LoadingRequestError<sup>18+</sup>
8704
8705Enumerates the reasons for data loading status changes.
8706
8707**Atomic service API**: This API can be used in atomic services since API version 18.
8708
8709**System capability**: SystemCapability.Multimedia.Media.Core
8710
8711| Name                | Value  | Description                          |
8712| -------------------- | ---- | ------------------------------ |
8713| LOADING_ERROR_SUCCESS | 0    | Returned by the client to indicate that the end of the resource.|
8714| LOADING_ERROR_NOT_READY | 1    | Returned by the client to indicate that the resource is not ready for access.|
8715| LOADING_ERROR_NO_RESOURCE | 2    | Returned by the client to indicate that the requested resource URL does not exist.|
8716| LOADING_ERROR_INVAID_HANDLE | 3    | Returned by the client to indicate that the ID of the requested resource handle (specified by **uuid**) is invalid.|
8717| LOADING_ERROR_ACCESS_DENIED | 4    | Returned by the client to indicate that the client does not have permission to request the resource.|
8718| LOADING_ERROR_ACCESS_TIMEOUT | 5    | Returned by the client to indicate that the access to the resource times out.|
8719| LOADING_ERROR_AUTHORIZE_FAILED | 6    | Returned by the client to indicate that authorization fails.|
8720
8721## AVMimeTypes<sup>12+</sup>
8722
8723Enumerates the MIME type, which is set by using [setMimeType](#setmimetype12).
8724
8725**Atomic service API**: This API can be used in atomic services since API version 12.
8726
8727**System capability**: SystemCapability.Multimedia.Media.Core
8728
8729
8730| Name      | Value  | Description                                                        |
8731| ---------- | ---- | ------------------------------------------------------------ |
8732| APPLICATION_M3U8       | application/m3u8    | Local M3U8 file.|
8733
8734
8735## PlaybackStrategy<sup>12+</sup>
8736
8737Describes the playback strategy.
8738
8739**System capability**: SystemCapability.Multimedia.Media.Core
8740
8741| Name | Type    | Mandatory| Description                |
8742| -------- | -------- | ---- | -------------------- |
8743| 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.|
8744| 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.|
8745| preferredBufferDuration | number | No | Preferred buffer duration, in seconds. The value ranges from 1 to 20.<br>For details, see [Minimizing Stuttering in Online Video Playback](https://developer.huawei.com/consumer/en/doc/best-practices/bpta-online-video-playback-lags-practice).<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
8746| 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.|
8747| 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.|
8748| 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.|
8749| mutedMediaType | [MediaType](#mediatype8) | No| Media type for muted playback. Only **MediaType.MEDIA_TYPE_AUD** can be set.|
8750| 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.|
8751| 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.|
8752| 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.|
8753| 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. The [speedDone](#onspeeddone9) event is invoked with a value of 100, indicating that smart frame catching has started successfully. 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.|
8754
8755## AVScreenCaptureRecordPreset<sup>12+</sup>
8756
8757Enumerates the encoding and container formats used during screen capture.
8758
8759**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture
8760
8761| Name                             | Value  | Description                                        |
8762| --------------------------------- | ---- | -------------------------------------------- |
8763| SCREEN_RECORD_PRESET_H264_AAC_MP4 | 0    | The H.264 video encoding format, AAC audio encoding format, and MP4 container format are used.|
8764| SCREEN_RECORD_PRESET_H265_AAC_MP4 | 1    | The H.265 video encoding format, AAC audio encoding format, and MP4 container format are used.|
8765
8766## AVScreenCaptureStateCode<sup>12+</sup>
8767
8768Enumerates the screen capture states used in callbacks.
8769
8770**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture
8771
8772| Name                                    | Value  | Description                    |
8773| ---------------------------------------- | ---- | ------------------------ |
8774| SCREENCAPTURE_STATE_STARTED              | 0    | Screen capture is started.            |
8775| SCREENCAPTURE_STATE_CANCELED             | 1    | Screen capture is canceled.            |
8776| SCREENCAPTURE_STATE_STOPPED_BY_USER      | 2    | Screen capture is manually stopped by the user.    |
8777| SCREENCAPTURE_STATE_INTERRUPTED_BY_OTHER | 3    | Screen capture is interrupted by another screen capture.    |
8778| SCREENCAPTURE_STATE_STOPPED_BY_CALL      | 4    | Screen capture is interrupted by an incoming call.        |
8779| SCREENCAPTURE_STATE_MIC_UNAVAILABLE      | 5    | The microphone is unavailable during screen capture.|
8780| SCREENCAPTURE_STATE_MIC_MUTED_BY_USER    | 6    | The microphone is muted by the user.      |
8781| SCREENCAPTURE_STATE_MIC_UNMUTED_BY_USER  | 7    | The microphone is unmuted by the user.      |
8782| SCREENCAPTURE_STATE_ENTER_PRIVATE_SCENE  | 8    | The system enters a privacy page during screen capture.      |
8783| SCREENCAPTURE_STATE_EXIT_PRIVATE_SCENE   | 9    | The system exits a privacy page during screen capture.      |
8784| SCREENCAPTURE_STATE_STOPPED_BY_USER_SWITCHES   | 10    | Screen capture is interrupted by system user switchover.      |
8785
8786## AVScreenCaptureFillMode<sup>18+</sup>
8787
8788Enumerates the video fill modes during screen capture.
8789
8790**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture
8791
8792| Name                             | Value  | Description                                        |
8793| --------------------------------- | ---- | -------------------------------------------- |
8794| PRESERVE_ASPECT_RATIO | 0    | Keeps the original aspect ratio, matching the aspect ratio of the physical screen.|
8795| SCALE_TO_FILL | 1    | Stretches the image to fit the specified dimensions.|
8796
8797## AVScreenCaptureStrategy<sup>20+</sup>
8798
8799Describes the screen capture strategy.
8800
8801**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture
8802
8803| Name                 | Type   | Mandatory| Description                |
8804| --------------------- | ------- | --- | -------------------- |
8805| keepCaptureDuringCall | boolean | No | Whether to keep screen capture during a cellular call.|
8806
8807## AVScreenCaptureRecordConfig<sup>12+</sup>
8808
8809Defines the screen capture parameters.
8810
8811**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture
8812
8813| Name             | Type                                                        | Mandatory| Description                                                        |
8814| ----------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
8815| fd                | number                                                       | Yes  | FD of the file output.                                          |
8816| frameWidth        | number                                                       | No  | Video width, in px. The default value varies according to the display in use.|
8817| frameHeight       | number                                                       | No  | Video height, in px. The default value varies according to the display in use.|
8818| videoBitrate      | number                                                       | No  | Video bit rate. The default value is **10000000**.                            |
8819| 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.|
8820| 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.|
8821| audioBitrate      | number                                                       | No  | Audio bit rate. This value is used for both internal capture and external capture (using microphones). The default value is **96000**.|
8822| preset            | [AVScreenCaptureRecordPreset](#avscreencapturerecordpreset12) | No  | Encoding and container format used. The default value is **SCREEN_RECORD_PRESET_H264_AAC_MP4**.|
8823| displayId<sup>15+</sup>            | number | No  | ID of the display used for screen capture. By default, the main screen is captured.|
8824| fillMode<sup>18+</sup>            | [AVScreenCaptureFillMode](#avscreencapturefillmode18)| No  | Video fill mode during screen capture.|
8825| strategy<sup>20+</sup>            | [AVScreenCaptureStrategy](#avscreencapturestrategy20)| No  | Screen capture strategy.|
8826
8827## AVScreenCaptureRecorder<sup>12+</sup>
8828
8829Provides APIs to manage screen capture. Before calling any API in AVScreenCaptureRecorder, you must use [createAVScreenCaptureRecorder()](#mediacreateavscreencapturerecorder12) to create an AVScreenCaptureRecorder instance.
8830
8831### init<sup>12+</sup>
8832
8833init(config: AVScreenCaptureRecordConfig): Promise\<void>
8834
8835Initializes screen capture and sets screen capture parameters. This API uses a promise to return the result.
8836
8837**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture
8838
8839**Parameters**
8840
8841| Name| Type                                                        | Mandatory| Description                    |
8842| ------ | ------------------------------------------------------------ | ---- | ------------------------ |
8843| config | [AVScreenCaptureRecordConfig](#avscreencapturerecordconfig12) | Yes  | Screen capture parameters to set.|
8844
8845**Return value**
8846
8847| Type          | Description                               |
8848| -------------- | ----------------------------------- |
8849| Promise\<void> | Promise that returns no value.|
8850
8851**Error codes**
8852
8853| ID| Error Message                                      |
8854| -------- | ---------------------------------------------- |
8855| 401      | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. Return by promise. |
8856| 5400103  | IO error. Return by promise.                   |
8857| 5400105  | Service died. Return by promise.               |
8858
8859**Example**
8860
8861```ts
8862import { BusinessError } from '@kit.BasicServicesKit';
8863
8864let avCaptureConfig: media.AVScreenCaptureRecordConfig = {
8865    fd: 0, // Before passing in an FD to this parameter, the file must be created by the caller and granted with the write permissions.
8866    frameWidth: 640,
8867    frameHeight: 480
8868    // Add other parameters.
8869};
8870
8871avScreenCaptureRecorder.init(avCaptureConfig).then(() => {
8872    console.info('Succeeded in initing avScreenCaptureRecorder');
8873}).catch((err: BusinessError) => {
8874    console.info('Failed to init avScreenCaptureRecorder, error: ' + err.message);
8875});
8876```
8877
8878### startRecording<sup>12+</sup>
8879
8880startRecording(): Promise\<void>
8881
8882Starts screen capture. This API uses a promise to return the result.
8883
8884**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture
8885
8886**Return value**
8887
8888| Type          | Description                            |
8889| -------------- | -------------------------------- |
8890| Promise\<void> | Promise that returns no value.|
8891
8892**Error codes**
8893
8894| ID| Error Message                        |
8895| -------- | -------------------------------- |
8896| 5400103  | IO error. Return by promise.     |
8897| 5400105  | Service died. Return by promise. |
8898
8899**Example**
8900
8901```ts
8902import { BusinessError } from '@kit.BasicServicesKit';
8903
8904avScreenCaptureRecorder.startRecording().then(() => {
8905    console.info('Succeeded in starting avScreenCaptureRecorder');
8906}).catch((err: BusinessError) => {
8907    console.info('Failed to start avScreenCaptureRecorder, error: ' + err.message);
8908});
8909```
8910
8911### stopRecording<sup>12+</sup>
8912
8913stopRecording(): Promise\<void>
8914
8915Stops screen capture. This API uses a promise to return the result.
8916
8917**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture
8918
8919**Return value**
8920
8921| Type          | Description                             |
8922| -------------- | --------------------------------- |
8923| Promise\<void> | Promise that returns no value.|
8924
8925**Error codes**
8926
8927| ID| Error Message                        |
8928| -------- | -------------------------------- |
8929| 5400103  | IO error. Return by promise.     |
8930| 5400105  | Service died. Return by promise. |
8931
8932**Example**
8933
8934```ts
8935import { BusinessError } from '@kit.BasicServicesKit';
8936
8937avScreenCaptureRecorder.stopRecording().then(() => {
8938    console.info('Succeeded in stopping avScreenCaptureRecorder');
8939}).catch((err: BusinessError) => {
8940    console.info('Failed to stop avScreenCaptureRecorder, error: ' + err.message);
8941});
8942```
8943
8944### skipPrivacyMode<sup>12+</sup>
8945
8946skipPrivacyMode(windowIDs: Array\<number>): Promise\<void>
8947
8948During screen capture, the application can exempt its privacy windows from security purposes. This API uses a promise to return the result.
8949For example, if a user enters a password in this application during screen capture, the application will not display a black screen.
8950
8951**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture
8952
8953**Parameters**
8954
8955| Name| Type   | Mandatory| Description                                                     |
8956| ------ | ------- | ---- | --------------------------------------------------------- |
8957| 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/arkts-apis-window-Window.md#getwindowproperties9).|
8958
8959**Return value**
8960
8961| Type          | Description                            |
8962| -------------- | -------------------------------- |
8963| Promise\<void> | Promise used to return the window IDs.|
8964
8965**Error codes**
8966
8967| ID| Error Message                        |
8968| -------- | -------------------------------- |
8969| 5400103  | IO error. Return by promise.     |
8970| 5400105  | Service died. Return by promise. |
8971
8972**Example**
8973
8974```ts
8975import { BusinessError } from '@kit.BasicServicesKit';
8976
8977let windowIDs = [];
8978avScreenCaptureRecorder.skipPrivacyMode(windowIDs).then(() => {
8979    console.info('Succeeded in skipping privacy mode');
8980}).catch((err: BusinessError) => {
8981    console.info('Failed to skip privacy mode, error: ' + err.message);
8982});
8983```
8984
8985### setMicEnabled<sup>12+</sup>
8986
8987setMicEnabled(enable: boolean): Promise\<void>
8988
8989Enables or disables the microphone. This API uses a promise to return the result.
8990
8991**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture
8992
8993**Parameters**
8994
8995| Name| Type   | Mandatory| Description                                                     |
8996| ------ | ------- | ---- | --------------------------------------------------------- |
8997| enable | boolean | Yes  | Whether to enable or disable the microphone. The value **true** means to enable the microphone, and **false** means the opposite.|
8998
8999**Return value**
9000
9001| Type          | Description                                   |
9002| -------------- | --------------------------------------- |
9003| Promise\<void> | Promise that returns no value.|
9004
9005**Error codes**
9006
9007| ID| Error Message                        |
9008| -------- | -------------------------------- |
9009| 5400103  | IO error. Return by promise.     |
9010| 5400105  | Service died. Return by promise. |
9011
9012**Example**
9013
9014```ts
9015import { BusinessError } from '@kit.BasicServicesKit';
9016
9017avScreenCaptureRecorder.setMicEnabled(true).then(() => {
9018    console.info('Succeeded in setMicEnabled avScreenCaptureRecorder');
9019}).catch((err: BusinessError) => {
9020    console.info('Failed to setMicEnabled avScreenCaptureRecorder, error: ' + err.message);
9021});
9022```
9023
9024### release<sup>12+</sup>
9025
9026release(): Promise\<void>
9027
9028Releases this AVScreenCaptureRecorder instance. This API uses a promise to return the result.
9029
9030**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture
9031
9032**Return value**
9033
9034| Type          | Description                             |
9035| -------------- | --------------------------------- |
9036| Promise\<void> | Promise that returns no value.|
9037
9038**Error codes**
9039
9040| ID| Error Message                        |
9041| -------- | -------------------------------- |
9042| 5400103  | IO error. Return by promise.     |
9043| 5400105  | Service died. Return by promise. |
9044
9045**Example**
9046
9047```ts
9048import { BusinessError } from '@kit.BasicServicesKit';
9049
9050avScreenCaptureRecorder.release().then(() => {
9051    console.info('Succeeded in releasing avScreenCaptureRecorder');
9052}).catch((err: BusinessError) => {
9053    console.info('Faile to release avScreenCaptureRecorder, error: ' + err.message);
9054});
9055```
9056
9057### on('stateChange')<sup>12+</sup>
9058
9059on(type: 'stateChange', callback: Callback\<AVScreenCaptureStateCode>): void
9060
9061Subscribes 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.
9062
9063**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture
9064
9065**Parameters**
9066
9067| Name  | Type    | Mandatory| Description                                                        |
9068| -------- | -------- | ---- | ------------------------------------------------------------ |
9069| type     | string   | Yes  | Event type, which is **'stateChange'** in this case.           |
9070| callback | function | Yes  | Callback invoked when the event is triggered. [AVScreenCaptureStateCode](#avscreencapturestatecode12) indicates the new state.|
9071
9072**Example**
9073
9074```ts
9075avScreenCaptureRecorder.on('stateChange', (state: media.AVScreenCaptureStateCode) => {
9076    console.info('avScreenCaptureRecorder stateChange to ' + state);
9077});
9078```
9079
9080### on('error')<sup>12+</sup>
9081
9082on(type: 'error', callback: ErrorCallback): void
9083
9084Subscribes 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.
9085
9086**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture
9087
9088**Parameters**
9089
9090| Name  | Type         | Mandatory| Description                                   |
9091| -------- | ------------- | ---- | --------------------------------------- |
9092| type     | string        | Yes  | Event type, which is **'error'** in this case.|
9093| callback | [ErrorCallback](../apis-basic-services-kit/js-apis-base.md#errorcallback) | Yes  | Callback invoked when the event is triggered.                 |
9094
9095**Error codes**
9096
9097| ID| Error Message                        |
9098| -------- | -------------------------------- |
9099| 201      | permission denied.     |
9100| 5400103  | IO error. Return by ErrorCallback. |
9101| 5400105  | Service died. Return by ErrorCallback. |
9102
9103**Example**
9104
9105```ts
9106avScreenCaptureRecorder.on('error', (err: BusinessError) => {
9107    console.error('avScreenCaptureRecorder error:' + err.message);
9108});
9109```
9110
9111### off('stateChange')<sup>12+</sup>
9112
9113 off(type: 'stateChange', callback?: Callback\<AVScreenCaptureStateCode>): void
9114
9115Unsubscribes from screen capture state changes. You can specify a callback to cancel the specified subscription.
9116
9117**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture
9118
9119**Parameters**
9120
9121| Name  | Type    | Mandatory| Description                                                        |
9122| -------- | -------- | ---- | ------------------------------------------------------------ |
9123| type     | string   | Yes  | Event type, which is **'stateChange'** in this case.           |
9124| callback | function | No  | Callback used for unsubscription. [AVScreenCaptureStateCode](#avscreencapturestatecode12) indicates the new state. If this parameter is not specified, the last subscription is canceled.|
9125
9126**Example**
9127
9128```ts
9129avScreenCaptureRecorder.off('stateChange');
9130```
9131
9132### off('error')<sup>12+</sup>
9133
9134off(type: 'error', callback?: ErrorCallback): void
9135
9136Unsubscribes from AVScreenCaptureRecorder errors. You can specify a callback to cancel the specified subscription.
9137
9138**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture
9139
9140**Parameters**
9141
9142| Name  | Type    | Mandatory| Description                                                      |
9143| -------- | -------- | ---- | ---------------------------------------------------------- |
9144| type     | string   | Yes  | Event type, which is **'error'** in this case.               |
9145| 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.|
9146
9147**Example**
9148
9149```ts
9150avScreenCaptureRecorder.off('error');
9151```
9152
9153<!--no_check-->