harmony 鸿蒙Camera Recording

  • 2023-06-24
  • 浏览 (335)

Camera Recording

Video 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 to set the resolution, flash, focal length, photo quality, and rotation angle.

How to Develop

Read Camera for the API reference.

  1. Import the media module. The APIs provided by this module are used to obtain the surface ID and create a photo output stream.
   import { BusinessError } from '@ohos.base';
   import media from '@ohos.multimedia.media';
  1. Create a surface.

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.

   async function getVideoSurfaceId(aVRecorderConfig: media.AVRecorderConfig): Promise<string|undefined> {  // For details about aVRecorderConfig, see the next section.
     let avRecorder: media.AVRecorder|undefined = undefined;
     try {
       avRecorder = await media.createAVRecorder();
     } catch (error) {
       let err = error as BusinessError;
       console.error(`createAVRecorder call failed. error code: ${err.code}`);
     }
     if (avRecorder === undefined) {
       return undefined;
     }
     avRecorder.prepare(aVRecorderConfig, (err: BusinessError) => {
       if (err == null) {
         console.log('prepare success');
       } else {
         console.log('prepare failed and error is ' + err.message);
       }
     });
     let videoSurfaceId = await avRecorder.getInputSurface();
     return videoSurfaceId;
   }
  1. Create a video output stream.

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.

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.

   async function getVideoOutput(cameraManager: camera.CameraManager, videoSurfaceId: string, cameraOutputCapability: camera.CameraOutputCapability): Promise<camera.VideoOutput|undefined> {
     let videoProfilesArray: Array<camera.VideoProfile> = cameraOutputCapability.videoProfiles;
     if (!videoProfilesArray) {
       console.error("createOutput videoProfilesArray == null||undefined");
       return undefined;
     }
     // AVRecorderProfile
     let aVRecorderProfile: media.AVRecorderProfile = {
       fileFormat: media.ContainerFormatType.CFT_MPEG_4, // Video file encapsulation format. Only MP4 is supported.
       videoBitrate: 100000, // Video bit rate.
       videoCodec: media.CodecMimeType.VIDEO_MPEG4, // Video file encoding format. Both MPEG-4 and AVC are supported.
       videoFrameWidth: 640, // Video frame width.
       videoFrameHeight: 480, // Video frame height.
       videoFrameRate: 30 // Video frame rate.
     };
     // 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.
     let aVRecorderConfig: media.AVRecorderConfig = {
       videoSourceType: media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV,
       profile: aVRecorderProfile,
       url: 'fd://35',
       rotation: 90 // 90° is the default vertical display angle. You can use other values based on project requirements.
     };
     // Create an AVRecorder instance.
     let avRecorder: media.AVRecorder|undefined = undefined;
     try {
       avRecorder = await media.createAVRecorder();
     } catch (error) {
       let err = error as BusinessError;
       console.error(`createAVRecorder call failed. error code: ${err.code}`);
     }
     if (avRecorder === undefined) {
       return undefined;
     }
     // Set video recording parameters.
     avRecorder.prepare(aVRecorderConfig);
     // Create a VideoOutput instance.
     let videoOutput: camera.VideoOutput|undefined = undefined;
     try {
       videoOutput = cameraManager.createVideoOutput(videoProfilesArray[0], videoSurfaceId);
     } catch (error) {
       let err = error as BusinessError;
       console.error('Failed to create the videoOutput instance. errorCode = ' + err.code);
     }
     return videoOutput;
   }
  1. Start video recording.

Call start() of the VideoOutput instance to start the video output stream, and then call start() of the AVRecorder instance to start recording.

   async function startVideo(videoOutput: camera.VideoOutput, avRecorder: media.AVRecorder): Promise<void> {
     videoOutput.start(async (err: BusinessError) => {
       if (err) {
         console.error('Failed to start the video output ${err.message}');
         return;
       }
       console.info('Callback invoked to indicate the video output start success.');
     });
     try {
       await avRecorder.start();
     } catch (error) {
       let err = error as BusinessError;
       console.error(`avRecorder start error: ${JSON.stringify(err)}`);
     }
   }
  1. Stop video recording.

Call stop() of the AVRecorder instance to stop recording, and then call stop() of the VideoOutput instance to stop the video output stream.

   async function stopVideo(videoOutput: camera.VideoOutput, avRecorder: media.AVRecorder): Promise<void> {
     try {
       await avRecorder.stop();
     } catch (error) {
       let err = error as BusinessError;
       console.error(`avRecorder stop error: ${JSON.stringify(err)}`);
     }
     videoOutput.stop((err: BusinessError) => {
       if (err) {
         console.error('Failed to stop the video output ${err.message}');
         return;
       }
       console.info('Callback invoked to indicate the video output stop success.');
     });
   }

Status Listening

During camera application development, you can listen for the status of the video output stream, including recording start, recording end, and recording stream output errors.

  • 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.
  function onVideoOutputFrameStart(videoOutput: camera.VideoOutput): void {
    videoOutput.on('frameStart', () => {
      console.info('Video frame started');
    });
  }
  • 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.
  function onVideoOutputFrameEnd(videoOutput: camera.VideoOutput): void {
    videoOutput.on('frameEnd', () => {
      console.info('Video frame ended');
    });
  }
  • 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.
  function onVideoOutputError(videoOutput: camera.VideoOutput): void {
    videoOutput.on('error', (error: BusinessError) => {
      console.info(`Video output error code: ${error.code}`);
    });
  }

你可能感兴趣的鸿蒙文章

harmony 鸿蒙Media

harmony 鸿蒙Developing Audio Call

harmony 鸿蒙Audio Call Development

harmony 鸿蒙Audio Decoding

harmony 鸿蒙Audio Effect Management

harmony 鸿蒙Audio Encoding

harmony 鸿蒙Audio Input Device Management

harmony 鸿蒙Audio Output Device Management

harmony 鸿蒙Audio Playback Concurrency Policy

harmony 鸿蒙Audio Playback Development

0  赞