• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Camera Recording
2
3Video recording is also an important function of the camera application. Video recording is the process of cyclic capturing of frames. To smooth videos, you can follow step 4 in [Camera Photographing](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/js-apis-camera.md) for the API reference.
8
91. Import the media module. The [APIs](../reference/apis/js-apis-media.md) provided by this module are used to obtain the surface ID and create a photo output stream.
10
11   ```ts
12   import { BusinessError } from '@ohos.base';
13   import media from '@ohos.multimedia.media';
14   ```
15
162. Create a surface.
17
18   Call **createAVRecorder()** of the media module to create an **AVRecorder** instance, and call **getInputSurface()** of the instance to obtain the surface ID, which is associated with the view output stream to process the data output by the stream.
19
20   ```ts
21   async function getVideoSurfaceId(aVRecorderConfig: media.AVRecorderConfig): Promise<string | undefined> {  // For details about aVRecorderConfig, see the next section.
22     let avRecorder: media.AVRecorder | undefined;
23     try {
24       avRecorder = await media.createAVRecorder();
25     } catch (error) {
26       let err = error as BusinessError;
27       console.error(`createAVRecorder call failed. error code: ${err.code}`);
28     }
29     if (avRecorder === undefined) {
30       return undefined;
31     }
32     avRecorder.prepare(aVRecorderConfig, (err: BusinessError) => {
33       if (err == null) {
34         console.log('prepare success');
35       } else {
36         console.log('prepare failed and error is ' + err.message);
37       }
38     });
39     let videoSurfaceId = await avRecorder.getInputSurface();
40     return videoSurfaceId;
41   }
42   ```
43
443. Create a video output stream.
45
46   Obtain the video output streams supported by the current device from **videoProfiles** in the **CameraOutputCapability** class. Then, define video recording parameters and use **createVideoOutput()** to create a video output stream.
47
48   **NOTE**: 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.
49
50   ```ts
51   async function getVideoOutput(cameraManager: camera.CameraManager, videoSurfaceId: string, cameraOutputCapability: camera.CameraOutputCapability): Promise<camera.VideoOutput | undefined> {
52     let videoProfilesArray: Array<camera.VideoProfile> = cameraOutputCapability.videoProfiles;
53     if (!videoProfilesArray) {
54       console.error("createOutput videoProfilesArray == null || undefined");
55       return undefined;
56     }
57     // AVRecorderProfile
58     let aVRecorderProfile: media.AVRecorderProfile = {
59       fileFormat: media.ContainerFormatType.CFT_MPEG_4, // Video file encapsulation format. Only MP4 is supported.
60       videoBitrate: 100000, // Video bit rate.
61       videoCodec: media.CodecMimeType.VIDEO_MPEG4, // Video file encoding format. Both MPEG-4 and AVC are supported.
62       videoFrameWidth: 640, // Video frame width.
63       videoFrameHeight: 480, // Video frame height.
64       videoFrameRate: 30 // Video frame rate.
65     }
66     // 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.
67     let aVRecorderConfig: media.AVRecorderConfig = {
68       videoSourceType: media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV,
69       profile: aVRecorderProfile,
70       url: 'fd://35',
71       rotation: 90 // 90° is the default vertical display angle. You can use other values based on project requirements.
72     }
73     // Create an AVRecorder instance.
74     let avRecorder: media.AVRecorder | undefined = undefined;
75     try {
76       avRecorder = await media.createAVRecorder();
77     } catch (error) {
78       let err = error as BusinessError;
79       console.error(`createAVRecorder call failed. error code: ${err.code}`);
80     }
81     if (avRecorder === undefined) {
82       return undefined;
83     }
84     // Set video recording parameters.
85     avRecorder.prepare(aVRecorderConfig);
86     // Create a VideoOutput instance.
87     let videoOutput: camera.VideoOutput | undefined = undefined;
88     try {
89       videoOutput = cameraManager.createVideoOutput(videoProfilesArray[0], videoSurfaceId);
90     } catch (error) {
91       let err = error as BusinessError;
92       console.error('Failed to create the videoOutput instance. errorCode = ' + err.code);
93     }
94     return videoOutput;
95   }
96   ```
97
984. Start video recording.
99
100   Call **start()** of the **VideoOutput** instance to start the video output stream, and then call **start()** of the **AVRecorder** instance to start recording.
101
102   ```ts
103   async function startVideo(videoOutput: camera.VideoOutput, avRecorder: media.AVRecorder): Promise<void> {
104     videoOutput.start(async (err: BusinessError) => {
105       if (err) {
106         console.error('Failed to start the video output ${err.message}');
107         return;
108       }
109       console.info('Callback invoked to indicate the video output start success.');
110     });
111     try {
112       await avRecorder.start();
113     } catch (error) {
114       let err = error as BusinessError;
115       console.error(`avRecorder start error: ${JSON.stringify(err)}`);
116     }
117   }
118   ```
119
1205. Stop video recording.
121
122   Call **stop()** of the **AVRecorder** instance to stop recording, and then call **stop()** of the **VideoOutput** instance to stop the video output stream.
123
124   ```ts
125   async function stopVideo(videoOutput: camera.VideoOutput, avRecorder: media.AVRecorder): Promise<void> {
126     try {
127       await avRecorder.stop();
128     } catch (error) {
129       let err = error as BusinessError;
130       console.error(`avRecorder stop error: ${JSON.stringify(err)}`);
131     }
132     videoOutput.stop((err: BusinessError) => {
133       if (err) {
134         console.error('Failed to stop the video output ${err.message}');
135         return;
136       }
137       console.info('Callback invoked to indicate the video output stop success.');
138     });
139   }
140   ```
141
142
143## Status Listening
144
145During camera application development, you can listen for the status of the video output stream, including recording start, recording end, and recording stream output errors.
146
147- Register the 'frameStart' event to listen for recording start events. This event can be registered when a **VideoOutput** object is created and is triggered when the bottom layer starts exposure for recording for the first time. Video recording is started as long as a result is returned.
148
149  ```ts
150  function onVideoOutputFrameStart(videoOutput: camera.VideoOutput): void {
151    videoOutput.on('frameStart', () => {
152      console.info('Video frame started');
153    });
154  }
155  ```
156
157- Register the 'frameEnd' event to listen for recording end events. This event can be registered when a **VideoOutput** object is created and is triggered when the last frame of recording ends. Video recording ends as long as a result is returned.
158
159  ```ts
160  function onVideoOutputFrameEnd(videoOutput: camera.VideoOutput): void {
161    videoOutput.on('frameEnd', () => {
162      console.info('Video frame ended');
163    });
164  }
165  ```
166
167- 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 [Camera Error Codes](../reference/apis/js-apis-camera.md#cameraerrorcode).
168
169  ```ts
170  function onVideoOutputError(videoOutput: camera.VideoOutput): void {
171    videoOutput.on('error', (error: BusinessError) => {
172      console.info(`Video output error code: ${error.code}`);
173    });
174  }
175  ```
176