how play mp4 video in google colab

I have a video.mp4 in content/video.mp4

if I wanted to play the video in google colab without downloading , ¿what code I should use to open a kind of video player in my jupyter notebook?


Solution 1:

Here's the code

from IPython.display import HTML
from base64 import b64encode
mp4 = open('video.mp4','rb').read()
data_url = "data:video/mp4;base64," + b64encode(mp4).decode()
HTML("""
<video width=400 controls>
      <source src="%s" type="video/mp4">
</video>
""" % data_url)

You can test it in a colab notebook here.

Update (Jun 2020)

To support a big vdo file, I write a library to upload to Google Drive and set it public. Then use the returned URL to display the video.

!pip install -U kora
from kora.drive import upload_public
url = upload_public('video.mp4')
# then display it
from IPython.display import HTML
HTML(f"""<video src={url} width=500 controls/>""")

Solution 2:

Currently, we need to compress the video file to play it in google colaboratory, if the format is not supported.

from IPython.display import HTML
from base64 import b64encode
import os

# Input video path
save_path = "/content/videos/result.mp4"

# Compressed video path
compressed_path = "/content/videos/result_compressed.mp4"

os.system(f"ffmpeg -i {save_path} -vcodec libx264 {compressed_path}")

# Show video
mp4 = open(compressed_path,'rb').read()
data_url = "data:video/mp4;base64," + b64encode(mp4).decode()
HTML("""
<video width=400 controls>
      <source src="%s" type="video/mp4">
</video>
""" % data_url)

Reference: https://towardsdatascience.com/yolov3-pytorch-on-google-colab-c4a79eeecdea

Solution 3:

Just input the mp4 video path to that function and you're good to go.

from IPython.display import HTML
from base64 import b64encode
 
def show_video(video_path, video_width = 600):
   
  video_file = open(video_path, "r+b").read()
 
  video_url = f"data:video/mp4;base64,{b64encode(video_file).decode()}"
  return HTML(f"""<video width={video_width} controls><source src="{video_url}"></video>""")
 
show_video(video_path)