Cách Stream video Camera trên trình duyệt một cách mượt mà nhất sử dụng python Flask + FFmpeg (HLS)
Cách bước stream video lên trình duyệt sử dụng Flask + FFmpeg (HLS):
Trên window thực hiện dowload:
- Vào trang chính thức: https://ffmpeg.org/download.html

- Click “Windows builds by BtbN” sau đó thực hiện tìm đến: ffmpeg-master-latest-win64-gpl.zip để download thực hiện lưu vào máy

Giải nén, thêm thư mục
binvào biến môi trườngPATH.
- Mở lại cmd / PowerShell, gõ:
ffmpeg -version
Sau khi cài xong, test lại RTSP stream: ffmpeg -rtsp_transport tcp -i "rtsp://admin:100225a@mnnsv.drayddns.com:15554/ch1/main" -f null -
Nếu bạn thấy khung log liên tục hiện frame=... fps=... bitrate=... → tức là FFmpeg đọc được stream ✅
Sau đó chạy proxy MJPEG về Flask:
ffmpeg -rtsp_transport tcp -i "rtsp://admin:100225a@mnnsv.drayddns.com:15554/ch1/main" `
-vf scale=640:360 `
-f mjpeg -q:v 5 -r 15 -listen 1 “http://127.0.0.1:8090/feed1.ffm”Trên linux:
Đối với Ubuntu thì sử dùng câu lênh:
sudo apt update
sudo apt install ffmpeg -ySau khi cài xong, test lại RTSP stream: ffmpeg -rtsp_transport tcp -i "rtsp://admin:100225a@mnnsv.drayddns.com:15554/ch1/main" -f null -
Nếu bạn thấy khung log liên tục hiện frame=... fps=... bitrate=... → tức là FFmpeg đọc được stream ✅
Mở cổng 8090
sudo ufw allow 8090/tcp
sudo ufw reloadSau đó chạy proxy MJPEG về Flask:
ffmpeg -rtsp_transport tcp -i "rtsp://admin:100225a@mnnsv.drayddns.com:15554/ch1/main" -vf scale=640:360 -f mjpeg -q:v 5 -r 15 -listen 1 "http://103.200.20.206:8090/feed1.mjpg"Tiếp theo đoạn code stream để lấy dữ liệu video;
Tạo 1 Thư mục: Project:
project/
├── app.py
└── templates/
└── index.html
app.py:
from flask import Flask, Response
import cv2
app = Flask(__name__)
def gen_frames():
cap = cv2.VideoCapture("http://127.0.0.1:8090/feed1.ffm")
while True:
success, frame = cap.read()
if not success:
break
else:
_, buffer = cv2.imencode('.jpg', frame)
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + buffer.tobytes() + b'\r\n')
@app.route('/video_feed')
def video_feed():
return Response(gen_frames(),
mimetype='multipart/x-mixed-replace; boundary=frame')
@app.route('/')
def index():
return '<img src="/video_feed" width="640" />'
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
file index.html
<!DOCTYPE html>
<html>
<head>
<title>RTSP Stream</title>
</head>
<body>
<h2>Camera Live Stream</h2>
<img src="{{ url_for('video_feed') }}" width="720" />
</body>
</html>Trên linux tương tự chỉ cần thay đổi IP là xong
Tác giả: Nguyễn Lâm
Những tin mới hơn
Những tin cũ hơn