使用 react-player 从缓存播放 mp3,无需服务工作者

问题描述

在我的 React 应用程序中,我想播放一个在使用 cache api 之前手动缓存的 mp3 文件。该文件位于不同的站点上,因此我使用 no-cors 模式来获取它并将不透明的响应放入缓存中。我现在的问题是:如何使用 react-player 从缓存中播放此文件(请参阅代码示例中的注释)?或者换句话说:如何将缓存的响应提供给 react-player?我的问题类似于 this one,但我不想为此使用服务工作者。运行我提供的代码示例:

  1. npx create-react-app my-app
  2. npm 我反应播放器
  3. 代码粘贴到 App.js 中

import React,{ useState } from "react";
import logo from "./logo.svg";
import "./App.css";
import ReactPlayer from "react-player";

const cacheName = "Testcache";
const url =
  "http://media.blubrry.com/nihongo_con_teppei/s/nihongoconteppei.com/wp-content/uploads/2021/01/Beginners-con-Teppei341.mp3";

function App() {
  const initialState = {
    urlForPlayer: url,};

  const [state,setState] = useState(initialState);

  const playFromCache = () => {
    caches.open(cacheName).then((cacheObj) => {
      cacheObj.match(url).then((response) => {
        if (response !== undefined) {
          //What should I do here to play from cache?
        }
      });
    });
  };

  const addToCache = () => {
    caches.open(cacheName).then((cache_obj) => {
      fetch(new Request(url,{ mode: "no-cors" }))
        .then((response) => {
          cache_obj.put(url,response);
          console.log("File added to cache");
        })
        .catch((error) => {
          console.log("Fetch Failed",error);
        });
    });
  };

  //The player initially loads the mp3 from the other website/origin
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <ReactPlayer url={state.urlForPlayer} controls={true} />
        <button onClick={playFromCache}>Play from cache</button>
        <button onClick={addToCache}> Add to cache</button>
      </header>
    </div>
  );
}

export default App;

解决方法

试试下面的代码来缓存你的视频。

const playFromCache = () => {
   caches.open(cacheName).then((cacheObj) => {
     cacheObj.match(url).then((response) => {
       if (response !== undefined) {
         // Print your response. If your response is correct,// trying streaming the video from here or keep updating the state and stream the video.
            console.log(res.arrayBuffer);
            return res.arrayBuffer();
       }
     });
   });
 };

点击here阅读更多内容。