HarmonyOS 鸿蒙Next中如何压缩视频文件
HarmonyOS 鸿蒙Next中如何压缩视频文件 如题,如何压缩视频文件?有没有示例?
使用AVCodec Kit视频编码功能,将未经压缩的视频数据传输至视频编码器进行编码处理,通过设定所需的编码格式、比特率、帧率等参数,并对编码输出进行控制,从而实现视频文件的压缩目的,编码器参数配置范围请参考:获取支持的编解码能力。
int32_t VideoEncoder::Configure(const SampleInfo &sampleInfo) {
OH_AVFormat *format = OH_AVFormat_Create();
CHECK_AND_RETURN_RET_LOG(format != nullptr, AVCODEC_SAMPLE_ERR_ERROR, "AVFormat create failed");
OH_AVFormat_SetIntValue(format, OH_MD_KEY_WIDTH, sampleInfo.videoWidth);
OH_AVFormat_SetIntValue(format, OH_MD_KEY_HEIGHT, sampleInfo.videoHeight);
OH_AVFormat_SetDoubleValue(format, OH_MD_KEY_FRAME_RATE, sampleInfo.frameRate);
OH_AVFormat_SetIntValue(format, OH_MD_KEY_PIXEL_FORMAT, sampleInfo.pixelFormat);
OH_AVFormat_SetIntValue(format, OH_MD_KEY_VIDEO_ENCODE_BITRATE_MODE, sampleInfo.bitrateMode);
OH_AVFormat_SetLongValue(format, OH_MD_KEY_BITRATE, sampleInfo.bitrate);
OH_AVFormat_SetIntValue(format, OH_MD_KEY_PROFILE, sampleInfo.hevcProfile);
// Setting HDRVivid-related parameters
if (sampleInfo.isHDRVivid) {
OH_AVFormat_SetIntValue(format, OH_MD_KEY_I_FRAME_INTERVAL, sampleInfo.iFrameInterval);
OH_AVFormat_SetIntValue(format, OH_MD_KEY_RANGE_FLAG, sampleInfo.rangFlag);
OH_AVFormat_SetIntValue(format, OH_MD_KEY_COLOR_PRIMARIES, sampleInfo.primary);
OH_AVFormat_SetIntValue(format, OH_MD_KEY_TRANSFER_CHARACTERISTICS, sampleInfo.transfer);
OH_AVFormat_SetIntValue(format, OH_MD_KEY_MATRIX_COEFFICIENTS, sampleInfo.matrix);
}
// ...
// Setting the Encoder
int ret = OH_VideoEncoder_Configure(encoder_, format);
OH_AVFormat_Destroy(format);
format = nullptr;
CHECK_AND_RETURN_RET_LOG(ret == AV_ERR_OK, AVCODEC_SAMPLE_ERR_ERROR, "Config failed, ret: %{public}d", ret);
return AVCODEC_SAMPLE_ERR_OK;
}
参考地址
https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs/faqs-avsession-13
更多关于HarmonyOS 鸿蒙Next中如何压缩视频文件的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS鸿蒙Next中,压缩视频文件可使用系统提供的媒体处理能力。通过@ohos.multimedia.mediaLibrary和@ohos.multimedia.image接口,可访问视频文件并进行编码参数调整。使用VideoEncoder组件设置输出格式(如H.264)与比特率、分辨率等参数以降低文件大小。具体步骤包括:获取视频文件、配置编码选项、启动压缩并保存输出。整个过程依赖鸿蒙的媒体引擎,无需第三方库。
在HarmonyOS Next中,可通过VideoCompressor组件实现视频压缩。以下为关键步骤及示例:
- 引入依赖(在module.json5中添加):
"abilities": [
{
"name": "VideoCompressor",
"srcEntry": "./ets/videocompressor/Videocompressor.ets"
}
]
- 核心代码示例:
import videoCompressor from '@ohos.multimedia.videoCompressor';
// 配置压缩参数
let options: videoCompressor.VideoCompressOptions = {
srcUri: 'file://.../input.mp4', // 源文件URI
dstUri: 'file://.../output.mp4', // 输出路径
quality: videoCompressor.Quality.MEDIUM, // 压缩质量
resolution: [1280, 720] // 输出分辨率
};
// 执行压缩
try {
await videoCompressor.compress(context, options);
console.log('压缩完成');
} catch (err) {
console.error(`压缩失败: ${err.code}, ${err.message}`);
}
- 关键参数说明:
- quality:支持LOW/MEDIUM/HIGH三档质量
- 支持分辨率自定义设置
- 可通过progressCallback监听压缩进度
注意:需在应用配置中声明ohos.permission.READ_MEDIA和ohos.permission.WRITE_MEDIA权限。实际路径需使用正确的沙箱路径访问方案。

