这可能是一个愚蠢的问题,我已经搜索过了但没有找到一个直接的答案:
你能否使用OpenCV和FFMPEG播放带有音频的视频?
如果不能,最好的方法是什么?这似乎很简单,但我对Python非常陌生,不知道该期望/搜索什么。
谢谢!
你能否使用OpenCV和FFMPEG播放带有音频的视频?
如果不能,最好的方法是什么?这似乎很简单,但我对Python非常陌生,不知道该期望/搜索什么。
谢谢!
import cv2
import numpy as np
#ffpyplayer for playing audio
from ffpyplayer.player import MediaPlayer
video_path="../L1/images/Godwin.mp4"
def PlayVideo(video_path):
video=cv2.VideoCapture(video_path)
player = MediaPlayer(video_path)
while True:
grabbed, frame=video.read()
audio_frame, val = player.get_frame()
if not grabbed:
print("End of video")
break
if cv2.waitKey(28) & 0xFF == ord("q"):
break
cv2.imshow("Video", frame)
if val != 'eof' and audio_frame is not None:
#audio
img, t = audio_frame
video.release()
cv2.destroyAllWindows()
PlayVideo(video_path)
样例代码可以运行,但是您需要根据您的视频速度调整cv2.waitKey(28)。
video = cv2.VideoCapture(video_path)
、fps = video.get(cv2.CAP_PROP_FPS)
、sleep_ms = int(numpy.round((1/fps)*1000))
。请注意,这些代码需要使用OpenCV和NumPy库。 - Sevagsleep_ms
值的 waitKey
,似乎仍存在音频和视频同步问题。 - Tumul Kumar#date: 22 May 2022
#reference:https://github.com/thedreamcode/python_basics/blob/master/read_video_audio.py
import cv2
import numpy as np
from ffpyplayer.player import MediaPlayer
def getVideoSource(source, width, height):
cap = cv2.VideoCapture(source)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
return cap
def running_videos(sourcePath):
camera = getVideoSource(sourcePath, 720, 480)
player = MediaPlayer(sourcePath)
while True:
ret, frame = camera.read()
audio_frame, val = player.get_frame()
if (ret == 0):
print("End of video")
break
frame = cv2.resize(frame, (720, 480))
cv2.imshow('Camera', frame)
if cv2.waitKey(20) & 0xFF == ord('q'):
break
#if val != 'eof' and audio_frame is not None:
#frame, t = audio_frame
#print("Frame:" + str(frame) + " T: " + str(t))
camera.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
running_videos( r"copy_path_to_video_file_here")
import numpy as np
import cv2
import pygame #pip install pygame
from pygame import mixer
mixer.init()
file_name = "Intro1.mp4"
window_name = "window"
interframe_wait_ms = 30
cap = cv2.VideoCapture(file_name)
if not cap.isOpened():
print("Error: Could not open video.")
exit()
cv2.namedWindow(window_name, cv2.WND_PROP_FULLSCREEN)
cv2.setWindowProperty(window_name, cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)
mixer.music.load("Intro1.mp3")
mixer.music.play()
while (True):
ret, frame = cap.read()
if not ret:
print("Reached end of video, exiting.")
break
cv2.imshow(window_name, frame)
if cv2.waitKey(interframe_wait_ms) & 0x7F == ord('q'):
print("Exit requested.")
break
cap.release()
cv2.destroyAllWindows()
以上代码使用OpenCV库和Pygame库来显示一个有对应音频的视频文件。以下是代码的简要概述:
总的来说,这段代码允许您使用OpenCV和Pygame库播放具有相应音频的视频文件。