Skip to content

视频缩略图获取

获取视频缩略图插件,支持 Android、iOS、Web、mp-weixin 平台

引入

ts
import { getVideoThumb } from '@/uni_modules/tui-video-thumb'

基础用法

vue
<template>
  <view class="fv p-16px">
    <image :src="imgsrc" mode="aspectFit" style="width:300px;height:200px;margin:20px auto;background:#f5f5f5;" />
    <button @click="getlocal">获取本地视频封面</button>
    <button @click="getNetwork">获取网络视频封面</button>
  </view>
</template>

<script setup>
import { getVideoThumb } from '@/uni_modules/tui-video-thumb'

const netWorkPath = 'https://yundie.xyz/cdn/1733384294236cbcbc420-a37d-11ec-97c5-1100ea3c8040.mp4'
const imgsrc = ref('')

function getlocal() {
  uni.chooseVideo({
    sourceType: ['album', 'camera'],
    compressed: false,
    success: (res : ChooseVideoSuccess) => {
      getVideoThumb({
        path: res.tempFilePath,
        time: 1,
        success: (rst : string) => {
          imgsrc.value = rst
        },
        fail: (err : UniError | null) => {
          console.error('失败:', err)
        }
      })
    }
  })
}

function getNetwork() {
  getVideoThumb({
    path: netWorkPath,
    time: 2,
    success: (res : string) => {
      imgsrc.value = res
    },
    fail: (err : UniError | null) => {
      console.error('失败:', err)
    }
  })
}
</script>

API

getVideoThumb(options)

获取视频指定时间点的缩略图。

参数

参数类型必填说明
pathstring视频文件路径,支持本地路径和网络 URL
timenumber获取帧的时间点(毫秒),默认 0 表示第一帧
successfunction成功回调,返回缩略图路径(string)
failfunction失败回调
completefunction完成回调

回调

回调参数说明
successresult: string缩略图路径(file:// 文件路径或 blob URL)
failerror: UniError | null错误信息
completeresult: string | null完成时返回

平台说明

平台实现方式返回格式
AndroidMediaMetadataRetriever + 缓存文件file:// 路径
iOSAVAssetImageGeneratorfile:// 路径
WebHTMLVideoElement + Canvasblob URL
mp-weixinuni.getVideoInfo().thumbTempFilePath临时文件路径

注意事项

  • Android 端使用 setDataSource(Context, Uri) 方式打开文件,比直接传路径性能更好
  • iOS 端使用原生 Swift helper 避免 unsafe pointer 问题
  • Web 端视频需要支持 CORS 才能正常截帧
  • 视频选择建议设置 compressed: false 避免等待压缩

示例

完整示例参考 demo/video-thumb/video-thumb.uvue