0

我正在尝试使用 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,
  },
});
4

1 回答 1

0

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.

于 2021-02-24T07:51:08.297 回答