首页 > 解决方案 > React Native Video 未加载本地文件

问题描述

我正在向我的 react 本机应用程序添加视频录制和预览功能。为了拍摄视频,我使用了以下代码,一旦录制,我就可以获取输出文件。现在使用文件 uri,我尝试使用 react 向用户预览这个文件-native-video 组件。但它总是显示空白屏幕,但没有加载视频。


import { RNCamera, FaceDetector } from 'react-native-camera';

 <RNCamera
      ref={ref => {
        this.camera = ref;
      }}
      style={{width:width(100),height:height(100)}}
      type={RNCamera.Constants.Type.back}

      flashMode={RNCamera.Constants.FlashMode.on}
      permissionDialogTitle={"Permission to use camera"}
      permissionDialogMessage={
        "We need your permission to use your camera phone"
      }
    >

 async startRecording() {
        this.setState({ recording: true });
        var self = this;
         this.camera.recordAsync().
        then((data) => {
            self.setState({video:data.uri})
        })
    }

一旦视频变量可用,我尝试使用下面的代码片段加载它:-

import Video from 'react-native-video';


 {this.state.video !== ''
                ?
                <Video source={{uri: this.state.video}}   // Can be a URL or a local file.
       ref={(ref) => {
         this.player = ref
       }}                                      
       onBuffer={this.onBuffer}                
       onError={this.videoError}               
       style={styles.backgroundVideo} />
       :
     <View/>
}

版本详细信息是:-

  1. “反应原生”:“0.61.5”。
  2. “反应原生视频”:“^5.0.2”
  3. “反应本机相机”:“^3.15.0”

这是相机录制完成后我得到的视频文件“file:///data/user/0/com.dezzexvideo/cache/Camera/94d367ef-c6b8-43c3-844f-7d0d2c6d0ddf.mp4”

标签: react-nativereact-native-camerareact-native-video

解决方案


您提到的文件路径file:///data/user/0/com.dezzexvideo/cache/Camera/94d367ef-c6b8-43c3-844f-7d0d2c6d0ddf.mp4 - 似乎是缓存目录文件路径。

所以可能你不能直接从缓存目录播放视频。你可以使用react-native-fs

使用RNFS首先检查文件是否存在于缓存路径中

       if(await RNFS.exists(cachefilepath)){
          //then copy the video file to Document Directory using RNFS

         //copyFile(filepath: string, destPath: string): Promise<void>

         RNFS.copyFile(cachefilepath, RNFS.DocumentDirectoryPath).then({
         })

       } 
       //Play file from directory path

       <Video source={{uri: RNFS.DocumentDirectoryPath+filename}} ... />

推荐阅读