Ionic 3中如何从媒体库加载视频?Native File已不被Ionic View支持
Hey there! Let's tackle your video loading task now that Native File isn't supported in Ionic View anymore. You mentioned you're using the Camera plugin's FILE_URI destination type, which gives you paths like /storage/emulated/0/DCIM/Camera/VID_20180312_210545.mp4 — here's how to use that path to load your video successfully:
Step 1: Configure the Camera Plugin Correctly
First, make sure your Camera call is set up to fetch video with the right parameters. Here's a TypeScript example:
import { Camera, CameraOptions } from '@ionic-native/camera/ngx'; constructor(private camera: Camera) {} selectVideoFromGallery() { const cameraOptions: CameraOptions = { sourceType: this.camera.PictureSourceType.PHOTOLIBRARY, mediaType: this.camera.MediaType.VIDEO, destinationType: this.camera.DestinationType.FILE_URI, encodingType: this.camera.EncodingType.MP4 }; this.camera.getPicture(cameraOptions).then((fileUri) => { // Pass the retrieved file path to your video loading function this.setupVideoPlayer(fileUri); }, (error) => { console.error('Failed to select video:', error); }); }
Step 2: Load the Video into Your UI
Once you have the fileUri, you can bind it directly to an HTML5 <video> tag. For better cross-platform compatibility, use Ionic's normalizeURL helper to clean up the path:
Component Code
import { normalizeURL } from '@ionic/angular'; // Adjust import based on your Ionic version videoSource: string; setupVideoPlayer(fileUri: string) { // Normalize the path to handle Android's file system quirks this.videoSource = normalizeURL(fileUri); }
Template Markup
Add this to your component's HTML to display the video:
<video controls [src]="videoSource" width="100%" style="max-height: 400px;"> Your browser does not support the video tag. </video>
Key Notes to Avoid Issues
- Permissions Matter: Double-check your
config.xmlhas the required permissions to access media files:<!-- Android --> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <!-- iOS --> <plugin name="cordova-plugin-media-capture"> <variable name="PHOTOLIBRARY_USAGE_DESCRIPTION" value="Need access to your photo library to select videos" /> </plugin> - Try NATIVE_URI if FILE_URI Fails: If you run into loading issues with
FILE_URI, switch todestinationType: this.camera.DestinationType.NATIVE_URI. This returns platform-native URIs (like Android'scontent://or iOS'sassets-library://) which sometimes have better compatibility with the video tag. - Skip Native File Entirely: Since it's no longer supported, you don't need to use the Native File plugin to read the video content. The Camera's returned path works directly with the
<video>tag once normalized.
内容的提问来源于stack exchange,提问作者Roger A. Leite

