You need to enable JavaScript to run this app. 如何使用react-native-video访问内部存储的已下载视频实现离线播放
优惠活动
大模型
产品
解决方案
定价
更多

如何使用react-native-video访问内部存储的已下载视频实现离线播放

React Native 简易视频播放器开发问题汇总

核心需求与待决策项

  • 基于 React Native 开发简易视频播放器
  • 核心业务流程:应用初始化时从服务器拉取播放列表,自动完成全量视频下载后从本地存储播放
  • 待确认:是否需要将播放列表存入本地数据库

已实现功能与现存问题

已完成功能

  • 支持在线播放视频
  • 支持单个视频下载

现存待解决问题

  • 无网络环境下无法正常播放视频
  • 仅支持单个视频下载,无法自动批量下载整个播放列表
  • 播放列表存在重复内容,需要避免重复下载相同视频
  • 无法从内部存储访问已下载的视频

当前实现代码

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'

export default test = () => {
  const [isLoading, setLoading] = useState(true);
  const [data, setData] = useState([]);
  const [currIndex, setCurrIndex] = useState(0);
  const [uri, setUri] = useState("示例在线视频地址");
  const [imei, setImei] = useState("14789")
  const [campaignId, setCampaignid] = 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

  {/* 仅应用初始化时调用一次,按周期拉取新播放列表 */}
  useEffect(() => {
    console.log("First Run")
    
    axios.get('你的拉取播放列表接口地址', {
      params: {
        ID: imei
      }
    })
    .then(function (response) {
      setData(response.data.play_list)
    })
    .catch(function (error) {
      console.log(error);
    })
    .finally(() => {
      setLoading(false)
    });

    onDownload()
  }, []);

  const onEnd = () => {
    setCurrIndex(currIndex + 1)
    setUri(data[currIndex].primary_src)
    setCampaignid(data[currIndex].campaign_id)

    axios.post('你的播放数据上报接口地址', {
      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 = () => {
    let dirs = RNFetchBlob.fs.dirs
    console.log(dirs.DCIMDir)
    RNFetchBlob
    .config({
        addAndroidDownloads : {
            useDownloadManager : true,
            path : dirs.DCIMDir + "/DDAD/",
            notification : true,
            mime : 'video/webm',
            description : 'File downloaded by download manager.'
        }
    })
    .fetch('GET', uri)
    .then((resp) => {
      // 返回已下载文件的路径
      resp.path()
    })
  }

  return (
    <InternetConnectionAlert
      onChange={(connectionState) => {
        console.log("Connection State: ", connectionState);
      }}
    >
      <View style={{ flex: 1, padding: 24 }}>
        {isLoading ? <ActivityIndicator/> : (
          <Video 
            source={{uri: uri}}
            ref={(ref) => {
              this.player = ref
            }}
            resizeMode={'contain'}
            onBuffer={this.onBuffer}
            onError={this.videoError}
            style={styles.backgroundVideo}
            onEnd={onEnd}
          />
        )}
      </View>
    </InternetConnectionAlert>
  );
};

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

内容的提问来源于stack exchange,提问作者Raiyan Khalil Shuvo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.02 21:36:09