如何使用 React Native Video 从内部存储访问我的视频?
How can I access my videos from internal storage with react native video?
我正在尝试使用本机反应制作一个简单的视频播放器,当应用程序初始化时,它将从服务器获取播放列表,自动下载它们,然后从本地存储播放。我不确定是否需要将播放列表存储在数据库中。
目前我能做到的是可以在线播放视频,结果在没有网络的情况下我不能再播放那些视频了。我也可以下载视频,但只下载了一个视频,而不是整个播放列表。因为我有重复的视频,所以我不想一次又一次地下载相同的视频。此外,我似乎也无法从我的内部存储器访问我下载的视频。我将在下面提供 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,
},
});
更新:要从本地存储播放视频,您需要在新 android 版本中处理 android 权限。添加 android:requestLegacyExternalStorage="true" 并将 compileSdkVersion 更新为 29。这解决了我的问题,视频正在离线播放。
我正在尝试使用本机反应制作一个简单的视频播放器,当应用程序初始化时,它将从服务器获取播放列表,自动下载它们,然后从本地存储播放。我不确定是否需要将播放列表存储在数据库中。
目前我能做到的是可以在线播放视频,结果在没有网络的情况下我不能再播放那些视频了。我也可以下载视频,但只下载了一个视频,而不是整个播放列表。因为我有重复的视频,所以我不想一次又一次地下载相同的视频。此外,我似乎也无法从我的内部存储器访问我下载的视频。我将在下面提供 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,
},
});
更新:要从本地存储播放视频,您需要在新 android 版本中处理 android 权限。添加 android:requestLegacyExternalStorage="true" 并将 compileSdkVersion 更新为 29。这解决了我的问题,视频正在离线播放。