如何通过React Native视频从内部存储访问我的视频? [英] How can I access my videos from internal storage with react native video?

查看:85
本文介绍了如何通过React Native视频从内部存储访问我的视频?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用react native制作一个简单的视频播放器,在初始化应用程序时,它将从服务器获取播放列表,自动下载它们,然后从本地存储中播放.我不确定是否需要将播放列表存储在数据库中.

I am trying to make a simple video player using react native where, when the app is initialized it will fetch the playlist from a server, automatically download them and then play from local storage. I am not sure if i need to store the playlist in a Database.

目前,我能够完成的工作就是能够在线播放视频,因此,当没有互联网时,我将无法再播放这些视频.我也可以下载视频,但是只下载了一个视频,而不是整个播放列表.由于我重复了视频,所以我不想一次又一次地下载相同的视频.另外,我似乎也无法从内部存储器访问下载的视频.我将在下面提供mt代码.谢谢

Currently what I have been able to accomplish is being able to play videos online, as a result when there is no internet I can't play those videos anymore. I was also able to download videos but only one video is being downloaded instead of the whole playlist. As I have repeated videos I don't want to download same videos again and again. Also it seems I am unable to access my downloaded videos from my internal storage as well. I will provide mt code below. Thank you

import React, { useEffect, useState } from 'react';
import { ActivityIndicator, FlatList, Text, View,StyleSheet } from 'react-native';
import Video from 'react-native-video';
import InternetConnectionAlert from "react-native-internet-connection-alert";
import axios from 'axios';
import RNFetchBlob from 'rn-fetch-blob'
// import { getLastUpdateTime } from 'react-native-device-info';

// console.log("YOLO")
export default test = () => {
  const [isLoading, setLoading] = useState(true);
  const [data, setData] = useState([]);
  const [currIndex, setCurrIndex] = useState(0);
  const [uri, setUri] = useState("http://admin.ddad-bd.com/storage/campaigns/6/videos/L8j548Msg2d0CrqXw3iTiCPeZFx4J4oEImcpXZpG.mp4");
  const [imei, setImei] = useState("14789")
  const [campaignId, setCampaignid] = useState("");
  // const[started_at, setStartedat] = useState("")
  // const[ended_at, setEndedat] = useState("")
  var today = new Date();
  started_at = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate() + ' ' + today.getHours() + ':' + today.getMinutes() + ':' + today.getSeconds();
  ended_at = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate() + ' ' + today.getHours() + ':' + today.getMinutes() + ':' + (today.getSeconds()+35);

  let dirs = RNFetchBlob.fs.dirs
  var filePath = dirs.DCIMDir



  {/* Only Called Once to fetch new Playlist every hour*/}
  useEffect(() => {

    console.log("First Run")
    
    axios.get('http://dev.ddad-bd.com/api/campaigns/index/', {
      params: {
        ID: imei
      }
    })
    .then(function (response) {
      setData(response.data.play_list)
    })
    .catch(function (error) {
      console.log(error);
    })
    .finally(() => {
      // onDownload(),
      setLoading(false)
    });


    onDownload()
  }, []);


  const onEnd = () => {

    

    setCurrIndex(currIndex + 1)
    setUri(data[currIndex].primary_src)
    setCampaignid(data[currIndex].campaign_id)
    console.log()

    axios.post('http://dev.ddad-bd.com/api/campaigns', {
      campaign_type: "campaign",
      android_imei: imei,
      campaign_id: campaignId,
      started_at: started_at,
      ended_at: ended_at,
      content_type: "primary"
    })
    .then(function (response) {
      console.log("Response Succesfull");
    })
    .catch(function (error) {
      console.log(error);
    });


  }

  const onDownload = () => {

    // JSON.parse(data)

    let dirs = RNFetchBlob.fs.dirs
    console.log(dirs.DCIMDir)
    RNFetchBlob
    .config({
        addAndroidDownloads : {
            useDownloadManager : true, // <-- this is the only thing required
            // Optional, override notification setting (default to true)
            path : dirs.DCIMDir + "/DDAD/",
            notification : true,
            // Optional, but recommended since android DownloadManager will fail when
            // the url does not contains a file extension, by default the mime type will be text/plain
            mime : 'video/webm',
            description : 'File downloaded by download manager.'
        }
    })
    .fetch('GET', uri)
    .then((resp) => {
      // the path of downloaded file
      resp.path()
    })

  }

  return (
    <InternetConnectionAlert
      onChange={(connectionState) => {
        console.log("Connection State: ", connectionState);
      }}
      
    >
      {/* {onDownload()} */}

      <View style={{ flex: 1, padding: 24 }}>
        {isLoading ? <ActivityIndicator/> : (
          
          // uri ? (
            
            // onLoad(),
            <Video 
            source={{uri: uri}}   // Can be a URL or a local file.
            ref={(ref) => {
              this.player = ref
              // this.player.presentFullscreenPlayer();
            }}
            
            // onLoad={onLoad} 
            resizeMode={'contain'}
            // repeat={true}                            // Store reference
            onBuffer={this.onBuffer}                // Callback when remote video is buffering
            onError={this.videoError}               // Callback when video cannot be loaded
            style={styles.backgroundVideo}
            onEnd={onEnd}
          />
          // ) : (
          //   <Video 
          //     source={{uri: "http://admin.ddad-bd.com/storage/campaigns/6/videos/L8j548Msg2d0CrqXw3iTiCPeZFx4J4oEImcpXZpG.mp4"}}   // Can be a URL or a local file.
          //     ref={(ref) => {
          //       this.player = ref
          //       // this.player.presentFullscreenPlayer();
          //     }} 
          //     resizeMode={'contain'}
          //     // repeat={true}                           // Store reference
          //     onBuffer={this.onBuffer}                // Callback when remote video is buffering
          //     onError={this.videoError}               // Callback when video cannot be loaded
          //     style={styles.backgroundVideo}
          //     onEnd={onEnd}
          //   />
          // )
        )}

      </View>
      {/* {... Your whole application should be here ... } */}
  </InternetConnectionAlert>

    

  );
};
var styles = StyleSheet.create({
  backgroundVideo: {
    position: 'absolute',
    top: 0,
    left: 0,
    bottom: 0,
    right: 0,
  },
});

推荐答案

更新:要从本地存储播放视频,您需要在新的android版本中处理android权限.添加android:requestLegacyExternalStorage ="true"并将compileSdkVersion更新为29.这解决了我的问题,并且视频可以离线播放.

Update: For videos to play from local storage you need to handle android permission in new android versions. Add android:requestLegacyExternalStorage="true" and also update compileSdkVersion to 29. This solved my problem and the videos are being played offline.

这篇关于如何通过React Native视频从内部存储访问我的视频?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆