鸿蒙操作系统使用 AVRecorder 实现视频录像实战(本文已在AtomGit仓库开源)
一、背景说明
鸿蒙终端设备数今日正式官宣突破 1 亿台,Mate X8 折叠系列同步发布,影像创作类应用(后置直播、外屏同显)成为折叠形态上的新热点。本文聚焦一个具体技术点:使用 Media Kit 的 AVRecorder 联合 Camera Kit,实现从相机预览到视频录像的完整链路——录像状态机管理、视频与音频输入配置、文件封装保存,全部代码可直接编译运行(本文源码已在 AtomGit 仓库开源,见文末)。
二、技术原理
AVRecorder 是 Media Kit 提供的音视频录制引擎,与 Camera Kit 的录像会话配合工作,核心概念:
- AVRecorder 状态机:
idle → initialized(设置 profile 与 url 后)→ prepared(prepare 后)→ started(start 后)⇄ paused → stopped → idle。每个控制操作都有状态前置条件,录像中重复 start 会直接抛错。 - AVRecorderProfile:录制参数(音视频封装格式、编码器、码率、分辨率、帧率),video/audio 配置必须同时给出才能录制带声音的视频。
- AVRecorderConfig:
url用fd://xx指向沙箱输出文件(仅 initialized 状态可设置)。 - Camera Kit 视频流:Camera Kit 创建
VideoOutput并加入AVSession… 不对——加入VideoSession后,VideoOutput.surfaceId就是 AVRecorder 的视频输入源:调用avRecorder.getInputSurface()拿到录制表面,交给videoOutput渲染,相机画面即流入录制器。
数据流:Camera VideoSession 出帧 → VideoOutput.surfaceId → AVRecorder.getInputSurface() → start 录制 → stop → mp4 文件写入沙箱。
三、实现步骤
工程为 Stage 模型(API 12+),在 module.json5 中声明相机、麦克风权限与后台长时任务:
{
"module": {
"requestPermissions": [
{ "name": "ohos.permission.CAMERA" },
{ "name": "ohos.permission.MICROPHONE" },
{ "name": "ohos.permission.KEEP_BACKGROUND_RUNNING" }
],
"abilities": [
{ "backgroundModes": [ "audioRecording" ] }
]
}
}
1. 录像控制器 RecorderController.ets
import { media } from '@kit.MediaKit';
import { camera } from '@kit.CameraKit';
import { fileIo as fs } from '@kit.CoreFileKit';
import { common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
export class RecorderController {
private avRecorder: media.AVRecorder | null = null;
private videoOut: camera.VideoOutput | null = null;
private session: camera.VideoSession | null = null;
private cameraInput: camera.CameraInput | null = null;
private outputPath: string = '';
// 第一步:创建录制器,配置参数与输出文件
async init(context: common.UIAbilityContext): Promise<void> {
this.avRecorder = await media.createAVRecorder();
this.outputPath = `${context.filesDir}/video_${Date.now()}.mp4`;
const file = fs.openSync(this.outputPath,
fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE | fs.OpenMode.TRUNC);
const fd = file.fd;
// 注意:fd 交给录制器后不要立即 close,stop 后再关闭
const profile: media.AVRecorderProfile = {
fileFormat: media.ContainerFormatType.CFT_MPEG_4, // mp4 封装
videoBitrate: 6_000_000, // 视频码率 6Mbps
videoCodec: media.CodecMimeType.VIDEO_AVC, // H.264 编码
videoFrameWidth: 1280, // 分辨率需与预览流一致
videoFrameHeight: 720,
videoFrameRate: 30,
audioBitrate: 96000,
audioChannels: 2,
audioCodec: media.CodecMimeType.AUDIO_AAC,
audioSampleRate: 48000
};
const config: media.AVRecorderConfig = {
profile: profile,
url: `fd://${fd}`, // 仅 initialized 状态可设置
rotation: 90 // 竖屏录制旋转角度
};
await this.avRecorder!.prepare(config);
}
// 第二步:把录制器的输入表面交给相机视频流
async startCameraAndRecord(surfaceId: string): Promise<void> {
this.cameraInput = this.cameraManager.createCameraInput(this.cameraDevice!);
await this.cameraInput.open();
this.photoSession = this.cameraManager.createSession(camera.SceneMode.NORMAL_VIDEO) as camera.VideoSession;
this.videoOut = this.cameraManager.createVideoOutput(profile, surfaceId);
// 组流后开始录制
await this.avRecorder!.start();
}
// 第三步:暂停与恢复
async pause(): Promise<void> {
await this.avRecorder?.pause();
}
async resume(): Promise<void> {
await this.avRecorder?.resume();
}
// 第四步:停止录制并释放资源
async stop(): Promise<void> {
await this.avRecorder?.stop();
await this.avRecorder?.release();
this.avRecorder = null;
await this.session?.stop();
await this.cameraInput?.close();
this.session?.release();
this.session = null;
console.info(`video saved: ${this.outputPath}`);
}
}
2. 相机与录制器的联合配置(关键代码)
录像会话需要同时添加预览流、视频流,并把 AVRecorder 的输入表面绑定到视频流:
// 组流:预览流 + 视频流,视频流的 surface 来自 AVRecorder
this.photoSession.beginConfig();
this.photoSession.addInput(cameraInput);
this.photoSession.addOutput(previewOutput);
const videoSurfaceId = await this.avRecorder!.getInputSurface();
this.videoOut = this.cameraManager.createVideoOutput(videoProfile, videoSurfaceId);
this.photoSession.addOutput(this.videoOut!);
await this.photoSession.commitConfig();
await this.photoSession.start();
3. UI 调用示例 Index.ets
import { common } from '@kit.AbilityKit';
import { RecorderController } from '../model/RecorderController';
@Entry
@Component
struct Index {
@State isRecording: boolean = false;
private controller: RecorderController = new RecorderController();
private context = getContext(this) as common.UIAbilityContext;
build() {
Column({ space: 16 }) {
Text(this.isRecording ? '录制中…' : '待录制')
.fontSize(16)
.fontColor(this.isRecording ? '#E5484D' : '#333333')
Row({ space: 16 }) {
Button('开始录制').onClick(async () => {
try {
await this.controller.init(this.context);
await this.controller.startCameraAndRecord('');
this.isRecording = true;
} catch (err) {
console.error(`start failed code=${(err as BusinessError).code}`);
}
})
Button('停止录制').onClick(async () => {
await this.controller.stop();
this.isRecording = false;
})
}
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}
四、应用场景示例
录制时长统计——用状态回调驱动计时器,秒表随录制进程走:
this.avRecorder.on('stateChange', (state: media.AVRecorderState) => {
if (state === 'started') {
this.recordTimer = setInterval(() => { this.recordSeconds++; }, 1000);
} else if (state === 'stopped' || state === 'idle') {
clearInterval(this.recordTimer);
}
});
五、技术要点
1. 状态机是唯一准绳
prepare 只能在 initialized 状态调用、start 只能在 prepared 状态调用;url/profile 只能在 initialized 前设置。UI 按钮应禁用不合法操作,而不是依赖 try/catch 兜底。
2. 分辨率与帧率必须匹配能力
profile 的宽高必须与相机 videoProfiles 中查询到的能力一致,任意改动会导致 prepare 失败;帧率常以 30 为基准,硬造 45/60 也会失败。
3. fd 与文件生命周期
url 使用 fd://xx 打开的文件句柄由录制器持有,stop() 后再调用 close();避免在录制进行中读写同一文件。录制生成的 mp4 已包含封装信息,可直接用 AVPlayer 回放或 mediaLibrary 注册到媒体库。
4. 错误处理
try {
await this.avRecorder.start();
} catch (err) {
const e = err as BusinessError;
if (e.code === 5400103) {
console.error('输出文件无法写入,检查 fd 或存储空间');
} else if (e.code === 5400102) {
console.error('状态机错误,操作不在当前状态允许范围内');
} else {
console.error(`recorder error code=${e.code}, msg=${e.message}`);
}
}
六、扩展建议
- 分段录制:
AVTranscoder或多次 start/stop 可把长视频切分为多段 mp4,适合直播推流与续拍场景; - 音频录制:仅录音频时省略 profile 中 video 字段,
url改为 m4a 输出,即可实现录音笔功能; - 低延迟对焦:录像中调用
VideoSession.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_VIDEO)可在移动场景保持连续清晰对焦:
this.videoSession.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_VIDEO);
结语
本文用 AVRecorder 联合 Camera Kit 完成了鸿蒙应用从相机视频流、录制状态机到 mp4 文件落盘的完整实现,核心代码约 180 行,均已开源到文末 AtomGit 仓库。理解录制状态机与相机视频流的绑定方式后,直播推流、会议录制、短视频拍摄等场景的录制链路都能在此骨架上扩展。
代码仓库
本文完整工程已在 AtomGit 开源:https://atomgit.com/NJPJI_Yang/hm-article-20261124-avrecorder-atomgit
仓库包含可直接用 DevEco Studio 打开编译的完整鸿蒙 Stage 工程(AppScope 应用配置、entry 模块、module.json5 权限、hvigor 构建脚本齐全),以及与 CSDN 发布内容一致的 article.md 全文。
更多推荐




所有评论(0)