Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i play audio file sent from flask send_file?

Tags:

reactjs

flask

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")
like image 702
Jongha Lim Avatar asked Oct 18 '25 10:10

Jongha Lim


1 Answers

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().

like image 136
Bas van der Linden Avatar answered Oct 21 '25 21:10

Bas van der Linden