how play mp4 video in google colab
Asked Answered
R

8

26

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?

Rosanarosane answered 6/8, 2019 at 13:27 Comment(1)
See also #18019977Legalism
A
36

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/>""")
Abrahamsen answered 6/8, 2019 at 14:44 Comment(5)
I'm trying to read a video of my google drive, but for some reason the runtime environment is restarted, do you have any ideaRosanarosane
Then, copy the file to current directory first.Abrahamsen
Hi Korakot, do you know how i could stream video from a url into colab as opposed to loading the video from a drive? Thank you very muchAmur
It's not working for heavy video, I tested with ~80MB video and runtime collapsed. Are there any other approaches?Ninefold
@Yachi웃 I have added a new method for a big video.Abrahamsen
L
16

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

Litharge answered 13/12, 2020 at 8:48 Comment(2)
Most complete answer in my opinion, since this worked for my otherwise unsupported mp4 video format.Prescind
Agree, clearest answer to this questionSisak
D
4

Didn't see any mention of MoviePy (which comes installed in Google Colab as of July 2023):

import moviepy.editor
moviepy.editor.ipython_display("video.mp4")
Deaconry answered 29/3, 2023 at 1:39 Comment(0)
R
2

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)
Rapping answered 16/11, 2021 at 13:58 Comment(1)
Thank you @Mathias! This does run, however is it supposed to display on another window? How do we view it?Frizz
B
0

To support a big vdo file ,getting link url for big videos

!pip install httplib2==0.15.0
!pip install google-api-python-client==1.7.11
#don't forget to restart the environment

from IPython.display import HTML
import IPython
from google.colab import output
!pip install -U kora
from kora.drive import upload_public

video_path='/content/drive/MyDrive/BigFileName.mkv'
video_url = upload_public(video_path)  #for google disk to https://

if (video_url.startswith('https://drive.google.com/')):
   video_url+='&confirm=t' # to bypass the window Google Drive - Virus scan warning
 print('video_url',video_url)
Billibilliard answered 12/12, 2022 at 13:7 Comment(1)
Stopped working from January 2023Billibilliard
B
0

One can start a local HTTP server on the Google Colab virtual machine (let's say on port 8000). The files can then be accessed via http://localhost:8000 within the notebook

For example:

import subprocess
subprocess.Popen(['python3', '-m', 'http.server', '8000']);

and then render HTML:

%%html
<video><source src="http://localhost:8000/video.mp4" type="video/mp4"></source></video>

Demo

Additionally, one can get an external URL to the virtual machine and access the files from the internet:

from google.colab.output import eval_js
print(eval_js("google.colab.kernel.proxyPort(8000)"))
Byproduct answered 1/3, 2023 at 16:4 Comment(0)
M
0

With only 2 lines of code:

from IPython.display import Video
Video("/content/pathofvideo.mp4", embed=True)

However the output is huge!

Molybdenum answered 23/11, 2023 at 18:59 Comment(0)
P
-1

This is all you need to define

import html
from IPython.display import display, Javascript, Image
from google.colab.output import eval_js

def preProcessVideo():
  js = Javascript('''
    const video = document.createElement('video');
    const labelElement = document.createElement('span');
    const videoUrl = 'https://rr2---sn-npoldn7z.c.drive.google.com/videoplayback?expire=1641882417&ei=8ercYbCiIuCKmvUPz5WB6Ac&ip=1.55.250.186&cp=QVRJU0lfUVRPSFhPOmpHU0F4ZW1JUnNobkNZVzY0MHlMYm44NDdNek45Nm5sSVQyTWota2J4MlE&id=8955091d9a3609fd&itag=18&source=webdrive&requiressl=yes&mh=yD&mm=32&mn=sn-npoldn7z&ms=su&mv=u&mvi=2&pl=27&ttl=transient&susc=dr&driveid=1S9PGt2CHDfuJSB1nIWebi4KVNRI7jEbf&app=explorer&mime=video/mp4&vprv=1&prv=1&dur=22.825&lmt=1641801389629564&mt=1641867503&txp=0011224&sparams=expire,ei,ip,cp,id,itag,source,requiressl,ttl,susc,driveid,app,mime,vprv,prv,dur,lmt&sig=AOq0QJ8wRgIhAJ8QuQoDRVLULTONbECJ9GyCqACa9Ci7i-4yK6vqgFdxAiEAoC-AMccHI239SCSOukNJEkXmqzKBIPqmb41I25Sjljs=&lsparams=mh,mm,mn,ms,mv,mvi,pl&lsig=AG3C_xAwRgIhAI650mDvui7WOdCTc-zfXSR_jXGCX0_marfJav3vEZDvAiEAz5-kvizrRBxJxmIZpO9LxDxkPQpcMTheY5Sq7pBMPQc=&cpn=BsF1Vhd4TGv91-3f&c=WEB_EMBEDDED_PLAYER&cver=1.20220109.00.00'

    async function playVideo() {
      const div = document.createElement('div');

      video.style.width = 320;
      video.style.height = 320;

      document.body.appendChild(div);
      div.appendChild(labelElement);
      div.appendChild(video);
      
      var source = document.createElement('source');

      source.setAttribute('src', videoUrl);
      source.setAttribute('type', 'video/mp4');
      video.appendChild(source);
      video.play();

      // Resize the output to fit the video element.
      google.colab.output.setIframeHeight(document.documentElement.scrollHeight, true);
    }
    ''')
  display(js)
  eval_js('playVideo()'.format())

Then call it preProcessVideo()

Pedagogy answered 11/1, 2022 at 8:21 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.