Play local (hard-drive) video file with HTML5 video tag?

Chris picture Chris · Jan 16, 2012 · Viewed 133k times · Source

I want to achieve the following.

<video src="file:///Users/username/folder/video.webm">
</video>

The intent is that the user will be able to select a file from his/her hard drive.

And the reason for not uploading is of course transmission costs and storage quota. There will be no reason to save the file.

Is it possible?

Answer

Dimitar Bonev picture Dimitar Bonev · Feb 19, 2012

It is possible to play a local video file.

<input type="file" accept="video/*"/>
<video controls autoplay></video>

When a file is selected via the input element:

  1. 'change' event is fired
  2. Get the first File object from the input.files FileList
  3. Make an object URL that points to the File object
  4. Set the object URL to the video.src property
  5. Lean back and watch :)

http://jsfiddle.net/dsbonev/cCCZ2/embedded/result,js,html,css/

(function localFileVideoPlayer() {
  'use strict'
  var URL = window.URL || window.webkitURL
  var displayMessage = function(message, isError) {
    var element = document.querySelector('#message')
    element.innerHTML = message
    element.className = isError ? 'error' : 'info'
  }
  var playSelectedFile = function(event) {
    var file = this.files[0]
    var type = file.type
    var videoNode = document.querySelector('video')
    var canPlay = videoNode.canPlayType(type)
    if (canPlay === '') canPlay = 'no'
    var message = 'Can play type "' + type + '": ' + canPlay
    var isError = canPlay === 'no'
    displayMessage(message, isError)

    if (isError) {
      return
    }

    var fileURL = URL.createObjectURL(file)
    videoNode.src = fileURL
  }
  var inputNode = document.querySelector('input')
  inputNode.addEventListener('change', playSelectedFile, false)
})()
video,
input {
  display: block;
}

input {
  width: 100%;
}

.info {
  background-color: aqua;
}

.error {
  background-color: red;
  color: white;
}
<h1>HTML5 local video file player example</h1>
<div id="message"></div>
<input type="file" accept="video/*" />
<video controls autoplay></video>