0

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

  1. npx 创建反应应用程序我的应用程序
  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;

4

1 回答 1

0

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

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

点击这里阅读更多。

于 2021-01-12T13:13:11.360 回答