1# Video Recording (ArkTS)
2
3As another important function of the camera application, video recording is the process of cyclic frame capture. To smooth video recording, you can follow step 4 in [Photo Capture](camera-shooting.md) to set the resolution, flash, focal length, photo quality, and rotation angle.
4
5## How to Develop
6
7Read [Camera](../../reference/apis-camera-kit/js-apis-camera.md) for the API reference.
8
91. Import the media module. The [APIs](../../reference/apis-media-kit/js-apis-media.md) provided by this module are used to obtain the surface ID and create a video output stream.
10
11   ```ts
12   import { BusinessError } from '@kit.BasicServicesKit';
13   import { camera } from '@kit.CameraKit';
14   import { media } from '@kit.MediaKit';
15   ```
16
172. Create a surface.
18
19   Call **createAVRecorder()** of the media module to create an **AVRecorder** instance, and call [getInputSurface](../../reference/apis-media-kit/js-apis-media.md#getinputsurface9) of the instance to obtain the surface ID, which is associated with the video output stream to process the stream data.
20
21   ```ts
22   async function getVideoSurfaceId(aVRecorderConfig: media.AVRecorderConfig): Promise<string | undefined> {  // For details about aVRecorderConfig, see the next section.
23     let avRecorder: media.AVRecorder | undefined = undefined;
24     try {
25       avRecorder = await media.createAVRecorder();
26     } catch (error) {
27       let err = error as BusinessError;
28       console.error(`createAVRecorder call failed. error code: ${err.code}`);
29     }
30     if (avRecorder === undefined) {
31       return undefined;
32     }
33     avRecorder.prepare(aVRecorderConfig, (err: BusinessError) => {
34       if (err == null) {
35         console.info('prepare success');
36       } else {
37         console.error('prepare failed and error is ' + err.message);
38       }
39     });
40     let videoSurfaceId = await avRecorder.getInputSurface();
41     return videoSurfaceId;
42   }
43   ```
44
453. Create a video output stream.
46
47   Obtain the video output streams supported by the current device from **videoProfiles** in the [CameraOutputCapability](../../reference/apis-camera-kit/js-apis-camera.md#cameraoutputcapability) class. Then, define video recording parameters and use [createVideoOutput](../../reference/apis-camera-kit/js-apis-camera.md#createvideooutput) to create a video output stream.
48
49   > **NOTE**
50   >
51   > The preview stream and video output stream must have the same aspect ratio of the resolution. For example, the aspect ratio in the code snippet below is 640:480 (which is equal to 4:3), then the aspect ratio of the resolution of the preview stream must also be 4:3. This means that the resolution can be 640:480, 960:720, 1440:1080, or the like.
52   >
53   > To obtain the video rotation angle (specified by **rotation**), call [getVideoRotation](../../reference/apis-camera-kit/js-apis-camera.md#getvideorotation12) in the [VideoOutput](../../reference/apis-camera-kit/js-apis-camera.md#videooutput) class.
54
55   ```ts
56   async function getVideoOutput(cameraManager: camera.CameraManager, videoSurfaceId: string, cameraOutputCapability: camera.CameraOutputCapability): Promise<camera.VideoOutput | undefined> {
57     let videoProfilesArray: Array<camera.VideoProfile> = cameraOutputCapability.videoProfiles;
58     if (!videoProfilesArray) {
59       console.error("createOutput videoProfilesArray == null || undefined");
60       return undefined;
61     }
62     // AVRecorderProfile
63     let aVRecorderProfile: media.AVRecorderProfile = {
64       fileFormat: media.ContainerFormatType.CFT_MPEG_4, // Video file container format. Only MP4 is supported.
65       videoBitrate: 100000, // Video bit rate.
66       videoCodec: media.CodecMimeType.VIDEO_AVC, // Video file encoding format. AVC is supported.
67       videoFrameWidth: 640, // Video frame width.
68       videoFrameHeight: 480, // Video frame height.
69       videoFrameRate: 30 // Video frame rate.
70     };
71     // Define video recording parameters. The ratio of the resolution width (videoFrameWidth) to the resolution height (videoFrameHeight) of the video output stream must be the same as that of the preview stream.
72     let aVRecorderConfig: media.AVRecorderConfig = {
73       videoSourceType: media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV,
74       profile: aVRecorderProfile,
75       url: 'fd://35',
76       rotation: 90 // The value of rotation is 90, which is obtained through getPhotoRotation.
77     };
78     // Create an AVRecorder instance.
79     let avRecorder: media.AVRecorder | undefined = undefined;
80     try {
81       avRecorder = await media.createAVRecorder();
82     } catch (error) {
83       let err = error as BusinessError;
84       console.error(`createAVRecorder call failed. error code: ${err.code}`);
85     }
86     if (avRecorder === undefined) {
87       return undefined;
88     }
89     // Set video recording parameters.
90     avRecorder.prepare(aVRecorderConfig);
91     // Create a VideoOutput instance.
92     let videoOutput: camera.VideoOutput | undefined = undefined;
93     // The width and height of the videoProfile object passed in by createVideoOutput must be the same as those of aVRecorderProfile.
94     let videoProfile: undefined | camera.VideoProfile = videoProfilesArray.find((profile: camera.VideoProfile) => {
95       return profile.size.width === aVRecorderProfile.videoFrameWidth && profile.size.height === aVRecorderProfile.videoFrameHeight;
96     });
97     if (!videoProfile) {
98       console.error('videoProfile is not found');
99       return;
100     }
101     try {
102       videoOutput = cameraManager.createVideoOutput(videoProfile, videoSurfaceId);
103     } catch (error) {
104       let err = error as BusinessError;
105       console.error('Failed to create the videoOutput instance. errorCode = ' + err.code);
106     }
107     return videoOutput;
108   }
109   ```
110
1114. Start video recording.
112
113   Call [start](../../reference/apis-camera-kit/js-apis-camera.md#start-1) of the **VideoOutput** instance to start the video output stream, and then call [start](../../reference/apis-media-kit/js-apis-media.md#start9) of the **AVRecorder** instance to start recording.
114
115   ```ts
116   async function startVideo(videoOutput: camera.VideoOutput, avRecorder: media.AVRecorder): Promise<void> {
117     videoOutput.start(async (err: BusinessError) => {
118       if (err) {
119         console.error(`Failed to start the video output ${err.message}`);
120         return;
121       }
122       console.info('Callback invoked to indicate the video output start success.');
123     });
124     try {
125       await avRecorder.start();
126     } catch (error) {
127       let err = error as BusinessError;
128       console.error(`avRecorder start error: ${JSON.stringify(err)}`);
129     }
130   }
131   ```
132
1335. Stop video recording.
134
135   Call [stop](../../reference/apis-media-kit/js-apis-media.md#stop9-3) of the **AVRecorder** instance to stop recording, and then call [stop](../../reference/apis-camera-kit/js-apis-camera.md#stop-1) of the **VideoOutput** instance to stop the video output stream.
136
137   ```ts
138   async function stopVideo(videoOutput: camera.VideoOutput, avRecorder: media.AVRecorder): Promise<void> {
139     try {
140       await avRecorder.stop();
141     } catch (error) {
142       let err = error as BusinessError;
143       console.error(`avRecorder stop error: ${JSON.stringify(err)}`);
144     }
145     videoOutput.stop((err: BusinessError) => {
146       if (err) {
147         console.error(`Failed to stop the video output ${err.message}`);
148         return;
149       }
150       console.info('Callback invoked to indicate the video output stop success.');
151     });
152   }
153   ```
154
155
156## Status Listening
157
158During camera application development, you can listen for the status of the video output stream, including recording start, recording end, and video output errors.
159
160- Register the **'frameStart'** event to listen for recording start events. This event can be registered when a **VideoOutput** instance is created and is triggered when the bottom layer starts exposure for recording for the first time. Video recording starts as long as a result is returned.
161
162  ```ts
163  function onVideoOutputFrameStart(videoOutput: camera.VideoOutput): void {
164    videoOutput.on('frameStart', (err: BusinessError) => {
165      if (err !== undefined && err.code !== 0) {
166        return;
167      }
168      console.info('Video frame started');
169    });
170  }
171  ```
172
173- Register the **'frameEnd'** event to listen for recording end events. This event can be registered when a **VideoOutput** instance is created and is triggered when the last frame of recording ends. Video recording ends as long as a result is returned.
174
175  ```ts
176  function onVideoOutputFrameEnd(videoOutput: camera.VideoOutput): void {
177    videoOutput.on('frameEnd', (err: BusinessError) => {
178      if (err !== undefined && err.code !== 0) {
179        return;
180      }
181      console.info('Video frame ended');
182    });
183  }
184  ```
185
186- Register the **'error'** event to listen for video output errors. The callback function returns an error code when an API is incorrectly used. For details about the error code types, see [CameraErrorCode](../../reference/apis-camera-kit/js-apis-camera.md#cameraerrorcode).
187
188  ```ts
189  function onVideoOutputError(videoOutput: camera.VideoOutput): void {
190    videoOutput.on('error', (error: BusinessError) => {
191      console.error(`Video output error code: ${error.code}`);
192    });
193  }
194  ```
195
196<!--RP1-->
197<!--RP1End-->
198