我正在嘗試使用音頻流式傳輸 FFmpeg。
我將在下面展示我的代碼:
匯入模塊
import subprocess as sp
創建變數
rtmpUrl = "rtmp://a.rtmp.youtube.com/live2/key"
camera_path = "BigBuckBunny.mp4"
cap = cv.VideoCapture(camera_path)
# Get video information
fps = int(cap.get(cv.CAP_PROP_FPS))
width = int(cap.get(cv.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv.CAP_PROP_FRAME_HEIGHT))
命令引數
# ffmpeg command
command = ['ffmpeg',
'-y',
'-f', 'rawvideo',
'-vcodec','rawvideo',
'-pix_fmt', 'bgr24',
'-s', "{}x{}".format(width, height),
'-r', str(fps),
'-i', '-',
'-c:v', 'libx264',
'-pix_fmt', 'yuv420p',
'-preset', 'ultrafast',
'-f', 'flv',
rtmpUrl]
為 ffmpeg 命令創建子行程
# Pipeline configuration
p = sp.Popen(command, stdin=sp.PIPE)
將幀發送到 RTMP 服務器
# read webcamera
while(cap.isOpened()):
ret, frame = cap.read()
if not ret:
print("Opening camera is failed")
break
# write to pipe
p.stdin.write(frame.tobytes())
我希望您能幫助我通過 FFmpeg 通過 RTMP 進行帶音頻的直播。謝謝!
uj5u.com熱心網友回復:
假設您實際上需要對視頻使用 OpenCV,您必須像 Gyan 評論的那樣將音頻直接添加到 FFmpeg,因為 OpenCV 不支持音頻。
-re 直播可能需要引數。
為了測驗,我將 RTMP URL 從 YouTube 修改為 localhost。
FFplay 子行程用于捕獲流(用于測驗)。
完整的代碼示例:
import subprocess as sp
import cv2
#rtmpUrl = "rtmp://a.rtmp.youtube.com/live2/key"
rtmp_url = "rtmp://127.0.0.1:1935/live/test" # Use localhost for testing
camera_path = "BigBuckBunny.mp4"
cap = cv2.VideoCapture(camera_path)
# Get video information
fps = int(cap.get(cv2.CAP_PROP_FPS))
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
# Start the TCP server first, before the sending client (for testing).
ffplay_process = sp.Popen(['ffplay', '-listen', '1', '-i', rtmp_url]) # Use FFplay sub-process for receiving the RTMP video.
# ffmpeg command
# OpenCV does not support audio.
command = ['ffmpeg',
'-y',
'-re', # '-re' is requiered when streaming in "real-time"
'-f', 'rawvideo',
#'-thread_queue_size', '1024', # May help https://stackoverflow.com/questions/61723571/correct-usage-of-thread-queue-size-in-ffmpeg
'-vcodec','rawvideo',
'-pix_fmt', 'bgr24',
'-s', "{}x{}".format(width, height),
'-r', str(fps),
'-i', '-',
'-vn', '-i', camera_path, # Get the audio stream without using OpenCV
'-c:v', 'libx264',
'-pix_fmt', 'yuv420p',
'-preset', 'ultrafast',
# '-c:a', 'aac', # Select audio codec
'-bufsize', '64M', # Buffering is probably required
'-f', 'flv',
rtmp_url]
# Pipeline configuration
p = sp.Popen(command, stdin=sp.PIPE)
# read webcamera
while (cap.isOpened()):
ret, frame = cap.read()
if not ret:
print("End of input file")
break
# write to pipe
p.stdin.write(frame.tobytes())
p.stdin.close() # Close stdin pipe
p.wait()
ffplay_process.kill() # Forcefully close FFplay sub-process
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/393760.html
標籤:Python opencv 声音的 ffmpeg 溪流
上一篇:使用影像處理檢測近水平線
