Playing youtube video randomly on element's background - javascript

Currently, I'm using this jquery which gets youtube video and plays them in element's background.
I was provided with this code that will play single youtube video. But I would like to make a list of videos and play them randomly... I am not so good with Javascript at the moment, so I would really appreciated some help on this...
right now I have this....
I wanna make a list of videos and play them randomly like a shuffled playlist..
$(function()
{
var videos = ['xJvt2SDV7ck', 'x6DD1k4BAUg', 'xJvt2SDV7ck'];
var index = Math.floor(Math.random() * videos.length);
var Video_back = new video_background($("#bgvideo"),
{
"position": "absolute", //Stick within the div
"z-index": "-1", //Behind everything
"loop": true, //Loop when it reaches the end
"autoplay": true, //Autoplay at start
"muted": true, //Muted at start
"youtube": "videos[index]", //Youtube video id
"start": 0, //Start with 6 seconds offset (to pass the introduction in this case for example)
"video_ratio": 1.333, // width/height -> If none provided sizing of the video is set to adjust
"fallback_image": "videos/main.jpg", //Fallback image path
});
});
Currently It only plays 1 video randomly selected from the list(single loop).
I want to make it so that it will move on to another video when the first video finishes..
HELP WILL BE MUCH MUCH APPRECIATED! THANK YOU FOR YOUR TIME!

The following answer is based on the fact that there is no way of determining when a video has finished. The lengths are in milliseconds:
$(function()
{
var videos =
[
{ id : 'xJvt2SDV7ck', length : 60000 },
{ id : 'x6DD1k4BAUg', length : 125000 },
{ id : 'xJvt2SDV7ck', length : 166000 }
];
function playNext()
{
var index = Math.floor(Math.random() * videos.length);
alert( "Playing next movie => " + videos[index].id );
var Video_back = new video_background($("#bgvideo"),
{
"position": "absolute", //Stick within the div
"z-index": "-1", //Behind everything
"loop": true, //Loop when it reaches the end
"autoplay": true, //Autoplay at start
"muted": true, //Muted at start
"youtube": videos[index].id, //Youtube video id
"start": 0, //Start with 6 seconds offset (to pass the introduction in this case for example)
"video_ratio": 1.333, // width/height -> If none provided sizing of the video is set to adjust
"fallback_image": "videos/main.jpg", //Fallback image path
});
setTimeout(function()
{
playNext();
}, videos[index].length);
}
playNext();
});

Related

Change player volume value in JS/HTML5 Player, but volume stays the same

I want to lower the default volume on an HTML player.
I can alter the values here:
`setAttributes(volumeSlider, { "type": "range", "min": "0", "max": "1", "step": "any", "value": "1", "orient": "vertical", "id": "volumeSlider" });`
http://codepen.io/Teeke/pen/MJPoOr
Changing value: 1 to 0.1 will make the volume slider lower to 10 per cent, but the playback track volume stays the same.
I've also tried muting and altering values on these two functions, with no effect:
function volumizer() {
if (audioTrack.volume == 0) { setText(muteButton,"volume"); }
else { setText(muteButton,"volumehigh"); }
}
function muter() {
if (audioTrack.volume == 0) {
audioTrack.volume = restoreValue;
volumeSlider.value = restoreValue;
} else {
audioTrack.volume = 0;
restoreValue = volumeSlider.value;
volumeSlider.value = 0;
}
}
What value do I need to change to lower the track volume programmatically?
What am I missing here... Your example works fine.
When I change the slider, the volume of the track changes both visually, in the console and as audio on this machine.
If it does not for you it might be a browser issue. I use Chrome Version 56.0.2924.87.
To see values in the console, press the console button on the lower left and use the console.log function:
volumeSlider.addEventListener("input", function(){
console.log(['beforeVolChng', volumeSlider.value, audioTrack.volume]);
audioTrack.volume = volumeSlider.value;
console.log(['afterVolChng', volumeSlider.value, audioTrack.volume]);
}, false);
Console.log can take anything: primitive types (int, float, char), objects and arrays etc.
So if your issue is: you want the playback volume on your slider to be applied when you start playing. Let me see.
Here this would be a good solution:
audioTrack.addEventListener('playing',
function(){
playhead.max = audioTrack.duration;
audioTrack.volume = volumeSlider.value;
}, false);

Resizing HTML multiple full width videos with javascript

I know that it's possible to use CSS to make video full width on a page, but I am using a Javascript library to display the videos because it has some nice skinning and other functionality in the template I'm using. It works great for a single video but the template hard codes the resize to an ID tag and I'm struggling to get it to work with multiple, different videos with different ID tags. The second container doesn't resize. Here is the code:
<section class="wrapper">
<section class="full-width">
<video id="video1" controls poster="img/poster.jpg" >
<source src="media/sample.mp4" type="video/mp4"/>
</video>
</section>
</section>
<!-- video2 markup is almost identical to video1 -->
function htmlVideo() {
videojs("video1", {
controlBar: {
timeDivider: false,
fullscreenToggle: false,
playToggle: false,
remainingTimeDisplay: false
},
"height": "auto",
"width": "auto"
}).ready(function() {
var myPlayer = this;
var aspectRatio = 9 / 16;
function resizeVideoJS() {
var width = document.getElementById(myPlayer.id()).parentElement.offsetWidth;
myPlayer.width(width).height(width * aspectRatio);
// I added these two lines but they don't work
var width2 = document.getElementById("video2").parentElement.offsetWidth;
document.getElementById("video2").width(width2).height(width2 * aspectRatio);
}
resizeVideoJS();
window.onresize = resizeVideoJS;
});
// I added the following code as well trying to initialize the
// video, but it doesn't work
videojs("video2", {
controlBar: {
timeDivider: false,
fullscreenToggle: false,
playToggle: false,
remainingTimeDisplay: false
},
"height": "auto",
"width": "auto"
}).ready(function() {
resizeVideoJS();
});
}
Be sure that each player instance refers to a player object (as provided by the library), as opposed to directly referring to the video element dom node.

Video.js remove poster when using currentTime before video starts

I have a playlist of videos, with a list of each video in a sidebar. When I click on the name of the video I want to load in the sidebar, the player switches the current video to the one I just clicked.
Some videos have sections, and those sections need to start playing at a certain time in the video. For example, I have a video with 2 sections, Section 1 starts at 0:00, but when I click on "Section 2" in the sidebar, the video should start playing at 1:30 seconds into the video.
Now I got this working with the following code, but the poster image is still playing over the video when I click on Section 2 which should start playing in the middle of the video. How can I get rid of the poster image when starting a video with currentTime offset?
(function($) {
var current, gototime;
var istime = false;
// video.js object
var $player = videojs('ppi-video');
$('a').on('click', function(e) {
e.preventDefault();
var attr = $(this).attr('data-video');
var time = $(this).attr('data-time');
if(typeof time !== 'undefined' && time !== false) {
istime = true;
gototime = time;
}else {
istime = false;
gototime = undefined;
}
// If link has data-video attribute... continue
if(typeof attr !== 'undefined' && attr !== false) {
if( current == attr ) return;
var image_path = "images/screens/";
var content_path = "source/";
// Wait till player is ready
$player.ready(function() {
// Hide the player?
$("#ppi-video_html5_api").fadeOut(400, function() {
// Change poster
$("#ppi-video_html5_api").attr('poster', image_path + attr + ".jpg");
$player.poster(image_path + attr + ".jpg");
});
$player.src([
{ type: "video/mp4", src: content_path + attr + ".mp4" },
{ type: "video/webm", src: content_path + attr + ".webm" },
]);
// Set the currently playing variable
current = attr;
$("#ppi-video_html5_api").fadeIn();
});
}
});
function updateVideo() {
if( istime ) {
$player.currentTime(gototime);
$player.ready(function() {
/**
* Trying to get rid of poster here, but not working
*/
$("#ppi-video_html5_api").attr('poster', '');
$player.poster('');
$player.play();
});
}else {
$player.currentTime(0);
}
}
// update video when metadata has loaded
$player.on('loadedmetadata', updateVideo);
})(jQuery);
I found myself in the same situation where i needed to programmatically hide the poster image. (i wanted the posterimage to hide on drag of a custom scrubbar)
I found two ways that might help someone else who is in the same situation (i know this is an old post, but i came across it looking for an answer).
First and most simply you can hide the poster image using css:
.vjs-poster.vjs-poster.vjs-poster {
display: none;
}
// specificity bumped for default css, your mileage may vary.
However because i wanted this to be done on drag event i figured i might as well just use js:
player.posterImage.hide();
It looks like on Chrome and Firefox, setting currentTime() needs to be delayed a bit. What I did was call play() and then pause() to remove the poster before the video starts. Then I set a timeout of 200 milliseconds which has a callback which then calls currentTime().
Kind of a makeshift workaround but it is working nicely.

Custom transition timing in impress.js

I'm trying to create different transition times for each slide in an impress.js presentation.
I found the code below in a book about impress.js. But checking it on JSLint it shows errors. I am not good enough with javascript to correct this myself. Anybody willing to help me out?
Edit: I need a solution without jQuery. This is because impress.js allows you to navigate through the presentation with spacebar and arrow keys and I don't want to lose that functionality.
I found that when navigating with the keys (while jQuery is timing the auto-advance) it does not respect the position where you navigated to, but forces you away from where you are. I would like instead that if you navigate to a slide (position) the auto-advance starts running the custom set time for that particular slide and advances to the next slide when the set amount of time has passed. This would be an awesome addition to impress.js. I hope this can be done. Thanks for your effort!
JSFiddle: http://jsfiddle.net/5sSE5/8/ (script added at the end of impress.js)
var step_transitions = [
{ "slide": 1, "duration": 2000 },
{ "slide": 2, "duration": 4000 },
{ "slide": 3, "duration": 1000 }
];
$(document).ready(function () {
var time_frame = 0;
step_transitions.filter(function (steps) {
time_frame = time_frame + steps.duration;
setTimeout(function () {
api.goto(steps.slide);
}); time_frame;
});
});
Addition: below script respects keyboard navigation, but all the slides have the same transition time.
var impress = impress();
impress.init();
document.addEventListener('impress:stepenter', function(e){
if (typeof timing !== 'undefined') clearInterval(timing);
var duration = (e.target.getAttribute('data-transition-duration') ? e.target.getAttribute('data-transition-duration') : 10000); // in ms
timing = setInterval(impress.next, duration);
});
There is an error in your code in the setTimeout:
setTimeout(function () {
api.goto(steps.slide);
}, time_frame);
It seems that the time_frame variable should be second argument of the setTimeout method.
Update
You also forgot to initialize the api variable before using it:
var api = impress();
You also need the jQuery library to be able to use the $ function.
See updated fiddle
Update 2
I reworked your code to make it continue from the first slide after the last is reached:
var step_transitions = [
{ "slide": 0, "duration": 3000 },
{ "slide": 1, "duration": 4000 },
{ "slide": 2, "duration": 2000 }
];
$(document).ready(function () {
var time_frame = 0,
api = impress(),
current_step_index = 0,
do_transition = function (){
var step = step_transitions[current_step_index];
api.goto(step.slide);
current_step_index++;
if(current_step_index >= step_transitions.length){
current_step_index = 0;
}
setTimeout(do_transition, step.duration);
};
//initial run
do_transition();
});
Note, that slides must start from 0, not 1.
See updated fiddle

Configure VideoJS Flash fallback

Since Firefox doesn't allow me to use an .mp4 file in the <video>-tag, I have to use the Flash-fallback on my VideoJS player.
For Chrome, Safari and IE, I can configure my VideoJS player with javascript to do pretty much anything. For example I like to loop it 5 times, hide the controls and mute the video. No issue there for the HTML5 version:
// Initialize the video with some settings
videojs(videoID, {
"controls": false,
"autoplay": false,
"preload": "auto",
});
var myVideo = videojs(videoID);
// Set the counter
var loop_count = 1;
// Function to loop the video exaclty 5 times
var loopInstagramVideo = function() {
if (loop_count <= 5) {
myVideo.play();
loop_count++;
} else {
loop_count = 1;
}
};
// Function to manipulatie the playing video (mute, no controls,...)
var setVideoOptions = function() {
myVideo.muted(1);
myVideo.controls(0);
};
// Set functions on the video
myVideo.on("play", setVideoOptions);
myVideo.on("ended", loopInstagramVideo);
So I would like to do the same for the Flash version.
The code above is generating an error on the videojs-call with the error:
TypeError: The element or ID supplied is not valid. (videojs)
Any thoughts on how to tackle this issue?
While this isn't an answer for your "looping" question, I just myself discovered that after calling videojs() on an element, the ID changes. Whether it's the ID of the element changes or the focus of the videojs call changes I don't know. The error pertaining to the ID not being valid is being caused by your first and second videojs() calls.
I would change this:
videojs(videoID, {
"controls": false,
"autoplay": false,
"preload": "auto",
});
var myVideo = videojs(videoID);
To this:
var myVideo = videojs(videoID);
myVideo.controls = false;
myVideo.autoplay = false;
myVideo.preload = "auto";
OR put those properties in the video tag itself.

Categories

Resources