本篇笔记是无意中翻阅“PiCamera”的技术文档发现的。文档链接:https://picamera.readthedocs.io/en/release-1.13/recipes2.html#web-streaming
文档翻译:
通过网络流式传输视频非常复杂。 在撰写本文时,所有平台上的所有Web浏览器仍然没有普遍支持的视频标准。 此外,HTTP最初被设计为一种用于服务网页的一次性协议。 自发明以来,为了满足其不断增长的用例(文件下载,恢复,流式传输等),已经增加了各种附加功能,但事实仍然是,目前还没有“简单”的视频流传输解决方案。
如果您想播放流“真实”视频格式(特别是MPEG1)的播放,则可能需要看一下pistreaming演示。 但是,出于本食谱的目的,我们将使用更简单的格式:MJPEG。 以下脚本使用Python的内置http.server模块制作了一个简单的视频流服务器:
源代码:
- import io
- import picamera
- import logging
- import socketserver
- from threading import Condition
- from http import server
- PAGE="""\
- <html>
- <head>
- <title>picamera MJPEG streaming demo</title>
- </head>
- <body>
- <h1>PiCamera MJPEG Streaming Demo</h1>
- <img src="stream.mjpg" width="640" height="480" />
- </body>
- </html>
- """
- class StreamingOutput(object):
- def __init__(self):
- self.frame = None
- self.buffer = io.BytesIO()
- self.condition = Condition()
- def write(self, buf):
- if buf.startswith(b'\xff\xd8'):
- # New frame, copy the existing buffer's content and notify all
- # clients it's available
- self.buffer.truncate()
- with self.condition:
- self.frame = self.buffer.getvalue()
- self.condition.notify_all()
- self.buffer.seek(0)
- return self.buffer.write(buf)
- class StreamingHandler(server.BaseHTTPRequestHandler):
- def do_GET(self):
- if self.path == '/':
- self.send_response(301)
- self.send_header('Location', '/index.html')
- self.end_headers()
- elif self.path == '/index.html':
- content = PAGE.encode('utf-8')
- self.send_response(200)
- self.send_header('Content-Type', 'text/html')
- self.send_header('Content-Length', len(content))
- self.end_headers()
- self.wfile.write(content)
- elif self.path == '/stream.mjpg':
- self.send_response(200)
- self.send_header('Age', 0)
- self.send_header('Cache-Control', 'no-cache, private')
- self.send_header('Pragma', 'no-cache')
- self.send_header('Content-Type', 'multipart/x-mixed-replace; boundary=FRAME')
- self.end_headers()
- try:
- while True:
- with output.condition:
- output.condition.wait()
- frame = output.frame
- self.wfile.write(b'--FRAME\r\n')
- self.send_header('Content-Type', 'image/jpeg')
- self.send_header('Content-Length', len(frame))
- self.end_headers()
- self.wfile.write(frame)
- self.wfile.write(b'\r\n')
- except Exception as e:
- logging.warning(
- 'Removed streaming client %s: %s',
- self.client_address, str(e))
- else:
- self.send_error(404)
- self.end_headers()
- class StreamingServer(socketserver.ThreadingMixIn, server.HTTPServer):
- allow_reuse_address = True
- daemon_threads = True
- with picamera.PiCamera(resolution='640x480', framerate=24) as camera:
- output = StreamingOutput()
- camera.start_recording(output, format='mjpeg')
- try:
- address = ('', 8000)
- server = StreamingServer(address, StreamingHandler)
- server.serve_forever()
- finally:
- camera.stop_recording()
运行上述代码后,我们就可以通过访问“http://树莓派IP:8000”观看树莓派直播啦!效果如下: