• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Video Recording
2
3OpenHarmony 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   let avRecorder: media.AVRecorder;
28   media.createAVRecorder().then((recorder: media.AVRecorder) => {
29     avRecorder = recorder
30   }, (error: Error) => {
31     console.error('createAVRecorder failed')
32   })
33   ```
34
352. Set the events to listen for.
36   | Event Type| Description|
37   | -------- | -------- |
38   | stateChange | Mandatory; used to listen for changes of the **state** attribute of the AVRecorder.|
39   | error | Mandatory; used to listen for AVRecorder errors.|
40
41   ```ts
42   // Callback function for state changes.
43   avRecorder.on('stateChange', (state: media.AVRecorderState, reason: media.StateChangeReason) => {
44     console.info('current state is: ' + state);
45   })
46   // Callback function for errors.
47   avRecorder.on('error', (err: BusinessError) => {
48     console.error('error happened, error message is ' + err);
49   })
50   ```
51
523. Set video recording parameters and call **prepare()**. The AVRecorder enters the **prepared** state.
53   > **NOTE**
54   >
55   > Pay attention to the following when configuring parameters:
56   >
57   > - In pure video recording scenarios, set only video-related parameters in **avConfig** of **prepare()**.
58   >   If audio-related parameters are configured, the system regards it as audio and video recording.
59   >
60   > - 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.
61   >
62   > - 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).
63
64   ```ts
65   let avProfile: media.AVRecorderProfile = {
66     fileFormat: media.ContainerFormatType.CFT_MPEG_4, // Video file encapsulation format. Only MP4 is supported.
67     videoBitrate: 200000, // Video bit rate.
68     videoCodec: media.CodecMimeType.VIDEO_AVC, // Video file encoding format. Both MPEG-4 and AVC are supported.
69     videoFrameWidth: 640, // Video frame width.
70     videoFrameHeight: 480, // Video frame height.
71     videoFrameRate: 30 // Video frame rate.
72   }
73   let avConfig: media.AVRecorderConfig = {
74     videoSourceType: media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV, // Video source type. YUV and ES are supported.
75     profile : avProfile,
76     url: 'fd://35', // Create, read, and write a file by referring to the sample code in Application File Access and Management.
77     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.
78   }
79   avRecorder.prepare(avConfig).then(() => {
80     console.info('avRecorder prepare success')
81   }, (error: Error) => {
82     console.error('avRecorder prepare failed')
83   })
84   ```
85
864. Obtain the surface ID required for video recording.
87   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.
88
89     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.
90
91   ```ts
92   avRecorder.getInputSurface().then((surfaceId: string) => {
93     console.info('avRecorder getInputSurface success')
94   }, (error: Error) => {
95     console.error('avRecorder getInputSurface failed')
96   })
97   ```
98
995. Initialize the video data input source.
100
101   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 [Recording](camera-recording-case.md).
102
1036. Start recording.
104
105   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.
106
1077. 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**.
108
1098. Call **resume()** to resume recording. The AVRecorder enters the **started** state again.
110
1119. Call **stop()** to stop recording. The AVRecorder enters the **stopped** state again. In addition, stop camera recording in the video data collection module.
112
11310. Call **reset()** to reset the resources. The AVRecorder enters the **idle** state. In this case, you can reconfigure the recording parameters.
114
11511. 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).
116
117
118## Sample Code
119
120Refer to the sample code below to complete the process of starting, pausing, resuming, and stopping recording.
121
122
123```ts
124import media from '@ohos.multimedia.media'
125import { BusinessError } from '@ohos.base';
126const TAG = 'VideoRecorderDemo:'
127export class VideoRecorderDemo {
128  private avRecorder: media.AVRecorder | undefined = undefined;
129  private videoOutSurfaceId: string = "";
130  private avProfile: media.AVRecorderProfile = {
131    fileFormat: media.ContainerFormatType.CFT_MPEG_4, // Video file encapsulation format. Only MP4 is supported.
132    videoBitrate : 100000, // Video bit rate.
133    videoCodec: media.CodecMimeType.VIDEO_AVC, // Video file encoding format. Both MPEG-4 and AVC are supported.
134    videoFrameWidth: 640, // Video frame width.
135    videoFrameHeight: 480, // Video frame height.
136    videoFrameRate: 30 // Video frame rate.
137  }
138  private avConfig: media.AVRecorderConfig = {
139    videoSourceType: media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV, // Video source type. YUV and ES are supported.
140    profile : this.avProfile,
141    url: 'fd://35', // Create, read, and write a file by referring to the sample code in Application File Access and Management.
142    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.
143  }
144
145  // Set AVRecorder callback functions.
146  setAvRecorderCallback() {
147    if (this.avRecorder != undefined) {
148      // Callback function for state changes.
149      this.avRecorder.on('stateChange', (state: media.AVRecorderState, reason: media.StateChangeReason) => {
150        console.info(TAG + 'current state is: ' + state);
151      })
152      // Callback function for errors.
153      this.avRecorder.on('error', (err: BusinessError) => {
154        console.error(TAG + 'error ocConstantSourceNode, error message is ' + err);
155      })
156    }
157  }
158
159  // Complete camera-related preparations.
160  async prepareCamera() {
161    // For details on the implementation, see the camera document.
162  }
163
164  // Start the camera stream output.
165  async startCameraOutput() {
166    // Call start of the VideoOutput class to start video output.
167  }
168
169  // Stop the camera stream output.
170  async stopCameraOutput() {
171    // Call stop of the VideoOutput class to stop video output.
172  }
173
174  // Release the camera instance.
175  async releaseCamera() {
176    // Release the instances created during camera preparation.
177  }
178
179  // Process of starting recording.
180  async startRecordingProcess() {
181    if (this.avRecorder != undefined) {
182      // 1. Create an AVRecorder instance.
183      this.avRecorder = await media.createAVRecorder();
184      this.setAvRecorderCallback();
185      // 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.
186      // 3. Set recording parameters to complete the preparations.
187      await this.avRecorder.prepare(this.avConfig);
188      this.videoOutSurfaceId = await this.avRecorder.getInputSurface();
189      // 4. Complete camera-related preparations.
190      await this.prepareCamera();
191      // 5. Start the camera stream output.
192      await this.startCameraOutput();
193      // 6. Start recording.
194      await this.avRecorder.start();
195    }
196  }
197
198  // Process of pausing recording.
199  async pauseRecordingProcess() {
200    if (this.avRecorder != undefined && this.avRecorder.state === 'started') { // pause() can be called only when the AVRecorder is in the started state .
201      await this.avRecorder.pause();
202      await this.stopCameraOutput(); // Stop the camera stream output.
203    }
204  }
205
206  // Process of resuming recording.
207  async resumeRecordingProcess() {
208    if (this.avRecorder != undefined && this.avRecorder.state === 'paused') { // resume() can be called only when the AVRecorder is in the paused state .
209      await this.startCameraOutput(); // Start camera stream output.
210      await this.avRecorder.resume();
211    }
212  }
213
214  async stopRecordingProcess() {
215    if (this.avRecorder != undefined) {
216      // 1. Stop recording.
217      if (this.avRecorder.state === 'started'
218        || this.avRecorder.state ==='paused') { // stop() can be called only when the AVRecorder is in the started or paused state.
219        await this.avRecorder.stop();
220        await this.stopCameraOutput();
221      }
222      // 2. Reset the AVRecorder.
223      await this.avRecorder.reset();
224      // 3. Release the AVRecorder instance.
225      await this.avRecorder.release();
226      // 4. After the file is recorded, close the file descriptor. The implementation is omitted here.
227      // 5. Release the camera instance.
228      await this.releaseCamera();
229    }
230  }
231
232  // Complete sample code for starting, pausing, resuming, and stopping recording.
233  async videoRecorderDemo() {
234    await this.startRecordingProcess();         // Start recording.
235    // You can set the recording duration. For example, you can set the sleep mode to prevent code execution.
236    await this.pauseRecordingProcess();         // Pause recording.
237    await this.resumeRecordingProcess();        // Resume recording.
238    await this.stopRecordingProcess();          // Stop recording.
239  }
240}
241```
242