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