Facebook
From SMa, 2 Months ago, written in Plain Text.
This paste is a reply to Untitled from SMA - go back
Embed
Viewing differences between Untitled and Re: Untitled
pip install pydub flask



from flask 
import cv2
Flask, Response
from pydub 
import pydub
AudioSegment
import pydub.playback
#For Emid
io

app = Flask(__name__)

@app.route('/stream')
def stream():
    
RTSP stream URL
rtsp_url 
MP3 file path
    mp3_file 
"rtsp://example.com/stream"

"path_to_file.mp3"

    
Open Load the RTSP stream
cap = cv2.VideoCapture(rtsp_url)

# Check if the stream was opened successfully
if not cap.isOpened():
    print("Failed to open the RTSP stream")
    exit(1)

# Prepare an empty 
MP3 audio stream
audio_stream 
file
    audio 
pydub.AudioSegment.empty()

from_file(mp3_file, format="mp3")

    
Read and process the video frames
while True:
    # Read 
Create frame from the stream
    ret, frame = cap.read()

    # Check if the frame was read successfully
    if not ret:
        print("Failed 
generator to read a frame from the RTSP stream")
        break

    # Extract 
stream audio data from in chunks
    def generate():
        # Specify 
the frame
    audio_data 
chunk size (in milliseconds) for streaming
        chunk_size 
frame.tobytes()

    
1000

        
Convert Iterate over the audio data to an AudioSegment
    audio_segment 
in chunks
        for i in range(0, len(audio), chunk_size):
            yield audio[i:i+chunk_size].raw_data

    # Set the content type as audio/mpeg
    headers 
pydub.AudioSegment(audio_data, frame_rate=44100, sample_width=2, channels=2)

    
{'Content-Type': 'audio/mpeg'}

    
Append Return the audio segment to the audio stream
    audio_stream += audio_segment

    # Play the audio stream
    pydub.playback.play(audio_stream)

    # Clear the audio stream
    audio_stream = pydub.AudioSegment.empty()

# Release resources
cap.release()
cv2.destroyAllWindows()
chunks as a Flask Response object
    return Response(generate(), headers=headers)

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




python stream_server.py