Stream audio/video to an ML model from your web app using our step-by-step guide for seamless integration and optimal performance.

Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
// Access the user's camera
navigator.mediaDevices.getUserMedia({ video: true, audio: true })
.then(function(stream) {
// Display the stream locally
const videoElement = document.querySelector('video');
videoElement.srcObject = stream;
// Create a MediaRecorder to capture stream chunks
const recorder = new MediaRecorder(stream);
// Send each recorded chunk to server via WebSocket when available
recorder.ondataavailable = function(event) {
if (event.data && event.data.size > 0) {
// Send binary data (blob) over an established WebSocket connection
websocket.send(event.data);
}
};
// Start recording with a timeslice of 1000 ms
recorder.start(1000);
})
.catch(function(error) {
console.error('Error accessing media devices.', error);
});
// Create a new WebSocket connection
const websocket = new WebSocket('ws://localhost:8000/stream');
// Log successful connection
websocket.onopen = function(event) {
console.log('WebSocket connection established.');
};
// Handle errors on the client side
websocket.onerror = function(error) {
console.error('WebSocket error: ', error);
};
// Optionally handle messages from the server (e.g., for acknowledgments)
websocket.onmessage = function(event) {
console.log('Message from server: ', event.data);
};
import asyncio
import websockets
import io
from PIL import Image
import numpy as np
import tensorflow as tf // Assuming TensorFlow is used
// Load your pre-trained ML model
model = tf.keras.models.load\_model('path/to/your/model.h5')
// Function to process a video frame (if using video streaming)
def process_frame(image_data):
// Convert raw bytes into an image
image = Image.open(io.BytesIO(image\_data))
image = image.resize((224, 224)) // Resize as per model requirement
image\_array = np.array(image) / 255.0
image_array = np.expand_dims(image\_array, axis=0)
prediction = model.predict(image\_array)
return prediction
async def handler(websocket, path):
async for message in websocket:
// When receiving a binary chunk, process it
if isinstance(message, bytes):
try:
result = process\_frame(message)
// Optionally, send the prediction results back to client
await websocket.send(str(result))
except Exception as e:
print("Error processing frame:", e)
// Extend similar logic for audio stream processing if needed
start\_server = websockets.serve(handler, 'localhost', 8000)
asyncio.get_event_loop().run_until_complete(start\_server)
asyncio.get_event_loop().run\_forever()
websocket.onmessage = function(event) {
// Display or process the ML prediction results received from the server
console.log('Prediction from ML model:', event.data);
// You might update the UI with the prediction data here
};
From startups to enterprises and everything in between, see for yourself our incredible impact.
Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We’ll discuss your project and provide a custom quote at no cost.Â