在开发相机应用时,需要先申请相关权限。
相机应用可通过调用和控制相机设备,完成预览、拍照和录像等基础操作。
录像也是相机应用的最重要功能之一,录像是循环帧的捕获。对于录像的自定义配置,开发者可以参考拍照中的步骤4,设置分辨率、闪光灯、焦距、照片质量及旋转角度等信息。
开发步骤
详细的API说明请参考@ohos.multimedia.camera (相机管理)。
-
导入media模块。
创建录像输出流的SurfaceId以及录像输出的数据,都需要用到系统提供的media接口@ohos.multimedia.media (媒体服务)能力,导入media接口的方法如下。
import { BusinessError } from '@kit.BasicServicesKit';
import { camera } from '@kit.CameraKit';
import { media } from '@kit.MediaKit'; -
创建Surface。
系统提供的media接口可以创建一个录像AVRecorder实例,通过该实例的getInputSurface方法获取SurfaceId,与录像输出流做关联,处理录像输出流输出的数据。
this.avRecorder = await this.createAVRecorder();
if (this.avRecorder === undefined) {
Logger.error(TAG, 'Failed to create the avRecorder.');
return;
}
await this.prepareAVRecorder();
let videoSurfaceId = await this.avRecorder.getInputSurface(); -
创建录像输出流。
通过CameraOutputCapability中的videoProfiles属性,可获取当前设备支持的录像输出流。然后,定义创建录像的参数,通过createVideoOutput方法创建录像输出流。
createVideoOutputFn(cameraManager: camera.CameraManager, videoProfileObj: camera.VideoProfile,
surfaceId: string): camera.VideoOutput | undefined {
let videoOutput: camera.VideoOutput | undefined = undefined;
try {
videoOutput = cameraManager.createVideoOutput(videoProfileObj, surfaceId);
Logger.info(TAG, `createVideoOutputFn success: ${videoOutput}`);
} catch (error) {
let err = error as BusinessError;
Logger.error(TAG, `createVideoOutputFn failed: ${err.code}`);
}
return videoOutput;
} -
开始录像。
先通过videoOutput的start方法启动录像输出流,再通过avRecorder的start方法开始录像。
async startVideo(): Promise<void> {
Logger.info(TAG, 'startVideo is called');
try {
await this.videoOutput?.start();
await this.avRecorder?.start();
this.isRecording = true;
} catch (error) {
let err = error as BusinessError;
Logger.error(TAG, `startVideo err: ${err.code}`);
}
Logger.info(TAG, 'startVideo End of call');
} -
停止录像。
先通过avRecorder的stop方法停止录像,再通过videoOutput的stop方法停止录像输出流。
async stopVideo(): Promise<void> {
Logger.info(TAG, 'stopVideo is called');
if (!this.isRecording) {
Logger.info(TAG, 'not in recording');
return;
}
try {
if (this.avRecorder) {
await this.avRecorder.stop();
}
if (this.videoOutput) {
await this.videoOutput.stop();
}
this.isRecording = false;
} catch (error) {
let err = error as BusinessError;
Logger.error(TAG, `stopVideo err: ${err.code}`);
}
Logger.info(TAG, 'stopVideo End of call');
}
状态监听
在相机应用开发过程中,可以随时监听录像输出流状态,包括录像开始、录像结束、录像流输出的错误。
-
通过注册固定的frameStart回调函数获取监听录像开始结果,videoOutput创建成功时即可监听,录像第一次曝光时触发,有该事件返回结果则认为录像开始。
videoOutput.on('frameStart', (err: BusinessError) => {
if (err !== undefined && err.code !== 0) {
return;
}
console.info('Video frame started');
}); -
通过注册固定的frameEnd回调函数获取监听录像结束结果,videoOutput创建成功时即可监听,录像完成最后一帧时触发,有该事件返回结果则认为录像流已结束。
videoOutput.on('frameEnd', (err: BusinessError) => {
if (err !== undefined && err.code !== 0) {
return;
}
console.info('Video frame ended');
}); -
通过注册固定的error回调函数获取监听录像输出错误结果,callback返回录像输出接口使用错误时对应的错误码,错误码类型参见CameraErrorCode。
videoOutput.on('error', (error: BusinessError) => {
console.error(`Video output error code: ${error.code}`);
});