【问题标题】:How can i play audio file sent from flask send_file?如何播放从烧瓶 send_file 发送的音频文件?
【发布时间】:2021-07-02 19:14:44
【问题描述】:

我正在使用 React 开发前端,使用 Flask 开发后端。
我想从 Flask 服务器发送一个 mp3 到客户端并在浏览器上播放。

反应

import React from "react";
import axios from "axios";

function App() {

  function handleClick() {
    axios
      .post(`http://localhost:5000/post`, { text: text })
      .then((res) => {
        // to set a audio from server into <audio controls>
      })
      .catch((error) => {console.log("axios error:", error);});
  }

  return (
    <div className="App">
      <button onClick={() => handleClick()}>BUTTON</button>
      <div>
        <audio controls>
          <source src="" type="audio/mpeg" />
        </audio>
      </div>
    </div>
  );
}

export default App;

烧瓶

@app.route('/post', methods=["POST"])
def testpost():
    req = request.get_json(force=True)
    # some process to send a file
    return send_file("test.mp3")

【问题讨论】:

    标签: reactjs flask


    【解决方案1】:

    为了能够从你的 react 应用调用你的烧瓶应用,你首先需要考虑 cors。

    您可能已经这样做了,但如果没有,您可以像这样使用Flask-CORS

    from flask import Flask, render_template, send_file, Response
    from flask_cors import CORS, cross_origin
    
    
    app = Flask(__name__)
    cors = CORS(app)
    
    
    @app.route("/post", methods=["POST"])
    @cross_origin()
    def testpost():
        return send_file("audio.mp3", mimetype="audio/mp3")
    

    然后我们可以在 react 应用中做这样的事情

    import React, { useState } from "react";
    import axios from "axios";
    
    function App() {
      const [src, setSrc] = useState("");
    
      function handleClick() {
        axios({
          url: "http://localhost:5000/post",
          method: "post",
          responseType: "blob",
        })
          .then((res) => {
            setSrc(URL.createObjectURL(res.data));
          })
          .catch((error) => {
            console.log("axios error:", error);
          });
      }
    
      return (
        <div className="App">
          <button onClick={() => handleClick()}>BUTTON</button>
          <div>
            <audio id="audio" controls src={src} />
          </div>
        </div>
      );
    }
    
    export default App;
    

    如果您想在按下执行handleClick 的按钮后立即播放音频,您可以执行document.querySelector('audio').play() 之类的操作。

    【讨论】:

      猜你喜欢
      • 2019-05-13
      • 2021-08-19
      • 2015-10-11
      • 2021-08-03
      • 2014-12-09
      • 2021-04-25
      • 1970-01-01
      • 1970-01-01
      • 2016-01-08
      相关资源
      最近更新 更多