Certainly! Below is an example of a Flask application that streams the server's microphone and camera to the clients using PyAudio for audio and OpenCV for video. In this example, the audio stream is captured using PyAudio, and the video stream is captured using OpenCV. The HTML includes a video element to display the video stream and uses JavaScript to handle the audio playback.
Flask Application Code
Ensure you have the required packages installed:
pip install Flask opencv-python pyaudio Flask-SocketIO eventlet
app.py (Flask Application)
import time
import cv2
import pyaudio
import numpy as np
from flask import Flask, render_template, Response
from flask_socketio import SocketIO, emit
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your_secret_key'
socketio = SocketIO(app)
# Audio Configuration
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
CHUNK = 1024
audio = pyaudio.PyAudio()
audio_stream = audio.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
# Video Configuration
video_capture = cv2.VideoCapture(0)
def generate_video():
while True:
success, frame = video_capture.read()
if not success:
break
ret, buffer = cv2.imencode('.jpg', frame)
frame = buffer.tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
def generate_audio():
while True:
audio_frame = audio_stream.read(CHUNK)
socketio.emit('audio_frame', {'data': audio_frame}, namespace='/audio')
time.sleep(CHUNK / RATE)
@app.route('/')
def index():
return render_template('index.html')
@socketio.on('connect', namespace='/audio')
def audio_connect():
print("Client connected to audio stream.")
if __name__ == '__main__':
socketio.start_background_task(generate_audio)
socketio.run(app, host='0.0.0.0', port=5000)
index.html (HTML page)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Microphone and Camera Streaming</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.0.5/socket.io.js"></script>
</head>
<body>
<h1>Camera Stream</h1>
<img id="video" src="{{ url_for('generate_video') }}" width="640" height="480" />
<h1>Microphone Stream</h1>
<audio id="audio" autoplay></audio>
<script>
const socket = io.connect('http://localhost:5000/audio');
const audioElement = document.getElementById('audio');
socket.on('audio_frame', function(data) {
const audioBlob = new Blob([data.data], { type: 'audio/wav' });
const audioUrl = URL.createObjectURL(audioBlob);
audioElement.src = audioUrl;
audioElement.play();
});
</script>
</body>
</html>
Explanation
-
Flask Application:
- The application uses Flask and Flask-SocketIO to handle real-time communication.
- The
generate_video function captures video frames from the camera and encodes them as JPEG.
- The
generate_audio function captures chunks of audio from the microphone and emits them to clients over a WebSocket.
-
HTML and JavaScript:
- The HTML has an
<img> element to show the video stream and an <audio> element for the audio stream.
- The JavaScript section connects to the Flask SocketIO server and listens for audio frames, playing them as they are received.
Running the Project
- Save the code snippets above in
app.py and index.html. Place index.html in a folder named templates.
- Run the Flask application using:
python app.py
- Open your browser and navigate to
http://localhost:5000 to see the camera and audio streaming.
Important Notes
- Ensure your environment has access to your camera and microphone.
- You may need to fine-tune the audio format and encoding as per your requirements.
- For best results, more robust error handling and format adjustments may be necessary based on your audio and video capture devices.