• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Camera Recording Sample (ArkTS)
2
3This topic provides sample code that covers the complete recording process to help you understand the complete API calling sequence. Before referring to the sample code, you are advised to read [Device Input Management](camera-device-input.md), [Camera Session Management](camera-session-management.md), [Camera Recording](camera-recording.md), and other related topics in [Camera Development (ArkTS)](camera-preparation.md).
4
5## Development Process
6
7After obtaining the output stream capabilities supported by the camera, create a video stream. The development process is as follows:
8
9![Recording Development Process](figures/recording-development-process.png)
10
11
12## Sample Code
13For details about how to obtain the context, see [Obtaining the Context of UIAbility](../application-models/uiability-usage.md#obtaining-the-context-of-uiability).
14
15```ts
16import camera from '@ohos.multimedia.camera';
17import { BusinessError } from '@ohos.base';
18import media from '@ohos.multimedia.media';
19import common from '@ohos.app.ability.common';
20
21async function videoRecording(baseContext: common.BaseContext, surfaceId: string): Promise<void> {
22  // Create a CameraManager instance.
23  let cameraManager: camera.CameraManager = camera.getCameraManager(baseContext);
24  if (!cameraManager) {
25    console.error("camera.getCameraManager error");
26    return;
27  }
28
29  // Listen for camera status changes.
30  cameraManager.on('cameraStatus', (err: BusinessError, cameraStatusInfo: camera.CameraStatusInfo) => {
31    console.info(`camera : ${cameraStatusInfo.camera.cameraId}`);
32    console.info(`status: ${cameraStatusInfo.status}`);
33  });
34
35  // Obtain the camera list.
36  let cameraArray: Array<camera.CameraDevice> = [];
37  try {
38    cameraArray = cameraManager.getSupportedCameras();
39  } catch (error) {
40    let err = error as BusinessError;
41    console.error(`getSupportedCameras call failed. error code: ${err.code}`);
42  }
43
44  if (cameraArray.length <= 0) {
45    console.error("cameraManager.getSupportedCameras error");
46    return;
47  }
48
49  // Obtain the output stream capabilities supported by the camera.
50  let cameraOutputCap: camera.CameraOutputCapability = cameraManager.getSupportedOutputCapability(cameraArray[0]);
51  if (!cameraOutputCap) {
52    console.error("cameraManager.getSupportedOutputCapability error")
53    return;
54  }
55  console.info("outputCapability: " + JSON.stringify(cameraOutputCap));
56
57  let previewProfilesArray: Array<camera.Profile> = cameraOutputCap.previewProfiles;
58  if (!previewProfilesArray) {
59    console.error("createOutput previewProfilesArray == null || undefined");
60  }
61
62  let photoProfilesArray: Array<camera.Profile> = cameraOutputCap.photoProfiles;
63  if (!photoProfilesArray) {
64    console.error("createOutput photoProfilesArray == null || undefined");
65  }
66
67  let videoProfilesArray: Array<camera.VideoProfile> = cameraOutputCap.videoProfiles;
68  if (!videoProfilesArray) {
69    console.error("createOutput videoProfilesArray == null || undefined");
70  }
71
72  let metadataObjectTypesArray: Array<camera.MetadataObjectType> = cameraOutputCap.supportedMetadataObjectTypes;
73  if (!metadataObjectTypesArray) {
74    console.error("createOutput metadataObjectTypesArray == null || undefined");
75  }
76
77  // Configure the parameters based on those supported by the hardware device.
78  let aVRecorderProfile: media.AVRecorderProfile = {
79    audioBitrate: 48000,
80    audioChannels: 2,
81    audioCodec: media.CodecMimeType.AUDIO_AAC,
82    audioSampleRate: 48000,
83    fileFormat: media.ContainerFormatType.CFT_MPEG_4,
84    videoBitrate: 2000000,
85    videoCodec: media.CodecMimeType.VIDEO_MPEG4,
86    videoFrameWidth: 640,
87    videoFrameHeight: 480,
88    videoFrameRate: 30
89  };
90  let aVRecorderConfig: media.AVRecorderConfig = {
91    audioSourceType: media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC,
92    videoSourceType: media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV,
93    profile: aVRecorderProfile,
94    url: 'fd://', // Before passing in a file descriptor to this parameter, the file must be created by the caller and granted with the read and write permissions. Example value: fd://45--file:///data/media/01.mp4.
95    rotation: 0, // The value can be 0, 90, 180, or 270. If any other value is used, prepare() reports an error.
96    location: { latitude: 30, longitude: 130 }
97  };
98
99  let avRecorder: media.AVRecorder | undefined = undefined;
100  try {
101    avRecorder = await media.createAVRecorder();
102  } catch (error) {
103    let err = error as BusinessError;
104    console.error(`createAVRecorder call failed. error code: ${err.code}`);
105  }
106
107  if (avRecorder === undefined) {
108    return;
109  }
110
111  try {
112    await avRecorder.prepare(aVRecorderConfig);
113  } catch (error) {
114    let err = error as BusinessError;
115    console.error(`prepare call failed. error code: ${err.code}`);
116  }
117
118  let videoSurfaceId: string | undefined = undefined; // The surfaceID is passed in to the camera API to create a VideoOutput instance.
119  try {
120    videoSurfaceId = await avRecorder.getInputSurface();
121  } catch (error) {
122    let err = error as BusinessError;
123    console.error(`getInputSurface call failed. error code: ${err.code}`);
124  }
125  if (videoSurfaceId === undefined) {
126    return;
127  }
128  // Create a VideoOutput instance.
129  let videoOutput: camera.VideoOutput | undefined = undefined;
130  try {
131    videoOutput = cameraManager.createVideoOutput(videoProfilesArray[0], videoSurfaceId);
132  } catch (error) {
133    let err = error as BusinessError;
134    console.error(`Failed to create the videoOutput instance. error: ${JSON.stringify(err)}`);
135  }
136  if (videoOutput === undefined) {
137    return;
138  }
139  // Listen for video output errors.
140  videoOutput.on('error', (error: BusinessError) => {
141    console.info(`Preview output error code: ${error.code}`);
142  });
143
144  // Create a session.
145  let captureSession: camera.CaptureSession | undefined = undefined;
146  try {
147    captureSession = cameraManager.createCaptureSession();
148  } catch (error) {
149    let err = error as BusinessError;
150    console.error(`Failed to create the CaptureSession instance. error: ${JSON.stringify(err)}`);
151  }
152  if (captureSession === undefined) {
153    return;
154  }
155  // Listen for session errors.
156  captureSession.on('error', (error: BusinessError) => {
157    console.info(`Capture session error code: ${error.code}`);
158  });
159
160  // Start configuration for the session.
161  try {
162    captureSession.beginConfig();
163  } catch (error) {
164    let err = error as BusinessError;
165    console.error(`Failed to beginConfig. error: ${JSON.stringify(err)}`);
166  }
167
168  // Create a camera input stream.
169  let cameraInput: camera.CameraInput | undefined = undefined;
170  try {
171    cameraInput = cameraManager.createCameraInput(cameraArray[0]);
172  } catch (error) {
173    let err = error as BusinessError;
174    console.error(`Failed to createCameraInput. error: ${JSON.stringify(err)}`);
175  }
176  if (cameraInput === undefined) {
177    return;
178  }
179  // Listen for camera input errors.
180  let cameraDevice: camera.CameraDevice = cameraArray[0];
181  cameraInput.on('error', cameraDevice, (error: BusinessError) => {
182    console.info(`Camera input error code: ${error.code}`);
183  });
184
185  // Open the camera.
186  try {
187    await cameraInput.open();
188  } catch (error) {
189    let err = error as BusinessError;
190    console.error(`Failed to open cameraInput. error: ${JSON.stringify(err)}`);
191  }
192
193  // Add the camera input stream to the session.
194  try {
195    captureSession.addInput(cameraInput);
196  } catch (error) {
197    let err = error as BusinessError;
198    console.error(`Failed to add cameraInput. error: ${JSON.stringify(err)}`);
199  }
200
201  // Create a preview output stream. For details about the surfaceId parameter, see the <XComponent>. The preview stream is the surface provided by the <XComponent>.
202  let previewOutput: camera.PreviewOutput | undefined = undefined;
203  try {
204    previewOutput = cameraManager.createPreviewOutput(previewProfilesArray[0], surfaceId);
205  } catch (error) {
206    let err = error as BusinessError;
207    console.error(`Failed to create the PreviewOutput instance. error: ${JSON.stringify(err)}`);
208  }
209
210  if (previewOutput === undefined) {
211    return;
212  }
213  // Add the preview input stream to the session.
214  try {
215    captureSession.addOutput(previewOutput);
216  } catch (error) {
217    let err = error as BusinessError;
218    console.error(`Failed to add previewOutput. error: ${JSON.stringify(err)}`);
219  }
220
221  // Add a video output stream to the session.
222  try {
223    captureSession.addOutput(videoOutput);
224  } catch (error) {
225    let err = error as BusinessError;
226    console.error(`Failed to add videoOutput. error: ${JSON.stringify(err)}`);
227  }
228
229  // Commit the session configuration.
230  try {
231    await captureSession.commitConfig();
232  } catch (error) {
233    let err = error as BusinessError;
234    console.error(`captureSession commitConfig error: ${JSON.stringify(err)}`);
235  }
236
237  // Start the session.
238  try {
239    await captureSession.start();
240  } catch (error) {
241    let err = error as BusinessError;
242    console.error(`captureSession start error: ${JSON.stringify(err)}`);
243  }
244
245  // Start the video output stream.
246  videoOutput.start((err: BusinessError) => {
247    if (err) {
248      console.error(`Failed to start the video output. error: ${JSON.stringify(err)}`);
249      return;
250    }
251    console.info('Callback invoked to indicate the video output start success.');
252  });
253
254  // Start video recording.
255  try {
256    await avRecorder.start();
257  } catch (error) {
258    let err = error as BusinessError;
259    console.error(`avRecorder start error: ${JSON.stringify(err)}`);
260  }
261
262  // Stop the video output stream.
263  videoOutput.stop((err: BusinessError) => {
264    if (err) {
265      console.error(`Failed to stop the video output. error: ${JSON.stringify(err)}`);
266      return;
267    }
268    console.info('Callback invoked to indicate the video output stop success.');
269  });
270
271  // Stop video recording.
272  try {
273    await avRecorder.stop();
274  } catch (error) {
275    let err = error as BusinessError;
276    console.error(`avRecorder stop error: ${JSON.stringify(err)}`);
277  }
278
279  // Stop the session.
280  captureSession.stop();
281
282  // Release the camera input stream.
283  cameraInput.close();
284
285  // Release the preview output stream.
286  previewOutput.release();
287
288  // Release the video output stream.
289  videoOutput.release();
290
291  // Release the session.
292  captureSession.release();
293
294  // Set the session to null.
295  captureSession = undefined;
296}
297```
298