• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.multimedia.media (Media) (System API)
2
3The multimedia subsystem provides a set of simple and easy-to-use APIs for you to access the system and use media resources.
4
5> **NOTE**
6>
7> - 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.
8> - This topic describes only system APIs provided by the module. For details about its public APIs, see [@ohos.multimedia.media (Media)](js-apis-media.md).
9
10## Modules to Import
11
12```ts
13import { media } from '@kit.MediaKit';
14```
15
16## media.createVideoRecorder<sup>9+</sup>
17
18createVideoRecorder(callback: AsyncCallback\<VideoRecorder>): void
19
20Creates a **VideoRecorder** instance. This API uses an asynchronous callback to return the result.
21
22Only one **VideoRecorder** instance can be created per device.
23
24**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
25
26**System API**: This is a system API.
27
28**Parameters**
29
30| Name  | Type                                           | Mandatory| Description                                                        |
31| -------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ |
32| callback | AsyncCallback<[VideoRecorder](#videorecorder9)> | Yes  | Callback used to return the result. If the operation is successful, a **VideoRecorder** instance is returned; otherwise, **null** is returned. The instance can be used to record video.|
33
34**Error codes**
35
36For details about the error codes, see [Media Error Codes](errorcode-media.md).
37
38| ID| Error Message                      |
39| -------- | ------------------------------ |
40| 5400101  | No memory. Return by callback. |
41
42**Example**
43
44```ts
45import { BusinessError } from '@kit.BasicServicesKit';
46
47let videoRecorder: media.VideoRecorder;
48media.createVideoRecorder((error: BusinessError, video: media.VideoRecorder) => {
49  if (video != null) {
50    videoRecorder = video;
51    console.info('video createVideoRecorder success');
52  } else {
53    console.error(`video createVideoRecorder fail, error message:${error.message}`);
54  }
55});
56```
57
58## media.createVideoRecorder<sup>9+</sup>
59
60createVideoRecorder(): Promise\<VideoRecorder>
61
62Creates a **VideoRecorder** instance. This API uses a promise to return the result.
63
64Only one **VideoRecorder** instance can be created per device.
65
66**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
67
68**System API**: This is a system API.
69
70**Return value**
71
72| Type                                     | Description                                                        |
73| ----------------------------------------- | ------------------------------------------------------------ |
74| Promise<[VideoRecorder](#videorecorder9)> | Promise used to return the result. If the operation is successful, a **VideoRecorder** instance is returned; otherwise, **null** is returned. The instance can be used to record video.|
75
76**Error codes**
77
78For details about the error codes, see [Media Error Codes](errorcode-media.md).
79
80| ID| Error Message                     |
81| -------- | ----------------------------- |
82| 5400101  | No memory. Return by promise. |
83
84**Example**
85
86```ts
87import { BusinessError } from '@kit.BasicServicesKit';
88
89let videoRecorder: media.VideoRecorder;
90media.createVideoRecorder().then((video: media.VideoRecorder) => {
91  if (video != null) {
92    videoRecorder = video;
93    console.info('video createVideoRecorder success');
94  } else {
95    console.error('video createVideoRecorder fail');
96  }
97}).catch((error: BusinessError) => {
98  console.error(`video catchCallback, error message:${error.message}`);
99});
100```
101
102## media.reportAVScreenCaptureUserChoice<sup>12+</sup>
103
104reportAVScreenCaptureUserChoice(sessionId: number, choice: string): Promise\<void>
105
106Reports the user selection result in the screen capture privacy dialog box to the AVScreenCapture server to determine whether to start screen capture. Screen capture starts only when the user touches a button to continue the operation.
107
108This API is called by the system application that creates the dialog box.
109
110**System capability**: SystemCapability.Multimedia.Media.AVScreenCapture
111
112**System API**: This is a system API.
113
114**Parameters**
115
116| Name   | Type  | Mandatory| Description                                                         |
117| --------- | ------ | ---- | ------------------------------------------------------------ |
118| sessionId | number | Yes  | Session ID of the AVScreenCapture service, which is sent to the application when the AVScreenCapture server starts the privacy dialog box.|
119| choice    | string | Yes  | User choice, including whether screen capture is agreed, selected display ID, and window ID. For details, see JsonData in the example below.|
120
121**Error codes**
122
123| ID| Error Message                                   |
124| -------- | ------------------------------------------- |
125| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. |
126| 5400101  | No memory. Return by promise.               |
127
128**Example**
129
130```ts
131import { BusinessError } from '@kit.BasicServicesKit';
132import { media } from '@kit.MediaKit';
133
134class JsonData {
135  public choice: string = 'true'
136  public displayId: number | null = -1
137  public missionId: number | null = -1
138}
139let sessionId: number = 0; // Use the ID of the session that starts the process.
140
141try {
142  const jsonData: JsonData = {
143    choice: 'true',  // Replace it with the user choice.
144    displayId: -1, // Replace it with the ID of the display selected by the user.
145    missionId: -1,   // Replace it with the ID of the window selected by the user.
146  }
147  await media.reportAVScreenCaptureUserChoice(sessionId, JSON.stringify(jsonData));
148} catch (error: BusinessError) {
149  console.error(`reportAVScreenCaptureUserChoice error, error message: ${error.message}`);
150}
151```
152
153## PixelMapParams<sup>11+</sup>
154
155Defines the format parameters of the video thumbnail to be obtained.
156
157**System capability**: SystemCapability.Multimedia.Media.AVImageGenerator
158
159| Name    | Type  |  Readable  |   Writable   |  Description                  |
160| -------- | ------ |   ------| ------ | ---------------------- |
161| colorFormat  | [PixelFormat](#pixelformat11) |  Yes  |  Yes  | Color format of the thumbnail.<br>**System API**: This is a system API.     |
162
163## PixelFormat<sup>11+</sup>
164
165Enumerates the color formats supported by the video thumbnail.
166
167**System capability**: SystemCapability.Multimedia.Media.AVImageGenerator
168
169**System API**: This is a system API.
170
171| Name                    | Value             | Description                                                        |
172| ------------------------ | --------------- | ------------------------------------------------------------ |
173| RGB_565       | 2   | RGB_565.                      |
174| RGBA_8888        | 3    | RGBA_8888.|
175| RGB_888        | 5    | RGB_888.                |
176
177## AvPlayer<sup>9+</sup>
178
179A playback management class that provides APIs to manage and play media assets. Before calling any API in **AVPlayer**, you must use [createAVPlayer()](js-apis-media.md#mediacreateavplayer9) to create an [AVPlayer](js-apis-media.md#avplayer9) instance.
180
181### setPlaybackRange<sup>12+</sup>
182
183setPlaybackRange(startTimeMs: number, endTimeMs: number, mode?: SeekMode) : Promise\<void>
184
185Sets the playback range and seeks to the start position of the range based on the specified [SeekMode](js-apis-media.md#seekmode8). After the setting, only the content in the specified range of the audio or video file is played. This API uses a promise to return the result. It can be used when the AVPlayer is in the initialized, prepared, paused, stopped, or completed state.
186
187**System capability**: SystemCapability.Multimedia.Media.AvPlayer
188
189**System API**: This is a system API.
190
191**Parameters**
192
193| Name  | Type                  | Mandatory| Description                       |
194| -------- | ---------------------- | ---- | --------------------------- |
195| startTimeMs | number | Yes  | Start position of the range, in ms. The value range is [0, duration). If **-1** is passed in, the system starts playing from position 0.|
196| endTimeMs | number | Yes  | End position of the range, in ms. The value range is (startTimeMs, duration]. If **-1** is passed in, the system plays the content until it reaches the final part of the asset.|
197| mode | [SeekMode](js-apis-media.md#seekmode8) | No  | Seek mode, which can be **SeekMode.SEEK_PREV_SYNC** or **SeekMode.SEEK_CLOSEST**.<br>The default value is **SeekMode.SEEK_PREV_SYNC**.|
198
199**Error codes**
200
201For details about the error codes, see [Media Error Codes](errorcode-media.md).
202
203| ID| Error Message                                  |
204| -------- | ------------------------------------------ |
205| 202  | Called from Non-System applications. Return by promise. |
206| 401  | The parameter check failed. Return by promise. |
207| 5400102  | Operation not allowed. Return by promise. |
208
209**Example**
210
211```ts
212import { media } from '@kit.MediaKit';
213import { BusinessError } from '@kit.BasicServicesKit';
214
215avPlayer.setPlaybackRange(0, 6000, media.SeekMode.SEEK_CLOSEST).then(() => {
216  console.info('Succeeded setPlaybackRange');
217}).catch((err: BusinessError) => {
218  console.error('Failed to setPlaybackRange' + err.message);
219});
220```
221
222## AVMetadataExtractor<sup>11+</sup>
223
224Provides APIs to obtain metadata from media assets. Before calling any API of **AVMetadataExtractor**, you must use [createAVMetadataExtractor()](js-apis-media.md#mediacreateavmetadataextractor11) to create an **AVMetadataExtractor** instance.
225
226### getTimeByFrameIndex<sup>12+</sup>
227
228getTimeByFrameIndex(index: number): Promise\<number>
229
230Obtains the video timestamp corresponding to a video frame number. Only MP4 video files are supported.
231
232**System capability**: SystemCapability.Multimedia.Media.AVMetadataExtractor
233
234**System API**: This is a system API.
235
236**Parameters**
237
238| Name| Type  | Mandatory| Description      |
239| ------ | ------ | ---- | ---------- |
240| index  | number | Yes  | Video frame number.|
241
242**Return value**
243
244| Type            | Description                               |
245| ---------------- | ----------------------------------- |
246| Promise\<number> | Promise used to return the timestamp, in microseconds.|
247
248**Error codes**
249
250For details about the error codes, see [Media Error Codes](errorcode-media.md).
251
252| ID| Error Message                                      |
253| -------- | ---------------------------------------------- |
254| 401      | The parameter check failed. Return by promise. |
255| 5400102  | Operation not allowed. Returned by promise.    |
256| 5400106  | Unsupported format. Returned by promise.       |
257
258**Example**
259
260```ts
261import { media } from '@kit.MediaKit';
262import { BusinessError } from '@kit.BasicServicesKit';
263
264avMetadataExtractor.getTimeByFrameIndex(0).then((timeUs: number) => {
265  console.info(`Succeeded getTimeByFrameIndex timeUs: ${timeUs}`);
266}).catch((err: BusinessError) => {
267  console.error(`Failed to getTimeByFrameIndex ${err.message}`);
268})
269```
270
271### getFrameIndexByTime<sup>12+</sup>
272
273getFrameIndexByTime(timeUs: number): Promise\<number>
274
275Obtains the video frame number corresponding to a video timestamp. Only MP4 video files are supported.
276
277**System capability**: SystemCapability.Multimedia.Media.AVMetadataExtractor
278
279**System API**: This is a system API.
280
281**Parameters**
282
283| Name| Type  | Mandatory| Description                    |
284| ------ | ------ | ---- | ------------------------ |
285| timeUs | number | Yes  | Video timestamp, in microseconds.|
286
287**Return value**
288
289| Type            | Description                     |
290| ---------------- | ------------------------- |
291| Promise\<number> | Promise used to return the video frame number.|
292
293**Error codes**
294
295For details about the error codes, see [Media Error Codes](errorcode-media.md).
296
297| ID| Error Message                                      |
298| -------- | ---------------------------------------------- |
299| 401      | The parameter check failed. Return by promise. |
300| 5400102  | Operation not allowed. Returned by promise.    |
301| 5400106  | Unsupported format. Returned by promise.       |
302
303**Example**
304
305```ts
306import { media } from '@kit.MediaKit';
307import { BusinessError } from '@kit.BasicServicesKit';
308
309avMetadataExtractor.getFrameIndexByTime(0).then((index: number) => {
310  console.info(`Succeeded getFrameIndexByTime index: ${index}`);
311}).catch((err: BusinessError) => {
312  console.error(`Failed to getFrameIndexByTime ${err.message}`);
313})
314```
315
316## VideoRecorder<sup>9+</sup>
317
318> **NOTE**
319> This class is deprecated after AVRecorder<sup>9+</sup> is released. You are advised to use [AVRecorder](js-apis-media.md#avrecorder9) instead.
320
321Implements video recording. Before calling any API in the **VideoRecorder** class, you must use [createVideoRecorder()](#mediacreatevideorecorder9) to create a [VideoRecorder](#videorecorder9) instance.
322
323### Attributes
324
325**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
326
327**System API**: This is a system API.
328
329| Name              | Type                                  | Readable| Writable| Description            |
330| ------------------ | -------------------------------------- | ---- | ---- | ---------------- |
331| state<sup>9+</sup> | [VideoRecordState](#videorecordstate9) | Yes  | No  | Video recording state.|
332
333### prepare<sup>9+</sup>
334
335prepare(config: VideoRecorderConfig, callback: AsyncCallback\<void>): void
336
337Sets video recording parameters. This API uses an asynchronous callback to return the result.
338
339**Required permissions:** ohos.permission.MICROPHONE
340
341**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
342
343**System API**: This is a system API.
344
345**Parameters**
346
347| Name  | Type                                        | Mandatory| Description                               |
348| -------- | -------------------------------------------- | ---- | ----------------------------------- |
349| config   | [VideoRecorderConfig](#videorecorderconfig9) | Yes  | Video recording parameters to set.           |
350| callback | AsyncCallback\<void>                         | Yes  | Callback used to return the result.|
351
352**Error codes**
353
354For details about the error codes, see [Media Error Codes](errorcode-media.md).
355
356| ID| Error Message                                  |
357| -------- | ------------------------------------------ |
358| 201      | Permission denied. Return by callback.     |
359| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed.       |
360| 5400102  | Operation not allowed. Return by callback. |
361| 5400105  | Service died. Return by callback.          |
362
363**Example**
364
365```ts
366import { BusinessError } from '@kit.BasicServicesKit';
367
368// Configure the parameters based on those supported by the hardware device.
369let videoProfile: media.VideoRecorderProfile = {
370  audioBitrate : 48000,
371  audioChannels : 2,
372  audioCodec : media.CodecMimeType.AUDIO_AAC,
373  audioSampleRate : 48000,
374  fileFormat : media.ContainerFormatType.CFT_MPEG_4,
375  videoBitrate : 2000000,
376  videoCodec : media.CodecMimeType.VIDEO_AVC,
377  videoFrameWidth : 640,
378  videoFrameHeight : 480,
379  videoFrameRate : 30
380}
381
382let videoConfig: media.VideoRecorderConfig = {
383  audioSourceType : media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC,
384  videoSourceType : media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV,
385  profile : videoProfile,
386  url : 'fd://xx', // The file must be created by the caller and granted with proper permissions.
387  rotation : 0,
388  location : { latitude : 30, longitude : 130 }
389}
390
391// asyncallback
392videoRecorder.prepare(videoConfig, (err: BusinessError) => {
393  if (err == null) {
394    console.info('prepare success');
395  } else {
396    console.error('prepare failed and error is ' + err.message);
397  }
398})
399```
400
401### prepare<sup>9+</sup>
402
403prepare(config: VideoRecorderConfig): Promise\<void>
404
405Sets video recording parameters. This API uses a promise to return the result.
406
407**Required permissions:** ohos.permission.MICROPHONE
408
409**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
410
411**System API**: This is a system API.
412
413**Parameters**
414
415| Name| Type                                        | Mandatory| Description                    |
416| ------ | -------------------------------------------- | ---- | ------------------------ |
417| config | [VideoRecorderConfig](#videorecorderconfig9) | Yes  | Video recording parameters to set.|
418
419**Return value**
420
421| Type          | Description                                    |
422| -------------- | ---------------------------------------- |
423| Promise\<void> | Promise used to return the result.|
424
425**Error codes**
426
427For details about the error codes, see [Media Error Codes](errorcode-media.md).
428
429| ID| Error Message                                 |
430| -------- | ----------------------------------------- |
431| 201      | Permission denied. Return by promise.     |
432| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed.       |
433| 5400102  | Operation not allowed. Return by promise. |
434| 5400105  | Service died. Return by promise.          |
435
436**Example**
437
438```ts
439import { BusinessError } from '@kit.BasicServicesKit';
440
441// Configure the parameters based on those supported by the hardware device.
442let videoProfile: media.VideoRecorderProfile = {
443  audioBitrate : 48000,
444  audioChannels : 2,
445  audioCodec : media.CodecMimeType.AUDIO_AAC,
446  audioSampleRate : 48000,
447  fileFormat : media.ContainerFormatType.CFT_MPEG_4,
448  videoBitrate : 2000000,
449  videoCodec : media.CodecMimeType.VIDEO_AVC,
450  videoFrameWidth : 640,
451  videoFrameHeight : 480,
452  videoFrameRate : 30
453}
454
455let videoConfig: media.VideoRecorderConfig = {
456  audioSourceType : media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC,
457  videoSourceType : media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV,
458  profile : videoProfile,
459  url : 'fd://xx', // The file must be created by the caller and granted with proper permissions.
460  rotation : 0,
461  location : { latitude : 30, longitude : 130 }
462}
463
464// promise
465videoRecorder.prepare(videoConfig).then(() => {
466  console.info('prepare success');
467}).catch((err: BusinessError) => {
468  console.error('prepare failed and catch error is ' + err.message);
469});
470```
471
472### getInputSurface<sup>9+</sup>
473
474getInputSurface(callback: AsyncCallback\<string>): void
475
476Obtains 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 data.
477
478Note 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.
479
480This API can be called only after [prepare()](#prepare9) is called.
481
482**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
483
484**System API**: This is a system API.
485
486**Parameters**
487
488| Name  | Type                  | Mandatory| Description                       |
489| -------- | ---------------------- | ---- | --------------------------- |
490| callback | AsyncCallback\<string> | Yes  | Callback used to return the result.|
491
492**Error codes**
493
494For details about the error codes, see [Media Error Codes](errorcode-media.md).
495
496| ID| Error Message                                  |
497| -------- | ------------------------------------------ |
498| 5400102  | Operation not allowed. Return by callback. |
499| 5400103  | I/O error. Return by callback.             |
500| 5400105  | Service died. Return by callback.          |
501
502**Example**
503
504```ts
505import { BusinessError } from '@kit.BasicServicesKit';
506
507// asyncallback
508let surfaceID: string; // Surface ID passed to the external system.
509videoRecorder.getInputSurface((err: BusinessError, surfaceId: string) => {
510  if (err == null) {
511    console.info('getInputSurface success');
512    surfaceID = surfaceId;
513  } else {
514    console.error('getInputSurface failed and error is ' + err.message);
515  }
516});
517```
518
519### getInputSurface<sup>9+</sup>
520
521getInputSurface(): Promise\<string>;
522
523 Obtains 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 data.
524
525Note 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.
526
527This API can be called only after [prepare()](#prepare9-1) is called.
528
529**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
530
531**System API**: This is a system API.
532
533**Return value**
534
535| Type            | Description                            |
536| ---------------- | -------------------------------- |
537| Promise\<string> | Promise used to return the result.|
538
539**Error codes**
540
541For details about the error codes, see [Media Error Codes](errorcode-media.md).
542
543| ID| Error Message                                 |
544| -------- | ----------------------------------------- |
545| 5400102  | Operation not allowed. Return by promise. |
546| 5400103  | I/O error. Return by promise.             |
547| 5400105  | Service died. Return by promise.          |
548
549**Example**
550
551```ts
552import { BusinessError } from '@kit.BasicServicesKit';
553
554// promise
555let surfaceID: string; // Surface ID passed to the external system.
556videoRecorder.getInputSurface().then((surfaceId: string) => {
557  console.info('getInputSurface success');
558  surfaceID = surfaceId;
559}).catch((err: BusinessError) => {
560  console.error('getInputSurface failed and catch error is ' + err.message);
561});
562```
563
564### start<sup>9+</sup>
565
566start(callback: AsyncCallback\<void>): void
567
568Starts recording. This API uses an asynchronous callback to return the result.
569
570This API can be called only after [prepare()](#prepare9) and [getInputSurface()](#getinputsurface9) are called, because the data source must pass data to the surface first.
571
572**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
573
574**System API**: This is a system API.
575
576**Parameters**
577
578| Name  | Type                | Mandatory| Description                        |
579| -------- | -------------------- | ---- | ---------------------------- |
580| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.|
581
582**Error codes**
583
584For details about the error codes, see [Media Error Codes](errorcode-media.md).
585
586| ID| Error Message                                  |
587| -------- | ------------------------------------------ |
588| 5400102  | Operation not allowed. Return by callback. |
589| 5400103  | I/O error. Return by callback.             |
590| 5400105  | Service died. Return by callback.          |
591
592**Example**
593
594```ts
595import { BusinessError } from '@kit.BasicServicesKit';
596
597// asyncallback
598videoRecorder.start((err: BusinessError) => {
599  if (err == null) {
600    console.info('start videorecorder success');
601  } else {
602    console.error('start videorecorder failed and error is ' + err.message);
603  }
604});
605```
606
607### start<sup>9+</sup>
608
609start(): Promise\<void>
610
611Starts recording. This API uses a promise to return the result.
612
613This API can be called only after [prepare()](#prepare9-1) and [getInputSurface()](#getinputsurface9-1) are called, because the data source must pass data to the surface first.
614
615**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
616
617**System API**: This is a system API.
618
619**Return value**
620
621| Type          | Description                                 |
622| -------------- | ------------------------------------- |
623| Promise\<void> | Promise used to return the result.|
624
625**Error codes**
626
627For details about the error codes, see [Media Error Codes](errorcode-media.md).
628
629| ID| Error Message                                 |
630| -------- | ----------------------------------------- |
631| 5400102  | Operation not allowed. Return by promise. |
632| 5400103  | I/O error. Return by promise.             |
633| 5400105  | Service died. Return by promise.          |
634
635**Example**
636
637```ts
638import { BusinessError } from '@kit.BasicServicesKit';
639
640// promise
641videoRecorder.start().then(() => {
642  console.info('start videorecorder success');
643}).catch((err: BusinessError) => {
644  console.error('start videorecorder failed and catch error is ' + err.message);
645});
646```
647
648### pause<sup>9+</sup>
649
650pause(callback: AsyncCallback\<void>): void
651
652Pauses recording. This API uses an asynchronous callback to return the result.
653
654This API can be called only after [start()](#start9) is called. You can resume recording by calling [resume()](#resume9).
655
656**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
657
658**System API**: This is a system API.
659
660**Parameters**
661
662| Name  | Type                | Mandatory| Description                        |
663| -------- | -------------------- | ---- | ---------------------------- |
664| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.|
665
666**Error codes**
667
668For details about the error codes, see [Media Error Codes](errorcode-media.md).
669
670| ID| Error Message                                  |
671| -------- | ------------------------------------------ |
672| 5400102  | Operation not allowed. Return by callback. |
673| 5400103  | I/O error. Return by callback.             |
674| 5400105  | Service died. Return by callback.          |
675
676**Example**
677
678```ts
679import { BusinessError } from '@kit.BasicServicesKit';
680
681// asyncallback
682videoRecorder.pause((err: BusinessError) => {
683  if (err == null) {
684    console.info('pause videorecorder success');
685  } else {
686    console.error('pause videorecorder failed and error is ' + err.message);
687  }
688});
689```
690
691### pause<sup>9+</sup>
692
693pause(): Promise\<void>
694
695Pauses recording. This API uses a promise to return the result.
696
697This API can be called only after [start()](#start9-1) is called. You can resume recording by calling [resume()](#resume9-1).
698
699**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
700
701**System API**: This is a system API.
702
703**Return value**
704
705| Type          | Description                                 |
706| -------------- | ------------------------------------- |
707| Promise\<void> | Promise used to return the result.|
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| 5400102  | Operation not allowed. Return by promise. |
716| 5400103  | I/O error. Return by promise.             |
717| 5400105  | Service died. Return by promise.          |
718
719**Example**
720
721```ts
722import { BusinessError } from '@kit.BasicServicesKit';
723
724// promise
725videoRecorder.pause().then(() => {
726  console.info('pause videorecorder success');
727}).catch((err: BusinessError) => {
728  console.error('pause videorecorder failed and catch error is ' + err.message);
729});
730```
731
732### resume<sup>9+</sup>
733
734resume(callback: AsyncCallback\<void>): void
735
736Resumes recording. This API uses an asynchronous callback to return the result.
737
738**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
739
740**System API**: This is a system API.
741
742**Parameters**
743
744| Name  | Type                | Mandatory| Description                        |
745| -------- | -------------------- | ---- | ---------------------------- |
746| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.|
747
748**Error codes**
749
750For details about the error codes, see [Media Error Codes](errorcode-media.md).
751
752| ID| Error Message                                  |
753| -------- | ------------------------------------------ |
754| 5400102  | Operation not allowed. Return by callback. |
755| 5400103  | I/O error. Return by callback.             |
756| 5400105  | Service died. Return by callback.          |
757
758**Example**
759
760```ts
761import { BusinessError } from '@kit.BasicServicesKit';
762
763// asyncallback
764videoRecorder.resume((err: BusinessError) => {
765  if (err == null) {
766    console.info('resume videorecorder success');
767  } else {
768    console.error('resume videorecorder failed and error is ' + err.message);
769  }
770});
771```
772
773### resume<sup>9+</sup>
774
775resume(): Promise\<void>
776
777Resumes recording. This API uses a promise to return the result.
778
779**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
780
781**System API**: This is a system API.
782
783**Return value**
784
785| Type          | Description                                 |
786| -------------- | ------------------------------------- |
787| Promise\<void> | Promise used to return the result.|
788
789**Error codes**
790
791For details about the error codes, see [Media Error Codes](errorcode-media.md).
792
793| ID| Error Message                                 |
794| -------- | ----------------------------------------- |
795| 5400102  | Operation not allowed. Return by promise. |
796| 5400103  | I/O error. Return by promise.             |
797| 5400105  | Service died. Return by promise.          |
798
799**Example**
800
801```ts
802import { BusinessError } from '@kit.BasicServicesKit';
803
804// promise
805videoRecorder.resume().then(() => {
806  console.info('resume videorecorder success');
807}).catch((err: BusinessError) => {
808  console.error('resume videorecorder failed and catch error is ' + err.message);
809});
810```
811
812### stop<sup>9+</sup>
813
814stop(callback: AsyncCallback\<void>): void
815
816Stops recording. This API uses an asynchronous callback to return the result.
817
818To start another recording, you must call [prepare()](#prepare9) and [getInputSurface()](#getinputsurface9) again.
819
820**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
821
822**System API**: This is a system API.
823
824**Parameters**
825
826| Name  | Type                | Mandatory| Description                        |
827| -------- | -------------------- | ---- | ---------------------------- |
828| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.|
829
830**Error codes**
831
832For details about the error codes, see [Media Error Codes](errorcode-media.md).
833
834| ID| Error Message                                  |
835| -------- | ------------------------------------------ |
836| 5400102  | Operation not allowed. Return by callback. |
837| 5400103  | I/O error. Return by callback.             |
838| 5400105  | Service died. Return by callback.          |
839
840**Example**
841
842```ts
843import { BusinessError } from '@kit.BasicServicesKit';
844
845// asyncallback
846videoRecorder.stop((err: BusinessError) => {
847  if (err == null) {
848    console.info('stop videorecorder success');
849  } else {
850    console.error('stop videorecorder failed and error is ' + err.message);
851  }
852});
853```
854
855### stop<sup>9+</sup>
856
857stop(): Promise\<void>
858
859Stops recording. This API uses a promise to return the result.
860
861To start another recording, you must call [prepare()](#prepare9-1) and [getInputSurface()](#getinputsurface9-1) again.
862
863**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
864
865**System API**: This is a system API.
866
867**Return value**
868
869| Type          | Description                                 |
870| -------------- | ------------------------------------- |
871| Promise\<void> | Promise used to return the result.|
872
873**Error codes**
874
875For details about the error codes, see [Media Error Codes](errorcode-media.md).
876
877| ID| Error Message                                 |
878| -------- | ----------------------------------------- |
879| 5400102  | Operation not allowed. Return by promise. |
880| 5400103  | I/O error. Return by promise.             |
881| 5400105  | Service died. Return by promise.          |
882
883**Example**
884
885```ts
886import { BusinessError } from '@kit.BasicServicesKit';
887
888// promise
889videoRecorder.stop().then(() => {
890  console.info('stop videorecorder success');
891}).catch((err: BusinessError) => {
892  console.error('stop videorecorder failed and catch error is ' + err.message);
893});
894```
895
896### release<sup>9+</sup>
897
898release(callback: AsyncCallback\<void>): void
899
900Releases the video recording resources. This API uses an asynchronous callback to return the result.
901
902**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
903
904**System API**: This is a system API.
905
906**Parameters**
907
908| Name  | Type                | Mandatory| Description                            |
909| -------- | -------------------- | ---- | -------------------------------- |
910| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.|
911
912**Error codes**
913
914For details about the error codes, see [Media Error Codes](errorcode-media.md).
915
916| ID| Error Message                         |
917| -------- | --------------------------------- |
918| 5400105  | Service died. Return by callback. |
919
920**Example**
921
922```ts
923import { BusinessError } from '@kit.BasicServicesKit';
924
925// asyncallback
926videoRecorder.release((err: BusinessError) => {
927  if (err == null) {
928    console.info('release videorecorder success');
929  } else {
930    console.error('release videorecorder failed and error is ' + err.message);
931  }
932});
933```
934
935### release<sup>9+</sup>
936
937release(): Promise\<void>
938
939Releases the video recording resources. This API uses a promise to return the result.
940
941**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
942
943**System API**: This is a system API.
944
945**Return value**
946
947| Type          | Description                                     |
948| -------------- | ----------------------------------------- |
949| Promise\<void> | Promise used to return the result.|
950
951**Error codes**
952
953For details about the error codes, see [Media Error Codes](errorcode-media.md).
954
955| ID| Error Message                         |
956| -------- | --------------------------------- |
957| 5400105  | Service died. Return by callback. |
958
959**Example**
960
961```ts
962import { BusinessError } from '@kit.BasicServicesKit';
963
964// promise
965videoRecorder.release().then(() => {
966  console.info('release videorecorder success');
967}).catch((err: BusinessError) => {
968  console.error('release videorecorder failed and catch error is ' + err.message);
969});
970```
971
972### reset<sup>9+</sup>
973
974reset(callback: AsyncCallback\<void>): void
975
976Resets video recording. This API uses an asynchronous callback to return the result.
977
978To start another recording, you must call [prepare()](#prepare9) and [getInputSurface()](#getinputsurface9) again.
979
980**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
981
982**System API**: This is a system API.
983
984**Parameters**
985
986| Name  | Type                | Mandatory| Description                        |
987| -------- | -------------------- | ---- | ---------------------------- |
988| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.|
989
990**Error codes**
991
992For details about the error codes, see [Media Error Codes](errorcode-media.md).
993
994| ID| Error Message                         |
995| -------- | --------------------------------- |
996| 5400103  | I/O error. Return by callback.    |
997| 5400105  | Service died. Return by callback. |
998
999**Example**
1000
1001```ts
1002import { BusinessError } from '@kit.BasicServicesKit';
1003
1004// asyncallback
1005videoRecorder.reset((err: BusinessError) => {
1006  if (err == null) {
1007    console.info('reset videorecorder success');
1008  } else {
1009    console.error('reset videorecorder failed and error is ' + err.message);
1010  }
1011});
1012```
1013
1014### reset<sup>9+</sup>
1015
1016reset(): Promise\<void>
1017
1018Resets video recording. This API uses a promise to return the result.
1019
1020To start another recording, you must call [prepare()](#prepare9-1) and [getInputSurface()](#getinputsurface9-1) again.
1021
1022**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
1023
1024**System API**: This is a system API.
1025
1026**Return value**
1027
1028| Type          | Description                                 |
1029| -------------- | ------------------------------------- |
1030| Promise\<void> | Promise used to return the result.|
1031
1032**Error codes**
1033
1034For details about the error codes, see [Media Error Codes](errorcode-media.md).
1035
1036| ID| Error Message                        |
1037| -------- | -------------------------------- |
1038| 5400103  | I/O error. Return by promise.    |
1039| 5400105  | Service died. Return by promise. |
1040
1041**Example**
1042
1043```ts
1044import { BusinessError } from '@kit.BasicServicesKit';
1045
1046// promise
1047videoRecorder.reset().then(() => {
1048  console.info('reset videorecorder success');
1049}).catch((err: BusinessError) => {
1050  console.error('reset videorecorder failed and catch error is ' + err.message);
1051});
1052```
1053
1054### on('error')<sup>9+</sup>
1055
1056on(type: 'error', callback: ErrorCallback): void
1057
1058Subscribes to video recording error events. After an error event is reported, you must handle the event and exit the recording.
1059
1060**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
1061
1062**System API**: This is a system API.
1063
1064**Parameters**
1065
1066| Name  | Type         | Mandatory| Description                                                        |
1067| -------- | ------------- | ---- | ------------------------------------------------------------ |
1068| type     | string        | Yes  | Event type, which is **'error'** in this case.<br>This event is triggered when an error occurs during video recording.|
1069| callback | [ErrorCallback](../apis-basic-services-kit/js-apis-base.md#errorcallback) | Yes  | Callback invoked when the event is triggered.                                      |
1070
1071**Error codes**
1072
1073For details about the error codes, see [Media Error Codes](errorcode-media.md).
1074
1075| ID| Error Message                         |
1076| -------- | --------------------------------- |
1077| 5400103  | I/O error. Return by callback.    |
1078| 5400105  | Service died. Return by callback. |
1079
1080**Example**
1081
1082```ts
1083import { BusinessError } from '@kit.BasicServicesKit';
1084
1085// This event is reported when an error occurs during the retrieval of videoRecordState.
1086videoRecorder.on('error', (error: BusinessError) => { // Set the 'error' event callback.
1087  console.error(`audio error called, error: ${error}`);
1088})
1089```
1090
1091## VideoRecordState<sup>9+</sup>
1092
1093Enumerates the video recording states. You can obtain the state through the **state** attribute.
1094
1095**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
1096
1097**System API**: This is a system API.
1098
1099| Name    | Type  | Description                  |
1100| -------- | ------ | ---------------------- |
1101| idle     | string | The video recorder is idle.        |
1102| prepared | string | The video recording parameters are set.|
1103| playing  | string | Video recording is in progress.        |
1104| paused   | string | Video recording is paused.        |
1105| stopped  | string | Video recording is stopped.        |
1106| error    | string | Video recording is in the error state.            |
1107
1108## VideoRecorderConfig<sup>9+</sup>
1109
1110Describes the video recording parameters.
1111
1112The **audioSourceType** and **videoSourceType** parameters are used to distinguish video-only recording from audio and video recording. (For audio-only recording, use [AVRecorder](js-apis-media.md#avrecorder9) or [AudioRecorder](js-apis-media.md#audiorecorderdeprecated).) For video-only recording, set only **videoSourceType**. For audio and video recording, set both **audioSourceType** and **videoSourceType**.
1113
1114**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
1115
1116**System API**: This is a system API.
1117
1118| Name           | Type                                          | Mandatory| Description                                                        |
1119| --------------- | ---------------------------------------------- | ---- | ------------------------------------------------------------ |
1120| audioSourceType | [AudioSourceType](js-apis-media.md#audiosourcetype9)           | No  | Type of the audio source for video recording. This parameter is mandatory for audio recording.                     |
1121| videoSourceType | [VideoSourceType](js-apis-media.md#videosourcetype9)           | Yes  | Type of the video source for video recording.                                      |
1122| profile         | [VideoRecorderProfile](#videorecorderprofile9) | Yes  | Video recording profile.                                         |
1123| rotation        | number                                         | No  | Rotation angle of the recorded video. The value can only be 0 (default), 90, 180, or 270.      |
1124| location        | [Location](js-apis-media.md#location)                          | No  | Geographical location of the recorded video. By default, the geographical location information is not recorded.                |
1125| url             | string                                         | Yes  | Video output URL. Supported: fd://xx (fd number)<br>![](figures/en-us_image_url.png) |
1126
1127## VideoRecorderProfile<sup>9+</sup>
1128
1129Describes the video recording profile.
1130
1131**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
1132
1133**System API**: This is a system API.
1134
1135| Name            | Type                                        | Mandatory| Description            |
1136| ---------------- | -------------------------------------------- | ---- | ---------------- |
1137| audioBitrate     | number                                       | No  | Audio encoding bit rate. This parameter is mandatory for audio recording.|
1138| audioChannels    | number                                       | No  | Number of audio channels. This parameter is mandatory for audio recording.|
1139| audioCodec       | [CodecMimeType](js-apis-media.md#codecmimetype8)             | No  | Audio encoding format. This parameter is mandatory for audio recording.  |
1140| audioSampleRate  | number                                       | No  | Audio sampling rate. This parameter is mandatory for audio recording.    |
1141| fileFormat       | [ContainerFormatType](js-apis-media.md#containerformattype8) | Yes  | Container format of a file.|
1142| videoBitrate     | number                                       | Yes  | Video encoding bit rate.|
1143| videoCodec       | [CodecMimeType](js-apis-media.md#codecmimetype8)             | Yes  | Video encoding format.  |
1144| videoFrameWidth  | number                                       | Yes  | Width of the recorded video frame.|
1145| videoFrameHeight | number                                       | Yes  | Height of the recorded video frame.|
1146| videoFrameRate   | number                                       | Yes  | Video frame rate.  |
1147