Randomize Background Video with Sound, after clicking function - javascript

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>

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();
});
}

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();
}
})

Turn off volume control and mute button in HTML5 video

We have some videos playing great in our HTML mobile app. However, our videos don't have sound, just subtitles, so we need to remove the volume slider and mute button but keep the timer bar.
Can this be done or toggled with HTML or CSS? Or is some javascript required to do this?
At the moment the setting within our html tag is just: controls="controls"
This has worked:
video::-webkit-media-controls-volume-slider {
display:none;
}
video::-webkit-media-controls-mute-button {
display:none;
}
Super easy:
Your html should be something like:
<video id="Video1">
<source src="..." type="video/mp4">
<source src="..." type="video/ogg">
Your browser does not support HTML5 video.
</video>
Add then a customized button to play the video:
<button id="play" onclick="vidplay()">></button>
Finally a progress bar:
<progress id="progressbar" value="0" max="100"></progress>
Then in javascript add a button to play
var video = document.getElementById("Video1");
function vidplay() {
var button = document.getElementById("play");
if (video.paused) {
video.play();
button.textContent = "||";
} else {
video.pause();
button.textContent = ">";
}
}
And a listener to update the progress bar:
video.addEventListener('timeupdate', updateProgressBar, false);
function updateProgressBar() {
var progressBar = document.getElementById('progressbar');
var percentage = Math.floor((100 / mediaPlayer.duration) * mediaPlayer.currentTime);
progressBar.value = percentage; progressBar.innerHTML = percentage + '% played';
}
So basically remove the "standard controls" and create your own ones.
If you wanted to achieve more complicated results, I would recommend you another option. This could be using a more configurable setting such as video.js.
Remove the controls attribute from the video element completely.
Try Here: http://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_video_controls. Remove the "controls" attribute and the bar will disappear.

Can't get HTML5 video to loop back to first frame.

I would like for an HTML5 video of mine to loop back to the first frame and pause after playback.
I found this page here and am using the code near the bottom of the page by "Offbeatmammal" which is:
<div id="vOverlay" style="position:relative; width:600px; height:300px; z-index:2;"></div>
<video style="position:relative; top:-300px; z-index:1;width:600px;height:340px;" width="600" height="409" id=videoPlayer controls="controls">
<source src="video.mp4" type="video/mp4">
</video>
<script>
var v = document.getElementById('videoPlayer');
var vv = document.getElementById('vOverlay');
<!-- Play, Pause -->
vv.addEventListener('click',function(e){
if (!v.paused) {
console.log("pause playback");
v.pause();
v.firstChild.nodeValue = 'Pause';
} else {
console.log("start playback")
v.play();
v.firstChild.nodeValue = 'Play';
}
});
</script>
I have found a few threads that seem to indicate i need to use this.currentTime = 0; but I have no clue where to add this to the code above. I tried several different places and it just isn't working. Any help is much appreciated.
Thanks!
When the video is finished. WHEN is key here. You need to search for the "playback finish" event.
seach google for "html5 video events" and you'll find this:
http://www.w3schools.com/tags/ref_av_dom.asp
then the code you need to write is:
v.addEventListener("ended", function(){
this.currentTime = 0;
});

Display video duration from videoJS

I am working on an HTML5 video player with jQuery. For now I have my video player working very well but I want to get the variable for the video duration and show/display it in pure HTML page.
So from here you can take more info about this Jquery video player:
http://www.videojs.com/docs/api/
I think the variable for video duration is: myPlayer.duration();
How I can display this value in HTML?
Here is my HTML code to display the player:
<video id="vemvo-player" class="video-js vjs-default-skin" controls autoplay="true" width="950" height="534"
data-setup="{}">
<source src="[var.base_url]/uploads/[var.video_play]" type='video/flv' />
</video>
This is what I have tried to display this variable but it says that it is = "0" when on the video player it says that it's 4min:
<video id="vemvo-player" class="video-js vjs-default-skin" controls autoplay="true" width="950" height="534"
data-setup="{}">
<source src="[var.base_url]/uploads/[var.video_play]" type='video/flv' />
</video>
<div id="duration"></div>
<script type="text/javascript">
_V_("vemvo-player").ready(function(){
var myPlayer = this;
var howLongIsThis = myPlayer.duration();
$('#duration').html('Duration: ' + howLongIsThis);
});
</script>
Where is my mistake?
You can try this. It works for me.
var myPlayer = videojs('vemvo-player');
if (myPlayer.readyState() < 1) {
// wait for loadedmetdata event
myPlayer.one("loadedmetadata", onLoadedMetadata);
}
else {
// metadata already loaded
onLoadedMetadata();
}
function onLoadedMetadata() {
alert(myPlayer.duration());
$('#duration').html("Duration: " + myPlayer.duration());
}
var player = videojs('my-video', {
fluid:false, // videojs settings
controls:true,
height: '300'
});
$(document).ready(function(){
console.log(player.duration());
// will return video duration. Can't be used while page is loading.
console.log(player.currentTime());
// will return current time if video paused at some time. Intially it would be 0.
});
Those who might come here and are using videojs with Vue 3, also might work with similar frameworks like React.
Referring to this code and component usage - https://docs.videojs.com/tutorial-vue.html you can do the following changes to get the duration, height, and width.
// New Code here
this.player = videojs(
this.$refs.videoPlayer,
this.options,
function onPlayerReady() {
console.log("onPlayerReady", this);
}
);
this.player.one("loadedmetadata", () => {
var duration = this.player.duration();
console.log(`Duration of Video ${duration}`);
console.log(`Original Width of Video ${this.player.videoWidth()}`);
});
I was having troubles to get the real duration of videos (using videojs v7.18.*) resulting in bugged custom progressbar! The problem was that player.duration() always returns rounded number while player.liveTracker.seekableEnd() returns the real value but only after start event.
For example, if real duration is 13.456s, these values are returned for videojs player object p:
| On ready | On load | On start
----------------------------|-------------|---------|----------
p.duration() | 0 | 14 | 14
p.liveTracker.seekableEnd() | 14 | 14 | 13.456
I've ended up with this solution in React:
const onDurationChange = () => {
const dur = player?.liveTracker.seekableEnd() || player?.duration() || 0;
setDurationInSec(dur);
}
return <video ref={videoRef} onDurationChange={onDurationChange}>
As you're using jQuery, that can be done much easier :) You can use $.html to edit the html contents of a dom element. Your code will look something like this:
<div id="duration"></div>
<script type="text/javascript">
_V_("vemvo-player").ready(function(){
var myPlayer = this;
var howLongIsThis = myPlayer.duration();
$('#duration').html('Duration: ' + howLongIsThis);
});
</script>

Categories

Resources