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?

korakot
  • 37,818
  • 16
  • 123
  • 144
molo32
  • 387
  • 1
  • 3
  • 6
  • See also https://stackoverflow.com/questions/18019477/how-can-i-play-a-local-video-in-my-ipython-notebook – alvas Mar 21 '23 at 03:59

7 Answers7

35

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/>""")
korakot
  • 37,818
  • 16
  • 123
  • 144
  • 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 idea – molo32 Aug 06 '19 at 15:28
  • Then, copy the file to current directory first. – korakot Aug 06 '19 at 16:43
  • 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 much – tezzaaa Apr 27 '20 at 22:04
  • It's not working for heavy video, I tested with ~80MB video and runtime collapsed. Are there any other approaches? – Tai Le Jun 17 '20 at 03:17
  • @Yachi웃 I have added a new method for a big video. – korakot Jun 17 '20 at 07:34
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

anilsathyan7
  • 1,423
  • 17
  • 25
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)
Godwin Mathias
  • 326
  • 4
  • 12
  • Thank you @Mathias! This does run, however is it supposed to display on another window? How do we view it? – maximus Sep 29 '22 at 19:15
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)
Nikolay L
  • 31
  • 2
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)"))
Aray Karjauv
  • 2,679
  • 2
  • 26
  • 44
0

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")
mdnestor
  • 137
  • 2
  • 9
-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()