Facebook
From SMa, 2 Weeks ago, written in Plain Text.
This paste is a reply to Untitled from SMA - view diff
Embed
Download Paste or View Raw
Hits: 208
  1. pip install pydub flask
  2.  
  3.  
  4.  
  5. from flask import Flask, Response
  6. from pydub import AudioSegment
  7. import io
  8.  
  9. app = Flask(__name__)
  10.  
  11. @app.route('/stream')
  12. def stream():
  13.     # MP3 file path
  14.     mp3_file = "path_to_file.mp3"
  15.  
  16.     # Load the MP3 audio file
  17.     audio = AudioSegment.from_file(mp3_file, format="mp3")
  18.  
  19.     # Create a generator to stream audio in chunks
  20.     def generate():
  21.         # Specify the chunk size (in milliseconds) for streaming
  22.         chunk_size = 1000
  23.  
  24.         # Iterate over the audio in chunks
  25.         for i in range(0, len(audio), chunk_size):
  26.             yield audio[i:i+chunk_size].raw_data
  27.  
  28.     # Set the content type as audio/mpeg
  29.     headers = {'Content-Type': 'audio/mpeg'}
  30.  
  31.     # Return the audio chunks as a Flask Response object
  32.     return Response(generate(), headers=headers)
  33.  
  34. if __name__ == '__main__':
  35.     app.run()
  36.  
  37.  
  38.  
  39.  
  40. python stream_server.py
  41.