Read Video path using javascript - javascript

How to read video path using javascript and pass it to html source value. Currently I am using hard coded from my html to read video and I want it to be dynamic to javascript. Here is my Temporary loading from content folder in my project:
<video id="video" controls preload="metadata" style="width:100%; height:100%">
<source src="~/Content/Videos/Sample_Vid.mp4" type="video/mp4">
</video>

If I understand your question correctly then you could:
implement a function like setVideoSource() as shown below, which would allow you to set/change the source of a video element that already exists in your page or,
implement a function like addVideo() as shown below, which would allow you to dynamically create/add a new video element to your page with a source of your choosing
Please see the documentation below for detail on how both functions work:
/*
Updates the source of first video in the document matching the selector
*/
function setVideoSource(selector, src) {
const element = document.querySelector(selector);
/*
Check that element is video before proceeding
*/
if(element.nodeName === 'VIDEO') {
/*
If element is a video, remove any source children if present
*/
for(const source of element.querySelectorAll('source')) {
element.removeChild(source);
}
/*
Create a new source element and populate it with the src
attribute
*/
const source = document.createElement('source');
source.setAttribute('src', src);
/*
Add source element to the video we're updating
*/
element.appendChild(source);
}
}
/*
Adds a new video to the document under the first element matching the parentSelector
*/
function addVideo(parentSelector, src, width, height) {
const parent = document.querySelector(parentSelector);
/*
Check that parent exists before proceeding
*/
if(parent) {
/*
Create new video element
*/
const video = document.createElement('video');
video.setAttribute('controls', true);
if(width) {
video.setAttribute('width', width);
}
if(height) {
video.setAttribute('height', height);
}
/*
Create a new source element and populate it with the src
attribute
*/
const source = document.createElement('source');
source.setAttribute('src', src);
/*
Add source element to the video we're inserting and add
the video element to the document element
*/
video.appendChild(source);
parent.appendChild(video);
}
}
// Update source of existing video
setVideoSource('#video', 'https://www.w3schools.com/html/mov_bbb.mp4')
// Add a new video to the page
addVideo('#parent', 'https://www.w3schools.com/html/mov_bbb.mp4', '100%', '150px')
<h3>Existing video dynamically updated with JavaScript</h3>
<video id="video" controls preload="metadata" style="width:100%; height:100%">
<source src="~/Content/Videos/Sample_Vid.mp4" type="video/mp4">
</video>
<h3>New video dynamically added to page with JavaScript</h3>
<div id="parent">
</div>
Hope that helps!

Related

videojs dynamic source update not working

I had this running before but after few years it seems it has stopped working.
Using videojs v7.3.0, and the plugin codebase is located in the local project directory itself.
<link rel="stylesheet" type="text/css" href="<?php echo Utility::getAssetsPath('videojs/video-js.min.css'); ?>" >
<script src="<?php echo Utility::getAssetsPath('videojs/video.min.js'); ?>"></script>
<div id="light">
<a class="boxclose" id="boxclose" onclick="lightbox_close();"></a>
<video id="video_player_frame" class="video-js vjs-default-skin" controls preload="none" width="595" data-setup="{}">
<source src="http://vjs.zencdn.net/v/oceans.mp4" type="video/mp4">
<!--Browser does not support <video> tag -->
<p class="vjs-no-js">Javascript is disabled.</p>
</video>
</div>
<a href="javascript:void(0);" onclick="lightbox_open(this);" data-link="<?php echo $list['file_path']; ?>">
</a>
I had to add a default video source or else it threw No Compatible source was found for this media.
function lightbox_open(el) {
/* load link to video source attribute */
var link_string = el.getAttribute('data-link');
var video_player_el_src = document.getElementById('video_player_frame').getElementsByTagName('source')[0];
video_player_el_src.setAttribute('src', link_string);
videojs('video_player_frame').ready(function() {
lightBoxVideo = this;
/** check if the video is already viewed
* if not, push link to viewed_video_arr,
* and load the player
**/
if(!viewed_video_arr.includes(link_string)) {
viewed_video_arr.push(link_string); /* store the video link to the array */
lightBoxVideo.load(); /* reload the video player */
}
window.scrollTo(0, 0);
document.getElementById('light').style.display = 'block';
document.getElementById('fade').style.display = 'block';
lightBoxVideo.play();
});
}
This used to work but it seems it doesn't support updating the source this way.
Since the codebase for the library is not pulled from some CDN I think it should have worked the way it was working earlier.
Any idea where it went wrong?
Instead of lighbox.load(); you should load the actual <video> element (not at the <source> tag level).
Untested code example:
function lightbox_open(el)
{
//# load link to video source attribute
var link_string = el.getAttribute('data-link');
//var video_player_el_src = document.getElementById('video_player_frame').getElementsByTagName('source')[0];
//video_player_el_src.setAttribute('src', link_string);
let video_player_el_src = document.getElementById('video_player_frame');
video_player_el_src.setAttribute('src', link_string);
videojs('video_player_frame').ready( function()
{
lightBoxVideo = this;
/** check if the video is already viewed
* if not, push link to viewed_video_arr,
* and load the player
**/
if(!viewed_video_arr.includes(link_string))
{
//# store the video link to the array
viewed_video_arr.push(link_string);
//# reload the video player
//lightBoxVideo.load();
video_player_el_src.load();
}
window.scrollTo(0, 0);
document.getElementById('light').style.display = 'block';
document.getElementById('fade').style.display = 'block';
lightBoxVideo.play();
});
}

Randomize Background Video with Sound, after clicking function

I wrote this code a while back, and it allowed users to click and refresh the page to autoplay a RANDOM background video with sound.
This is the function that they click that loads the function
https://pastebin.com/0XXEHvQQ
<div align="center">
<p><font face="verdana" size="2">
<a onclick="ok()"> press me PLAY VIDS :)</a></font></p>
</div>
https://pastebin.com/PD5qdNDM
<div align="center">
<p><font face="verdana" size="2">
<a onclick="ok()"> -> press me to fix the site :) <-</a></font></p>
</div>
</div>
</div>
</div>
<!-- Scripts -->
<script src="js/parallax.js"></script>
<script>
// Pretty simple huh?
var scene = document.getElementById('scene');
var parallax = new Parallax(scene);
</script>
</script>
<script src="js/custom.js"></script>
<script>
let volumeInterval;
function loaded(){
setInterval(loop, 600);
volumeInterval = setInterval(volume, 1);
}
function unload(){
for (var i = 1; i < 99999; i++)
window.clearInterval(i);
console.log("unloaded");
}
function volume() {
try {
document.getElementsByTagName("video")[0].volume = 0.15;
console.log("done!");
clearInterval(volumeInterval);
}
catch (e) {
console.log("waiting..");
}
}
function ok() {
document.write(unescape(
and heres the unescaped code
https://pastebin.com/YJwbG2mC
<!-- VIDEO GRABBB -->
<video preload="auto" autoplay="true" loop="true">
<source id="player" src="5.mp4">
<script>
var video = document.currentScript.parentElement;
video.volume = 0.33;
//document.getElementById('player').currentTime = 20;
</script>
<script>
var video = document.getElementById("player");
video.addEventListener("timeupdate", function(){
if(this.currentTime >= 1000) {
location.reload();
}
});
</script>
<script type="text/javascript">
var video = document.getElementsByTagName('video')[0];
video.onended = function() {
location.reload();
};
</script>
<script>
document.getElementById("player").src = "/" + Math.floor((Math.random()*7)+1) + ".mp4";
</script>
</video>
No matter how I try to adjust the unescaped code, I can't get the MP4 to autoplay after clicking the function.
Here is my live site that I no longer can access: form.wtf
According to the HTML Spec on the Source Element,
Dynamically modifying a source element and its attribute when the element is already inserted in a video or audio element will have no effect. To change what is playing, just use the src attribute on the media element directly, possibly making use of the canPlayType() method to pick from amongst available resources. Generally, manipulating source elements manually after the document has been parsed is an unnecessarily complicated approach.
Therefore, no matter what you do to the source element, you can't change the video unless the new src is applied directly to the video element.
Replacing the source element also has no effect on the video that plays. The source element's src attribute may changed but the video will keep on playing.
Therefore, you should leave your source's src attribute empty until the JavaScript code sets it or
Leave out the source tag all together and apply the src straight to the video.
Math.floor(Math.random() * 7 + 1); is exactly the same thing as Math.ceil(Math.random() * 7);
document.querySelector('#player > source').src = `/${Math.ceil(Math.random() * 7)}.mp4`;
<video id="player" preload="auto" autoplay loop>
<source src="">
</video>

Change HTML 5 autoplayed video source dynamically

On my website https://cravydev.netlify.com I'm trying to change the video dynamically when the different headlines are in viewport.
I'm using a div with HTML 5 autoplay and loop properties, but not able yet to change the video source and load again when the specific headline is on screen. Here are the details.
HTML
<div class="iphone-sticky"></div>
<div class="iphone-video">
<video autoplay loop muted poster="assets/img/poster.png" id="iphonevideo">
<source id="video1" src="assets/img/iphone-video.mp4" type="video/mp4">
<source id="video2" src="assets/img/iphone-video-1.mp4" type="video/mp4">
</video>
JS
//Detect is element is in viewport
$(window).on('resize scroll', function() {
var player = document.getElementById('iphonevideo2');
if ($('#headline2').isInViewport()) {
var source = document.getElementById('video1');
$(source).attr("src", "assets/img/iphone-video-1.mp4");
player.pause();
player.load();
} else if ($('#headline3').isInViewport()) {
var source = document.getElementById('video1');
$(source).attr("src", "assets/img/iphone-video.mp4");
player.pause();
player.load();
}
});
EDIT
I have been able to solve it thanks to Kley comment. Now the problem is that the js logic does not check constantly the viewport visibility of headlines, only once. Also, the video is played while scrolling and the poster image appears, making the whole experience a little bit weird.
Any suggestion to solve that?
Thanks!
Check the page, it's not the viewport ()
I could tell you that you are changing the src every time you scroll while it is visible, this is causing the video to restart. You must make a validation, if it has already been changed the src should not be changed again.
Note that # headline2 is not visible when # headline3 is a bit up.
you have to scroll down until the end of the page to enter this condition.
You could use another smaller element at the beginning of each #headline to do this validation.
you could use the first p of the #headline
For example:
$(window).on('resize scroll', function() {
var player = document.getElementById('iphonevideo2');
if ($('#headline2 p').eq(0).isInViewport()) {
var source = document.getElementById('video1');
var url = "assets/img/iphone-video-1.mp4";
var src = $(source).attr("src");
// validate if you already have the src
if(src==url) return; // if exists src leaves function
$(source).attr("src", url);
player.pause();
player.load();
} else if ($('#headline3 p').eq(0).isInViewport()) {
var source = document.getElementById('video1');
var src = $(source).attr("src");
var url = "assets/img/iphone-video.mp4";
// validate if you already have the src
if(src==url) return; // if exists src leaves function
$(source).attr("src", url);
player.pause();
player.load();
}
})

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>

Save and load elements from webpage

I have in my webpage a series of elements, for example videos or other media:
<div id = "text">
</div>
<video height="240" width="412" id="video" controls="controls"> </video>
I change with JavaScript the original status of these elements and I use
Popcorn.js for create a synchronization events, for example:
var video = document.getElementById('video');
video.src = $("#url").val(); //Change src value
var popcorn = Popcorn( "#video" );
popcorn.footnote({ //Create a synchronization event; I add a footnote
start: 2,
stop: 5,
text: 'Hello World!!!',
target: 'text',
});
So now, my problem is that I want save these elements with their events.
And after I want to have the possibility to load (in the my webpage) this elements for continue to change them again.
How can I save/load in this case?

Categories

Resources