Как я могу получить доступ к своим видео из внутреннего хранилища с помощью React Native Video?

Я пытаюсь создать простой видеопроигрыватель, используя react native, где при инициализации приложения оно будет извлекать список воспроизведения с сервера, автоматически загружать их, а затем воспроизводить из локального хранилища. Я не уверен, нужно ли мне хранить список воспроизведения в базе данных.

В настоящее время я смог воспроизвести видео в Интернете, в результате, когда нет Интернета, я больше не могу воспроизводить эти видео. Мне также удалось загрузить видео, но загружается только одно видео вместо всего плейлиста. Поскольку у меня есть повторяющиеся видео, я не хочу загружать одни и те же видео снова и снова. Также кажется, что я не могу получить доступ к своим загруженным видео из моего внутреннего хранилища. Я предоставлю код MT ниже. Спасибо

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,
  },
});

person Raiyan Khalil Shuvo    schedule 19.02.2021    source источник


Ответы (1)


Обновление: для воспроизведения видео из локального хранилища вам необходимо обрабатывать разрешение Android в новых версиях Android. Добавьте android: requestLegacyExternalStorage = true, а также обновите compileSdkVersion до 29. Это решило мою проблему, и видео воспроизводятся в автономном режиме.

person Raiyan Khalil Shuvo    schedule 24.02.2021