首页 > 解决方案 > 如何在 Ionic iOS 中显示来自画廊的视频

问题描述

我正在使用 html5 的视频标签来显示我从图库中选择的视频。我遇到了一个问题,即使我提供了来源,视频也无法加载。

这是一个以电容器为桥梁的 Ionic/Angular 项目,但仍使用 Cordova 插件。这是我的代码原型:

我的页面.page.ts

import { Camera, CameraOptions } from '@ionic-native/camera/ngx';
import { Capacitor } from '@capacitor/core';

@Component({...})
export class MyPage {

  // ... some code which gets the a reference to the video element from the template

  // this function is called when the user clicks a button to choose video from gallery
  onPickVideo() {
    const cameraOptions: CameraOptions = {
      destinationType: this.camera.DestinationType.NATIVE_URI,
      sourceType: this.camera.PictureSourceType.SAVEDPHOTOALBUM,
      mediaType: this.camera.MediaType.VIDEO,
    };
    this.camera.getPicture(cameraOptions).then(videoUri => {
      console.log(videoUri);
      this.videoSrc = Capacitor.convertFileSrc(videoUri);
      console.log(this.videoSrc);
      this.videoEl.load();
      this.videoEl.currentTime = 0.1;
    });
  }
}

我的page.page.html

<video playsinline #video>
  <source [src]=".videoSrc" type="video/mp4" />
  Your browser does not support the video tag.
</video>

my-page.page.ts 的输出是:

file:///private/var/mobile/Containers/Data/Application/7D85727C-CE9A-4816-BC42-C97F03AFDEB4/tmp/F6DCE819-ED4A-41E4-BAFB-814500F2FB27.MOV

capacitor://localhost/_capacitor_file_/private/var/mobile/Containers/Data/Application/7D85727C-CE9A-4816-BC42-C97F03AFDEB4/tmp/F6DCE819-ED4A-41E4-BAFB-814500F2FB27.MOV

这适用于桌面和 Android。它不适用于装有 iOS 12 的 iPhone 6。在其他 iOS 版本上未经测试。

我尝试过的一些事情:

标签: iosangularcordovaionic-frameworkhtml5-video

解决方案


通过“清理” URL 来解决。我还没有了解这真正意味着什么。这是任何人需要的代码

import { Camera, CameraOptions } from '@ionic-native/camera/ngx';
import { Capacitor } from '@capacitor/core';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';


@Component({...})
export class MyPage {

  // ... some code which gets the a reference to the video element from the template

  safeUrl: SafeUrl;

  constructor(private sanitizer: DomSanitizer) {}

  // this function is called when the user clicks a button to choose video from gallery
  onPickVideo() {
    const cameraOptions: CameraOptions = {
      destinationType: this.camera.DestinationType.NATIVE_URI,
      sourceType: this.camera.PictureSourceType.SAVEDPHOTOALBUM,
      mediaType: this.camera.MediaType.VIDEO,
    };
    this.camera.getPicture(cameraOptions).then(videoUri => {
      this.safeUrl = this.sanitizer.bypassSecurityTrustUrl(
          Capacitor.convertFileSrc(videoUri)
        );
      this.videoEl.load();
      this.videoEl.currentTime = 0.1;
    });
  }
}

然后确保在模板中使用 safeUrl [src]="safeUrl"


推荐阅读