Jongha Lim
Jongha Lim

Reputation: 59

How can i play audio file sent from flask send_file?

I am developing Frontend using React and Backend using Flask.
I want to send an mp3 from the Flask server to the client and play it on the browser.

React

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;

Flask

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

Upvotes: 4

Views: 2163

Answers (1)

bas
bas

Reputation: 15722

In order to be able to call your flask app from your react app you will first need to account for cors.

You might have already done this, but if not you could use Flask-CORS like this:

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")

Then we can do something like this in the react app

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;

If you immediately want to play the audio after pressing the button that executes handleClick you can do something like document.querySelector('audio').play().

Upvotes: 3

Related Questions