📑

pafy と youtube_dl で動画再生

2023/01/15に公開

見つけたサンプルでは動画再生速度が定速にならない。
動画のオブジェクトの中にfpsがあったのでこれを使ってwait時間を調整。

import cv2
import pafy


# Choose a YouTube URL (paste from viewing a video on the web)
url=["https://www.youtube.com/watch?v=jzbG__vsD2w",
     "https://www.youtube.com/watch?v=tWoo8i_VkvI"
    ]
# Use pafy to get the video stream url
for video_no in range(2):
    video = pafy.new(url[video_no])
    # Have a look at available streams
    #print("Streams : " + str(video.allstreams))
    # But for now get best stream
    best = video.getbest(preftype="mp4")
    print(vars(best))

    # Initialise OpenCV Video Capture Object with URL
    capture = cv2.VideoCapture(best.url)

    # Test out viewing very slowly frame by frame
    while(capture.isOpened()):
        # Capture frame-by-frame
        ret, frame = capture.read()

        if ret == True:
            # Display the resulting frame
            cv2.imshow('Frame',frame)

            # Press Q on keyboard to  exit
            if cv2.waitKey(int(1000/best._info['fps']+0.5)) & 0xFF == ord('q'): # +0.5は切り捨て⇒四捨五入変換
                break
        # Break the loop
        else:
            break
    capture.release()
cv2.destroyAllWindows() 

前よりはマシになった

Discussion