使用Android原生相机拍摄视频时如何限制最长时长
实现方案
ActivityResultContracts.CaptureVideo 本身支持通过系统标准Intent参数配置时长限制,你可以通过自定义合约的方式注入参数,配合兜底校验实现需求:
方法1:自定义活动结果合约(推荐)
原生ActivityResultContracts.CaptureVideo默认仅接收输出视频的Uri作为入参,你可以继承该类,在生成Intent的阶段注入时长限制参数:
// 自定义带时长限制的视频拍摄合约 class CaptureVideoWithDurationLimit( // 传入最大允许拍摄时长,单位为秒 private val maxDurationSeconds: Int ) : ActivityResultContracts.CaptureVideo() { override fun createIntent(context: Context, input: Uri): Intent { val intent = super.createIntent(context, input) // 注入系统标准时长限制参数 intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, maxDurationSeconds) return intent } }
使用方式如下:
- 注册活动结果启动器
// 3分钟等于180秒,传入自定义合约 private val captureVideoLauncher = registerForActivityResult( CaptureVideoWithDurationLimit(180) ) { isSuccess -> if (isSuccess) { // 拍摄成功,后续处理逻辑 } }
- 调起相机时传入预先准备的视频输出Uri即可
// 自行构造输出视频的Uri,省略构造逻辑 val outputVideoUri: Uri = ... captureVideoLauncher.launch(outputVideoUri)
兜底校验方案
MediaStore.EXTRA_DURATION_LIMIT的生效依赖于被调起的相机应用对该参数的支持,绝大多数系统原生相机都兼容该配置,为了避免小众第三方相机不生效的问题,建议在拍摄完成后二次校验视频时长:
// 读取视频文件时长,单位为毫秒 fun getVideoDuration(context: Context, videoUri: Uri): Long { val retriever = MediaMetadataRetriever() return try { retriever.setDataSource(context, videoUri) val durationStr = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION) durationStr?.toLongOrNull() ?: 0 } catch (e: Exception) { 0 } finally { retriever.release() } } // 拍摄成功后调用校验 val duration = getVideoDuration(context, outputVideoUri) if (duration > 180 * 1000) { // 时长超限,提示用户并删除无效文件 context.contentResolver.delete(outputVideoUri, null, null) Toast.makeText(context, "视频时长不能超过3分钟", Toast.LENGTH_SHORT).show() }
内容的提问来源于stack exchange,提问作者Tarsila Costalonga
相关产品推荐
相关产品推荐

