0

In my react application I would like to play an mp3 file that was manually cached before using the cache api. The file is located on a different site, so I am using the no-cors mode to fetch it and put an opaque response into the cache. My question now is: How can I play this file from the cache using react-player (see comment in the code example)? Or in other words: How do I feed the cached response into react-player? My question is similar to this one, but I don't want to use a service worker for this. To run the code example I provided:

  1. npx create-react-app my-app
  2. npm i react-player
  3. paste the code into 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;
JoeCool
  • 129
  • 7

1 Answers1

0

Try the below code to cache your video.

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

Click here to read more.

Hrushikesh Rao
  • 109
  • 1
  • 4