serving static audio files with flask in react

Step 1: Install Flask

pip install flask

Step 2: Create a Flask app

from flask import Flask, send_from_directory

app = Flask(__name__)

Step 3: Define a route for serving audio files

@app.route('/audio/<path:filename>')
def serve_audio(filename):
    return send_from_directory('path/to/audio/files', filename)

Step 4: Run the Flask app

if __name__ == '__main__':
    app.run(debug=True)

Step 5: Set up your React component to fetch and play audio

import React, { useState } from 'react';

const AudioPlayer = () => {
  const [audioUrl, setAudioUrl] = useState('/audio/example.mp3');

  const playAudio = () => {
    const audio = new Audio(audioUrl);
    audio.play();
  };

  return (
    <div>
      <button onClick={playAudio}>Play Audio</button>
    </div>
  );
};

export default AudioPlayer;

Step 6: Use the AudioPlayer component in your main React app

import React from 'react';
import AudioPlayer from './AudioPlayer';

const App = () => {
  return (
    <div>
      <h1>React Audio Player</h1>
      <AudioPlayer />
    </div>
  );
};

export default App;

Step 7: Run your React app (assuming you have set up your React project using Create React App or a similar tool)

npm start

Ensure that your Flask app is also running, and visit your React app in the browser to see and interact with the audio player.