HarmonyOS鸿蒙Next中如何读取沙箱中视频的信息
HarmonyOS鸿蒙Next中如何读取沙箱中视频的信息 如何读取在沙箱中的视频的时长、视频方向、帧率(fps)、宽、高、minetype?
3 回复
参考demo:
import { media } from '@kit.MediaKit';
import { image } from '@kit.ImageKit';
import { fileIo } from '@kit.CoreFileKit';
let context = getContext(this)
let filesDir = context.filesDir
let filePath = filesDir + "/" + "videoTest.mp4"
@Entry
@Component
struct Index {
@State message: string = 'Hello World'
@State pixelMap: image.PixelMap | undefined = undefined;
build() {
Row() {
Column() {
Text('把视频保存到沙箱路径').fontSize(50).fontWeight(FontWeight.Bold).onClick(() => {
context.resourceManager.getRawFile("videoTest.mp4", (err, value) => {
let file = fileIo.openSync(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
console.log(`${value.buffer.byteLength}`)
fileIo.writeSync(file.fd, value.buffer)
fileIo.closeSync(file.fd)
})
})
Button('测量视频宽高')
.type(ButtonType.Capsule)
.margin({ top: 20 })
.backgroundColor('#0D9FFB')
.width('60%')
.height('5%')
.onClick(async () => {
let avMetadataExtractor = await media.createAVMetadataExtractor()
avMetadataExtractor.fdSrc = fileIo.openSync(getContext().filesDir + '/videoTest.mp4');
let metadata = await avMetadataExtractor.fetchMetadata()
console.log(metadata.videoWidth + '')
})
Image(this.pixelMap)
.width(300)
.height(300)
.margin({ top: 20 })
}
.width('100%')
}
.height('100%')
}
}
更多关于HarmonyOS鸿蒙Next中如何读取沙箱中视频的信息的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS鸿蒙Next中,读取沙箱中视频信息可以通过File
和MediaMetadataRetriever
类实现。首先,使用File
类访问沙箱中的视频文件,确保文件路径正确。然后,使用MediaMetadataRetriever
类提取视频的元数据信息,如时长、分辨率、编码格式等。具体步骤如下:
- 获取沙箱中的视频文件路径,通常通过
context.getFilesDir()
或context.getExternalFilesDir()
获取。 - 使用
MediaMetadataRetriever
类,调用setDataSource()
方法,传入视频文件路径。 - 调用
extractMetadata()
方法,传入相应的键值(如MediaMetadataRetriever.METADATA_KEY_DURATION
获取时长,MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH
获取宽度等),即可获取视频的元数据信息。
注意:操作前需确保应用具有读取沙箱文件的权限。
在HarmonyOS鸿蒙Next中,可以通过FileManager
和MediaLibrary
等API读取沙箱中的视频信息。首先,使用FileManager
获取视频文件的路径,然后通过MediaLibrary
查询视频的元数据,如分辨率、时长等。示例代码如下:
import ohos.media.photokit.metadata.MediaLibrary;
import ohos.media.photokit.metadata.MediaMetadata;
import ohos.utils.net.Uri;
Uri videoUri = Uri.parse("file://沙箱路径/视频文件.mp4");
MediaLibrary mediaLibrary = new MediaLibrary(context);
MediaMetadata metadata = mediaLibrary.getMediaMetadata(videoUri);
String duration = metadata.getString(MediaMetadata.DURATION);
String resolution = metadata.getString(MediaMetadata.RESOLUTION);
确保在config.json
中声明必要的权限,如ohos.permission.READ_MEDIA
。