目录

Video播放系统图库视频

问题现象

如何使用Video组件播放用户系统图库中的视频文件。

背景知识

解决方案

创建PhotoViewPicker实例,调用select接口拉起图库界面供用户进行视频文件的选择,文件选择成功后,会返回视频文件的uri,可以通过Video组件播放该uri对应的相册视频。

参考代码如下:

import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct Index {
  @State videoUri: string = '';
  private controller: VideoController = new VideoController();

  build() {
    Column({ space: 20 }) {
      Video({
        src: this.videoUri,
        controller: this.controller,
      })
        .width('100%')
        .aspectRatio(1)
        .loop(false)
        .autoPlay(true)
        .controls(false)
        .objectFit(ImageFit.Contain)
        .onError(() => {
          console.error(`video error.`);
        })
        .onStop(() => {
          console.info(`video stopped.`);
        })
        .onUpdate(() => {
          console.info(`video update.`);
        })
        .onPrepared(() => {
          console.info(`video prepared.`);
        });

      Button('Select Video')
        .padding(5)
        .fontSize(30)
        .onClick(() => {
          let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
          photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.VIDEO_TYPE;
          photoSelectOptions.maxSelectNumber = 1;
          let uris: Array<string> = [];
          let photoViewPicker = new photoAccessHelper.PhotoViewPicker();
          photoViewPicker.select(photoSelectOptions)
            .then((photoSelectResult: photoAccessHelper.PhotoSelectResult) => {
              uris = photoSelectResult.photoUris;
              if (uris.length > 0) {
                this.videoUri = uris[0];
                console.info(`Video URI: ${this.videoUri}`);
              }
            })
            .catch((err: BusinessError) => {
              console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
            });
        });
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center);
  }
}