视频缩略图获取
获取视频缩略图插件,支持 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)
获取视频指定时间点的缩略图。
参数
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
path | string | 是 | 视频文件路径,支持本地路径和网络 URL |
time | number | 否 | 获取帧的时间点(毫秒),默认 0 表示第一帧 |
success | function | 否 | 成功回调,返回缩略图路径(string) |
fail | function | 否 | 失败回调 |
complete | function | 否 | 完成回调 |
回调
| 回调 | 参数 | 说明 |
|---|---|---|
success | result: string | 缩略图路径(file:// 文件路径或 blob URL) |
fail | error: UniError | null | 错误信息 |
complete | result: string | null | 完成时返回 |
平台说明
| 平台 | 实现方式 | 返回格式 |
|---|---|---|
| Android | MediaMetadataRetriever + 缓存文件 | file:// 路径 |
| iOS | AVAssetImageGenerator | file:// 路径 |
| Web | HTMLVideoElement + Canvas | blob URL |
| mp-weixin | uni.getVideoInfo().thumbTempFilePath | 临时文件路径 |
注意事项
- Android 端使用
setDataSource(Context, Uri)方式打开文件,比直接传路径性能更好 - iOS 端使用原生 Swift helper 避免 unsafe pointer 问题
- Web 端视频需要支持 CORS 才能正常截帧
- 视频选择建议设置
compressed: false避免等待压缩
示例
完整示例参考 demo/video-thumb/video-thumb.uvue