Search code examples
pythonopencvyoutubegoogle-colaboratory

Playing videos on Google Colab


I tried to use the following codes to play YouTube videos on Google Colab,

!pip install pytube==9.1.0
from pytube import YouTube
yt = YouTube('https://www.youtube.com/watch?v=-ncJV0tMAjE&t=72s')

The title of yt object is,

print(yt.title)
>> 作業2 第二題 強健控制:結構化不確定參數的Riccati equation

Then, I imported cv2.

import cv2
import numpy as np
cap = cv2.VideoCapture('作業2 第二題 強健控制:結構化不確定參數的Riccati equation.mp4')

while(cap.isOpened()):
    ret, frame = cap.read()

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    cv2.imshow('frame',gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

However, I always got an error message as,

Runtime died. Automatically restarting.

What should I do?


Solution

  • You need to get the embed code of your video.

    from IPython.display import HTML
    
    HTML('<iframe width="560" height="315" src="https://www.youtube.com/embed/lTTZ8PkQ_Pk" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>')