• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Video Recording (ArkTS)
2
3The system provides the AVRecorder for you to develop the video recording service. The AVRecorder supports audio recording, audio encoding, video encoding, audio encapsulation, and video encapsulation. It is applicable to simple video recording scenarios and can be used to generate local video files directly.
4
5You will learn how to use the AVRecorder to complete the process of starting, pausing, resuming, and stopping recording.
6
7During application development, you can use the **state** attribute of the AVRecorder to obtain the AVRecorder state or call **on('stateChange')** to listen for state changes. Your code must meet the state machine requirements. For example, **pause()** is called only when the AVRecorder is in the **started** state, and **resume()** is called only when it is in the **paused** state.
8
9**Figure 1** Recording state transition
10
11![Recording state change](figures/video-recording-status-change.png)
12
13For details about the state, see [AVRecorderState](../reference/apis/js-apis-media.md#avrecorderstate9).
14
15## How to Develop
16
17> **NOTE**
18>
19> The AVRecorder only processes video data. To complete video recording, it must work with the video data collection module, which transfers the captured video data to the AVRecorder for data processing through the surface. A typical video data collection module is the camera module, which currently is available only to system applications. For details, see [Camera](../reference/apis/js-apis-camera.md).
20
21Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API reference.
22
231. Create an **AVRecorder** instance. The AVRecorder is the **idle** state.
24
25   ```ts
26   import media from '@ohos.multimedia.media';
27
28   let avRecorder: media.AVRecorder;
29   media.createAVRecorder().then((recorder: media.AVRecorder) => {
30     avRecorder = recorder;
31   }, (error: Error) => {
32     console.error('createAVRecorder failed');
33   })
34   ```
35
362. Set the events to listen for.
37   | Event Type| Description|
38   | -------- | -------- |
39   | stateChange | Mandatory; used to listen for changes of the **state** attribute of the AVRecorder.|
40   | error | Mandatory; used to listen for AVRecorder errors.|
41
42   ```ts
43   import media from '@ohos.multimedia.media';
44
45   // Callback function for state changes.
46   avRecorder.on('stateChange', (state: media.AVRecorderState, reason: media.StateChangeReason) => {
47     console.info('current state is: ' + state);
48   })
49   // Callback function for errors.
50   avRecorder.on('error', (err: BusinessError) => {
51     console.error('error happened, error message is ' + err);
52   })
53   ```
54
553. Set video recording parameters and call **prepare()**. The AVRecorder enters the **prepared** state.
56   > **NOTE**
57   >
58   > Pay attention to the following when configuring parameters:
59   >
60   > - In pure video recording scenarios, set only video-related parameters in **avConfig** of **prepare()**.
61   >   If audio-related parameters are configured, the system regards it as audio and video recording.
62   >
63   > - The [recording specifications](avplayer-avrecorder-overview.md#supported-formats) in use must be those supported. The video bit rate, resolution, and frame rate are subject to the ranges supported by the hardware device.
64   >
65   > - The recording output URL (URL in **avConfig** in the sample code) must be in the format of fd://xx (where xx indicates a file descriptor). You must call [ohos.file.fs](../reference/apis/js-apis-file-fs.md) to implement access to the application file. For details, see [Application File Access and Management](../file-management/app-file-access.md).
66
67   ```ts
68   import media from '@ohos.multimedia.media';
69   import { BusinessError } from '@ohos.base';
70
71   let avProfile: media.AVRecorderProfile = {
72     fileFormat: media.ContainerFormatType.CFT_MPEG_4, // Video file encapsulation format. Only MP4 is supported.
73     videoBitrate: 200000, // Video bit rate.
74     videoCodec: media.CodecMimeType.VIDEO_MPEG4, // Video file encoding format. Both MPEG-4 and AVC are supported.
75     videoFrameWidth: 640, // Video frame width.
76     videoFrameHeight: 480, // Video frame height.
77     videoFrameRate: 30 // Video frame rate.
78   }
79   let avConfig: media.AVRecorderConfig = {
80     videoSourceType: media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV, // Video source type. YUV and ES are supported.
81     profile : avProfile,
82     url: 'fd://35', // Create, read, and write a file by referring to the sample code in Application File Access and Management.
83     rotation: 0 // Video rotation angle. The default value is 0, indicating that the video is not rotated. The value can be 0, 90, 180, or 270.
84   }
85   avRecorder.prepare(avConfig).then(() => {
86     console.info('avRecorder prepare success');
87   }, (error: BusinessError) => {
88     console.error('avRecorder prepare failed');
89   })
90   ```
91
924. Obtain the surface ID required for video recording.
93
94   Call **getInputSurface()**. The returned surface ID is transferred to the video data collection module (video input source), which is the camera module in the sample code.
95
96   The video data collection module obtains the surface based on the surface ID and transmits video data to the AVRecorder through the surface. Then the AVRecorder processes the video data.
97
98   ```ts
99   import { BusinessError } from '@ohos.base';
100
101   avRecorder.getInputSurface().then((surfaceId: string) => {
102     console.info('avRecorder getInputSurface success');
103   }, (error: BusinessError) => {
104     console.error('avRecorder getInputSurface failed');
105   })
106   ```
107
1085. Initialize the video data input source.
109
110   This step is performed in the video data collection module. For the camera module, you need to create a **Camera** instance, obtain the camera list, create a camera input stream, and create a video output stream. For details, see [Camera Recording](camera-recording.md).
111
1126. Start recording.
113
114   Start the input source to input video data, for example, by calling **camera.VideoOutput.start**. Then call **AVRecorder.start()** to switch the AVRecorder to the **started** state.
115
1167. Call **pause()** to pause recording. The AVRecorder enters the **paused** state. In addition, pause data input in the video data collection module, for example, by calling **camera.VideoOutput.stop**.
117
1188. Call **resume()** to resume recording. The AVRecorder enters the **started** state again.
119
1209. Call **stop()** to stop recording. The AVRecorder enters the **stopped** state again. In addition, stop camera recording in the video data collection module.
121
12210. Call **reset()** to reset the resources. The AVRecorder enters the **idle** state. In this case, you can reconfigure the recording parameters.
123
12411. Call **release()** to release the resources. The AVRecorder enters the **released** state. In addition, release the video data input source resources (camera resources in this example).
125
126
127## Sample Code
128
129Refer to the sample code below to complete the process of starting, pausing, resuming, and stopping recording.
130
131
132```ts
133import media from '@ohos.multimedia.media';
134import { BusinessError } from '@ohos.base';
135
136const TAG = 'VideoRecorderDemo:';
137export class VideoRecorderDemo {
138  private avRecorder: media.AVRecorder | undefined = undefined;
139  private videoOutSurfaceId: string = "";
140  private avProfile: media.AVRecorderProfile = {
141    fileFormat: media.ContainerFormatType.CFT_MPEG_4, // Video file encapsulation format. Only MP4 is supported.
142    videoBitrate : 100000, // Video bit rate.
143    videoCodec: media.CodecMimeType.VIDEO_MPEG4, // Video file encoding format. Both MPEG-4 and AVC are supported.
144    videoFrameWidth: 640, // Video frame width.
145    videoFrameHeight: 480, // Video frame height.
146    videoFrameRate: 30 // Video frame rate.
147  }
148  private avConfig: media.AVRecorderConfig = {
149    videoSourceType: media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV, // Video source type. YUV and ES are supported.
150    profile : this.avProfile,
151    url: 'fd://35', // Create, read, and write a file by referring to the sample code in Application File Access and Management.
152    rotation: 0 // Video rotation angle. The default value is 0, indicating that the video is not rotated. The value can be 0, 90, 180, or 270.
153  }
154
155  // Set AVRecorder callback functions.
156  setAvRecorderCallback() {
157    if (this.avRecorder != undefined) {
158      // Callback function for state changes.
159      this.avRecorder.on('stateChange', (state: media.AVRecorderState, reason: media.StateChangeReason) => {
160        console.info(TAG + 'current state is: ' + state);
161      })
162      // Callback function for errors.
163      this.avRecorder.on('error', (err: BusinessError) => {
164        console.error(TAG + 'error ocConstantSourceNode, error message is ' + err);
165      })
166    }
167  }
168
169  // Complete camera-related preparations.
170  async prepareCamera() {
171    // For details on the implementation, see the camera document.
172  }
173
174  // Start the camera stream output.
175  async startCameraOutput() {
176    // Call start of the VideoOutput class to start video output.
177  }
178
179  // Stop the camera stream output.
180  async stopCameraOutput() {
181    // Call stop of the VideoOutput class to stop video output.
182  }
183
184  // Release the camera instance.
185  async releaseCamera() {
186    // Release the instances created during camera preparation.
187  }
188
189  // Process of starting recording.
190  async startRecordingProcess() {
191    if (this.avRecorder != undefined) {
192      // 1. Create an AVRecorder instance.
193      this.avRecorder = await media.createAVRecorder();
194      this.setAvRecorderCallback();
195      // 2. Obtain the file descriptor of the recorded file. The obtained file descriptor is passed in to the URL in avConfig. The implementation is omitted here.
196      // 3. Set recording parameters to complete the preparations.
197      await this.avRecorder.prepare(this.avConfig);
198      this.videoOutSurfaceId = await this.avRecorder.getInputSurface();
199      // 4. Complete camera-related preparations.
200      await this.prepareCamera();
201      // 5. Start the camera stream output.
202      await this.startCameraOutput();
203      // 6. Start recording.
204      await this.avRecorder.start();
205    }
206  }
207
208  // Process of pausing recording.
209  async pauseRecordingProcess() {
210    if (this.avRecorder != undefined && this.avRecorder.state === 'started') { // pause() can be called only when the AVRecorder is in the started state .
211      await this.avRecorder.pause();
212      await this.stopCameraOutput(); // Stop the camera stream output.
213    }
214  }
215
216  // Process of resuming recording.
217  async resumeRecordingProcess() {
218    if (this.avRecorder != undefined && this.avRecorder.state === 'paused') { // resume() can be called only when the AVRecorder is in the paused state .
219      await this.startCameraOutput(); // Start camera stream output.
220      await this.avRecorder.resume();
221    }
222  }
223
224  async stopRecordingProcess() {
225    if (this.avRecorder != undefined) {
226      // 1. Stop recording.
227      if (this.avRecorder.state === 'started'
228        || this.avRecorder.state ==='paused') { // stop() can be called only when the AVRecorder is in the started or paused state.
229        await this.avRecorder.stop();
230        await this.stopCameraOutput();
231      }
232      // 2. Reset the AVRecorder.
233      await this.avRecorder.reset();
234      // 3. Release the AVRecorder instance.
235      await this.avRecorder.release();
236      // 4. After the file is recorded, close the file descriptor. The implementation is omitted here.
237      // 5. Release the camera instance.
238      await this.releaseCamera();
239    }
240  }
241
242  // Complete sample code for starting, pausing, resuming, and stopping recording.
243  async videoRecorderDemo() {
244    await this.startRecordingProcess();         // Start recording.
245    // You can set the recording duration. For example, you can set the sleep mode to prevent code execution.
246    await this.pauseRecordingProcess();         // Pause recording.
247    await this.resumeRecordingProcess();        // Resume recording.
248    await this.stopRecordingProcess();          // Stop recording.
249  }
250}
251```
252