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 28 media.createAVRecorder().then((recorder) => { 29 avRecorder = recorder 30 }, (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, reason) => { 44 console.info('current state is: ' + state); 45 }) 46 // Callback function for errors. 47 avRecorder.on('error', (err) => { 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 = { 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 = { 74 videoSourceType: media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV, // Video source type. YUV and ES are supported. 75 profile : this.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) => { 82 console.error('avRecorder prepare failed') 83 }) 84 ``` 85 864. Obtain the surface ID required for video recording. 87 88 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. 89 90 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. 91 92 ```ts 93 avRecorder.getInputSurface().then((surfaceId) => { 94 console.info('avRecorder getInputSurface success') 95 }, (error) => { 96 console.error('avRecorder getInputSurface failed') 97 }) 98 ``` 99 1005. Initialize the video data input source. 101 102 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). 103 1046. Start recording. 105 106 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. 107 1087. 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**. 109 1108. Call **resume()** to resume recording. The AVRecorder enters the **started** state again. 111 1129. Call **stop()** to stop recording. The AVRecorder enters the **stopped** state again. In addition, stop camera recording in the video data collection module. 113 11410. Call **reset()** to reset the resources. The AVRecorder enters the **idle** state. In this case, you can reconfigure the recording parameters. 115 11611. 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). 117 118 119## Sample Code 120 121Refer to the sample code below to complete the process of starting, pausing, resuming, and stopping recording. 122 123 124```ts 125import media from '@ohos.multimedia.media' 126const TAG = 'VideoRecorderDemo:' 127export class VideoRecorderDemo { 128 private avRecorder; 129 private videoOutSurfaceId; 130 private avProfile = { 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 = { 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 // Callback function for state changes. 148 this.avRecorder.on('stateChange', (state, reason) => { 149 console.info(TAG + 'current state is: ' + state); 150 }) 151 // Callback function for errors. 152 this.avRecorder.on('error', (err) => { 153 console.error(TAG + 'error ocConstantSourceNode, error message is ' + err); 154 }) 155 } 156 157 // Complete camera-related preparations. 158 async prepareCamera() { 159 // For details on the implementation, see the camera document. 160 } 161 162 // Start the camera stream output. 163 async startCameraOutput() { 164 // Call start of the VideoOutput class to start video output. 165 } 166 167 // Stop the camera stream output. 168 async stopCameraOutput() { 169 // Call stop of the VideoOutput class to stop video output. 170 } 171 172 // Release the camera instance. 173 async releaseCamera() { 174 // Release the instances created during camera preparation. 175 } 176 177 // Process of starting recording. 178 async startRecordingProcess() { 179 // 1. Create an AVRecorder instance. 180 this.avRecorder = await media.createAVRecorder(); 181 this.setAvRecorderCallback(); 182 // 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. 183 // 3. Set recording parameters to complete the preparations. 184 await this.avRecorder.prepare(this.avConfig); 185 this.videoOutSurfaceId = await this.avRecorder.getInputSurface(); 186 // 4. Complete camera-related preparations. 187 await this.prepareCamera(); 188 // 5. Start the camera stream output. 189 await this.startCameraOutput(); 190 // 6. Start recording. 191 await this.videoRecorder.start(); 192 } 193 194 // Process of pausing recording. 195 async pauseRecordingProcess() { 196 if (this.avRecorder.state ==='started') { // pause() can be called only when the AVRecorder is in the started state . 197 await this.avRecorder.pause(); 198 await this.stopCameraOutput(); // Stop the camera stream output. 199 } 200 } 201 202 // Process of resuming recording. 203 async resumeRecordingProcess() { 204 if (this.avRecorder.state === 'paused') { // resume() can be called only when the AVRecorder is in the paused state . 205 await this.startCameraOutput(); // Start camera stream output. 206 await this.avRecorder.resume(); 207 } 208 } 209 210 async stopRecordingProcess() { 211 // 1. Stop recording. 212 if (this.avRecorder.state === 'started' 213 || this.avRecorder.state ==='paused') { // stop() can be called only when the AVRecorder is in the started or paused state. 214 await this.avRecorder.stop(); 215 await this.stopCameraOutput(); 216 } 217 // 2. Reset the AVRecorder. 218 await this.avRecorder.reset(); 219 // 3. Release the AVRecorder instance. 220 await this.avRecorder.release(); 221 // 4. After the file is recorded, close the file descriptor. The implementation is omitted here. 222 // 5. Release the camera instance. 223 await this.releaseCamera(); 224 } 225 226 // Complete sample code for starting, pausing, resuming, and stopping recording. 227 async videoRecorderDemo() { 228 await this.startRecordingProcess(); // Start recording. 229 // You can set the recording duration. For example, you can set the sleep mode to prevent code execution. 230 await this.pauseRecordingProcess(); // Pause recording. 231 await this.resumeRecordingProcess(); // Resume recording. 232 await this.stopRecordingProcess(); // Stop recording. 233 } 234} 235``` 236