Play from an arbitrary position using MediaElement.js for HTML5 video - javascript

I need to be able to play an HTML5 video (mp4 format) from any arbitrary location.
<script src="{{ STATIC_URL }}mediaelementjs/jquery.js"></script>
<script src="{{ STATIC_URL }}mediaelementjs/mediaelement-and-player.min.js"></script>
<link rel="stylesheet" href="{{ STATIC_URL }}mediaelementjs/mediaelementplayer.min.css" />
<script>
$(document).ready(function(){$('video, audio').mediaelementplayer({
// if the <video width> is not specified, this is the default
defaultVideoWidth: 480,
// if the <video height> is not specified, this is the default
defaultVideoHeight: 270,
// if set, overrides <video width>
videoWidth: -1,
// if set, overrides <video height>
videoHeight: -1,
// width of audio player
audioWidth: 400,
// height of audio player
audioHeight: 30,
// initial volume when the player starts
startVolume: 0.8,
// useful for <audio> player loops
loop: false,
// enables Flash and Silverlight to resize to content size
enableAutosize: true,
// the order of controls you want on the control bar (and other plugins below)
features: ['playpause','progress','current','duration','tracks','volume','fullscreen'],
// Hide controls when playing and mouse is not over the video
alwaysShowControls: false,
// force iPad's native controls
iPadUseNativeControls: false,
// force iPhone's native controls
iPhoneUseNativeControls: false,
// force Android's native controls
AndroidUseNativeControls: false,
// forces the hour marker (##:00:00)
alwaysShowHours: false,
// show framecount in timecode (##:00:00:00)
showTimecodeFrameCount: false,
// used when showTimecodeFrameCount is set to true
framesPerSecond: 25,
// turns keyboard support on and off for this instance
enableKeyboard: true,
// when this player starts, it will pause other players
pauseOtherPlayers: true,
// array of keyboard commands
keyActions: [],
// start with English automatically turned on
startLanguage: 'en'
}
);});
<video id="demo" width="720" height="600" controls="controls" preload="auto">
<!-- MP4 for Safari, IE9, iPhone, iPad, Android, and Windows Phone 7 -->
<source type="video/mp4" src="{{ STATIC_URL }}/video/sample.m4v" />
<!-- Optional: Add subtitles for each language -->
<track label="English" srclang="en" kind="subtitles" type="text/vtt" src="{{ STATIC_URL }}video/sample.vtt" />
</video>
Say I want to add a link that contains the time information (e.g., 10 seconds from the beginning), and when I click on it, the video should plays starting not from the beginning, but from 10 seconds and onwards. In the following transcript. The time 00:00:10 is a link that can be clicked on. Could anyone give me some pointers on how to do this?
...
Line 158: That is a good word. 00:00:10
...

The previous answer suggested to use currentTime(), which is a get/set method in HTML5 but only a get method in MEJS. You should rather use (MEJS') setCurrentTime(), to set the starting time so, having a button like
<button class="button" id="play">play : starts at 8 seconds</button>
... you could use this jQuery code :
var media; // we need this global variable
jQuery(document).ready(function ($) {
$("video").mediaelementplayer({
success: function (mediaElement, domObject) {
media = mediaElement; // make it available for other functions
}
});
$(".button").on("click", function () {
media.setCurrentTime(8); // set starting time
media.play();
});
}); // ready
... or you could have more buttons (with different IDs) to set more actions like
$("#parentContainer").on("click", ".button", function (event) {
if (event.target.id == "play") {
media.setCurrentTime(8);
media.play();
}
if (event.target.id == "pause") {
media.pause();
}
});
Note: video should be preloaded for set properties to work.

Use html5 player play() and currentTime:
HTML:
<button id="time" onClick="playVideo()">00:00:16</button>
<video id="demo" width="30%" height="auto" controls="controls" preload="auto">
<source type="video/mp4" src="http://clips.vorwaerts-gmbh.de/VfE_html5.mp4" />
</video>
JS:
<script type="text/javascript">
var time = document.getElementById("time").innerHTML;
var parts = time.split(':');
var seconds = (+parts[0]) * 60 * 60 + (+parts[1]) * 60 + (+parts[2]);
function playVideo() {
var video = document.getElementById("demo");
video.currentTime = seconds;
video.play();
}
</script>

Related

VideoJS - Disable auto fullscreen after pressing play button

I switched to VideoJS thanks to ridicilious pricing policy of JWPlayer.
The problem is, when the user starts the video on iOS, it toggles native fullscreen. I want control panel to be available on fullscreen mode but I couldn't manage it yet.
Code:
<video id="tvideo" class="video-js vjs-default-skin vjs-big-play-centered" controls preload="auto" poster="..." data-setup='{"language":"en", "controls": true,"autoplay": false, "fluid": true, "aspectRatio": "16:9", "playbackRates": [0.5, 1, 1.5, 2]}'>
<source src="..." type='video/mp4' label='240p' res='240'/>
<source src="..." type='video/mp4' label='360p' res='360'/>
<source src="..." type='video/mp4' label='720p' res='720'/>
<p class="vjs-no-js">Bu videoyu görüntülemek için lütfen JavaScript'i etkinleştirin.</p>
</video>
<script type="text/javascript">
var myPlayer = videojs("#tvideo");
myPlayer.videoJsResolutionSwitcher({
default: 'high',
dynamicLabel: true
});
myPlayer.persistvolume({
namespace: 'httpswwwseyredelimcom'
});
myPlayer.brand({
image: "...",
title: "...",
destination: "...",
destinationTarget: "_top"
});
myPlayer.ready(function() {
this.hotkeys({
volumeStep: 0.1,
seekStep: 5,
enableModifiersForNumbers: false
});
$(".bAd").detach().appendTo(".video-js");
$(".plAd").detach().appendTo(".video-js");
function resizeVideoJS() {
var containerWidth = $('.video-player').width();
var videoHeight = Math.round((containerWidth / 16) * 9);
myPlayer.width(containerWidth).height(videoHeight);
}
window.onresize = resizeVideoJS;
myPlayer.on("ended", function() {
startNextVideo();
});
});
</script>
How could I manage not getting autofull screen and let user have control panels on fullscreen?
Thanks in advance.
To preserve inline playing, add playsinline attribute to video tag.
Actually, this won't work as described for video.js. It works for the straight-up html5 player.
For video.js, you need to use .playsinline(true) as you do so set other properties on an object. You could call it on .ready().
This method worked for me:
instanceName.ready(function(){
myPlayer = this;
myPlayer.playsinline(true);
});
https://docs.videojs.com/player#playsinline

HTML5 Video - How to do a seamless play and/or loop of several videos?

How can I reliably play several videos one after another seamlessly? As there is a small pause or flicker between playing 2 videos.
In my particular example I have 3 videos. I need to play all 3 of them seamlessly one after another, and I also need to loop middle video an arbitrary number of times (say 2 or 3). All of that needs to happen seamlessly and consistently across different browsers.
I've been trying everything under the moon, from starting video playback on video end, to using several video tags and hiding and replacing them, I even tried to implement this in Flash, but alas nothing works, and the same problem happens in current Flash as well.
I've seen this (or similar) question asked many times but I haven't seen a reliable solution yet.
Does anyone know a solution to this?
After trying various things I have finally been able to create what seems to be a working solution. I haven't tested this on older browsers or other OSes, but this works on latest versions of Chrome, IE, Firefox and Opera. (Although some more feedback of whether this works on other systems would be appreciated)
The idea is to have all 3 videos output frames to HTML5 canvas. The original videos are hidden and preloaded in advance to avoid pause between loading.
Here is the code:
var playCounter = 0;
var clipArray = [];
var $video1 = $("#video1");
var $video2 = $("#video2");
var $video3 = $("#video3");
$video1.attr("src", "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerEscapes.mp4");
$video2.attr("src", "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerJoyrides.mp4");
$video3.attr("src", "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerFun.mp4");
var timerID;
var $canvas = $("#myCanvas");
var ctx = $canvas[0].getContext("2d");
function stopTimer() {
window.clearInterval(timerID);
}
$('#startPlayback').click(function() {
stopTimer();
playCounter = $('#playbackNum').val();
clipArray = [];
// addd element to the end of the array
clipArray.push(1);
for (var i = 0; i < playCounter; i++) {
clipArray.push(2);
}
clipArray.push(3);
$video2[0].load();
$video3[0].load();
$video1[0].play();
});
function drawImage(video) {
//last 2 params are video width and height
ctx.drawImage(video, 0, 0, 640, 360);
}
// copy the 1st video frame to canvas as soon as it is loaded
$video1.one("loadeddata", function() {
drawImage($video1[0]);
});
// copy video frame to canvas every 30 milliseconds
$video1.on("play", function() {
timerID = window.setInterval(function() {
drawImage($video1[0]);
}, 30);
});
$video2.on("play", function() {
timerID = window.setInterval(function() {
drawImage($video2[0]);
}, 30);
});
$video3.on("play", function() {
timerID = window.setInterval(function() {
drawImage($video3[0]);
}, 30);
});
function onVideoEnd() {
//stop copying frames to canvas for the current video element
stopTimer();
// remove 1st element of the array
clipArray.shift();
//IE fix
if (!this.paused) this.pause();
if (clipArray.length > 0) {
if (clipArray[0] === 1) {
$video1[0].play();
}
if (clipArray[0] === 2) {
$video2[0].play();
}
if (clipArray[0] === 3) {
$video3[0].play();
}
} else {
// in case of last video, make sure to load 1st video so that it would start from the 1st frame
$video1[0].load();
}
}
$video1.on("ended", onVideoEnd);
$video2.on("ended", onVideoEnd);
$video3.on("ended", onVideoEnd);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div id="border">
<video id="video1" width="640" height="360" hidden>
<source type="video/mp4">
Your browser does not support playing this Video
</video>
<video id="video2" width="640" height="360" hidden>
<source type="video/mp4">
Your browser does not support playing this Video
</video>
<video id="video3" width="640" height="360" hidden>
<source type="video/mp4">
Your browser does not support playing this Video
</video>
<div>
<canvas id="myCanvas" width="640" height="360"> </canvas>
</div>
<div role="controls">
<div>
<label>
Times the middle video will repeat itself:
</label>
</div>
<div>
<input id="playbackNum" value="1" />
</div>
<p>
<button id="startPlayback">Start</button>
</p>
</div>
</div>
Please note, the code is not very pretty and would benefit from some cleanup and optimization, but at least this should show the way to work around the problem and implement a seamless playback of several videos in HTML5.
Also make sure to include jQuery source file in html file location for the code to work.
I have used VideoJS for some time and it allows seamless video playing.
http://videojs.com
You will be required jQuery for this. There are many other jQuery video players.

NaN out of get duration in Javascript

I have a problem to get out the duration of an mp4 video file when the html document is ready. My code:
(function ($, root, undefined) {
$(function () {
'use strict';
$(document).ready(function() {
var duration = $("section:first-child() video").get(0).duration;
alert(duration);
});
});
});
The script works in firefox but in chrome it returns an NaN. Im not a javascript professional and i use wordpress HTML5 Blank theme.
Thanks for your help and best regards.
You need to preload the video metadata for you to be able to access them. Then, within the loadedmetadata event, you may access the duration as below.
$(function() {
var $video = $('#video_container').find('video');
$video.on("loadedmetadata", function() {
$('#duration').text($video[0].duration);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="video_container">
<video poster="http://media.w3.org/2010/05/sintel/poster.png" preload="metadata" controls="" width="400">
<source type="video/mp4" src="http://media.w3.org/2010/05/sintel/trailer.mp4" id="mp4"></source>
<source type="video/webm" src="http://media.w3.org/2010/05/sintel/trailer.webm" id="webm"></source>
<source type="video/ogg" src="http://media.w3.org/2010/05/sintel/trailer.ogv" id="ogv"></source>
<p>Your user agent does not support the HTML5 Video element.</p>
</video>
</div>
<div>Total duration : <span id="duration"></span></div>
you need a listener to get the duration of a video
var videoTime = 0;
var currentvideo = document.getElementById('video');
currentvideo.addEventListener('play', function() {
videoTime= currentvideo.duration;
console.info(videoTime) // get the duration
});

Prevent reset of currentTime when video loads?

I want to be able to reload the video into the HTML5 video without having to reset the currentTime when it is loaded. The way I am currently doing it is the following:
<button onclick="getCurTime()" type="button">Get current time position</button>
<button onclick="setCurTime()" type="button">Set time position to 5 seconds</button><br>
<div style="width:800px; height:445px;">
<video id="myVideo" width="100%" height="100%" controls="controls">
<source src="http://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_320x180.mp4" type="video/mp4">
</video>
<script>
var vid = document.getElementById("myVideo");
function setCurTime() {
vid.currentTime=100;
}
$(document).ready(function ()
{
$('#myVideo').videocontrols(
{
preview:
{
sprites: ['big_bunny_108p_preview.jpg'],
step: 10,
width: 200
},
theme:
{
progressbar: 'blue',
range: 'pink',
volume: 'pink'
}
});
vid.play();
});
setInterval(function(){
if(vid.currentTime > vid.duration-1)
{
myVideo.src = "http://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_320x180.mp4";
myVideo.load();
myVideo.play();
vid.currentTime = vid.duration-60*5
}
}, 1);
</script>
</div>
How would I go about doing this? Is there even a way to just update the data in the video player without having to reload the video? I want to be able to do this so if someone makes a modification to the video, it will just update the data in the video player so the user doesn't have to reload the whole video again.
per discussion in comment thread above, I'm still not 100% sure why you're reloading the same video so I may be missing some context, but the following code will let you change the video source but preserve the current time. It does assume jQuery for the event handler (though you can easily use the regular javascript event handler on the same event to do the same thing)
<video id="v" width="320" height="240" controls="controls" mute>
<source src="Video.mp4" />
</video>
<button onclick="reload()">Reload</button>
<script>
function reload() {
vid=document.getElementById("v")
// record the current time for the video that is playing
curTime = vid.currentTime
// set the source for the replacement video...
vid.src = "http://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_320x180.mp4";
// ... and load it
vid.load();
// add event handler for "canplay" to set the time, and then start the video
$("#v").on("canplay",function() {
vid.currentTime = curTime
vid.play();
// remove the event to stop it triggering multiple times
$("#v").off("canplay")
})
}
</script>

How to take youtube screenshot

<script src="jquery.js"></script>
<video id="video" controls preload="none" width="640" poster="http://media.w3.org/2010/05/sintel/poster.png" onloadedmetadata="$(this).trigger('video_really_ready')">
<source id='mp4' src="http://media.w3.org/2010/05/sintel/trailer.mp4" type='video/mp4' />
<source id='webm' src="http://media.w3.org/2010/05/sintel/trailer.webm" type='video/webm'/>
<source id='ogv' src="http://media.w3.org/2010/05/sintel/trailer.ogv" type='video/ogg' />
</video>
<br />
<input type="button" id="capture" value="Capture" /> Press play, and then start capturing
<div id="screen"></div>
<script>
var VideoSnapper = {
/**
* Capture screen as canvas
* #param {HTMLElement} video element
* #param {Object} options = width of screen, height of screen, time to seek
* #param {Function} handle function with canvas element in param
*/
captureAsCanvas: function(video, options, handle) {
// Create canvas and call handle function
var callback = function() {
// Create canvas
var canvas = $('<canvas />').attr({
width: options.width,
height: options.height
})[0];
// Get context and draw screen on it
canvas.getContext('2d').drawImage(video, 0, 0, options.width, options.height);
// Seek video back if we have previous position
if (prevPos) {
// Unbind seeked event - against loop
$(video).unbind('seeked');
// Seek video to previous position
video.currentTime = prevPos;
}
// Call handle function (because of event)
handle.call(this, canvas);
}
// If we have time in options
if (options.time && !isNaN(parseInt(options.time))) {
// Save previous (current) video position
var prevPos = video.currentTime;
// Seek to any other time
video.currentTime = options.time;
// Wait for seeked event
$(video).bind('seeked', callback);
return;
}
// Otherwise callback with video context - just for compatibility with calling in the seeked event
return callback.apply(video);
}
};
$(function() {
$('video').bind('video_really_ready', function() {
var video = this;
$('input').click(function() {
var canvases = $('canvas');
VideoSnapper.captureAsCanvas(video, { width: 160, height: 68, time: 40 }, function(canvas) {
$('#screen').append(canvas);
if (canvases.length == 4)
canvases.eq(0).remove();
})
});
});
});
</script>
How can I add youtube video instead. Could not play youtube video in video tag. embed tag is working to play youtube video. How to take screenshot by placing youtube video inside embed tag. Please help me
I could solve this with ffmpeg.
Just run
ffmpeg -i inputfile.avi -r 1 -t 1 -ss 00:00:03 image-%d.jpeg
where
-i inputfile.avi - input file
-r 1 - one frame per second
-t 1 - how many seconds should be converted to images
-ss 00:00:03 - from what second to start
image-%d.jpeg - resulting filename template
Found here http://linuxers.org/tutorial/how-extract-images-video-using-ffmpeg
The following bookmarklet capture a Youtube video at click time, in the current video resolution and quality, as you are seeing it, but without the toolbars overlays.
javascript:void(function(){let canvas=document.createElement("canvas"),video=document.querySelector("video"),ctx=canvas.getContext("2d");canvas.width=parseInt(video.offsetWidth),canvas.height=parseInt(video.offsetHeight),ctx.drawImage(video,0,0,canvas.width,canvas.height);var base64ImageData=canvas.toDataURL("image/jpeg"),o = new Date(0),p = new Date(video.currentTime*1000),filename="📷Capture_"+new URL(document.location.href).searchParams.get("v")+"_"+document.title+"#"+new Date(p.getTime()-o.getTime()).toISOString().split("T")[1].split("Z")[0]+".jpg",a=document.createElement("a");a.download=filename,a.href=base64ImageData,a.click()}());
Enhancement of the bookmarklet found here https://github.com/ReeganExE/youtube-screenshot.:
Image served as file download.
Does not block the playing video.
The image title contains the Youtube ID, the video title, and the exact time of the capture in the video.
Modified to work also in Firefox
If manually set up image this might be help you.
Try add poster="placeholder.png" //photo you want to the video tag.
example
<video width="470" height="255" poster="placeholder.png" controls>
<source src="video.mp4" type="video/mp4">
<source src="video.ogg" type="video/ogg">
<source src="video.webm" type="video/webm">
<object data="video.mp4" width="470" height="255">
<embed src="video.swf" width="470" height="255">
</object>
</video>

Categories

Resources