首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在没有服务工作人员的情况下使用从缓存中播放mp3

在没有服务工作人员的情况下使用从缓存中播放mp3
EN

Stack Overflow用户
提问于 2021-01-11 13:58:46
回答 1查看 608关注 0票数 0

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

  1. npx创建反应应用我的应用程序
  2. npm I反应-球员
  3. 将代码粘贴到App.js中

代码语言:javascript
复制
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;

EN

回答 1

Stack Overflow用户

发布于 2021-01-12 13:13:11

尝试下面的代码缓存您的视频。

代码语言:javascript
复制
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();
       }
     });
   });
 };

单击这里阅读更多信息。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65668247

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档