Javascript: Play website background videos in series? - javascript

I'm designing a landing page with video background. I'd like to auto-play a series of background video clips (looping back to #1 when the sequence runs out, although I haven't tried to integrate this wrinkle yet). I pulled some sample code off a reputable webdev blog and adapted it, but currently to no effect (my initial video plays once with the desired effect, but gives way to its poster image, rather than the next clip). Relevant html and js below. Help much appreciated!
<div id="video-box">
<video class="landing-video" autoplay muted poster="./resources/media/images/Two-Swimmers.jpg">
<source src="./resources/media/video/Two-Swimmers.mp4" type="video/mp4" />
</video>
<div class="video-playlist">
</div>
</div>
<script type="text/javascript" src="video.js"></script>
video.js code:
( function() {
var videoPlayer = document.getElementById( 'video-box' ),
video = videoPlayer.getElementsByClassName( 'landing-video' )[0],
playlist = videoPlayer.getElementsByClassName( 'video-playlist' )[0],
source = video.getElementsByTagName( 'source' ),
linkList = [],
videoDirectory = './resources/media/video/',
currentVideo = 0,
allLinks = playlist.children,
linkNumber = allLinks.length,
i, filename;
function playVideo( index ) {
allLinks[index].classList.add( 'current-video' );
currentVideo = index;
source[0].src = videoDirectory + linkList[index] + '.mp4';
video.load();
video.play();
}
for ( i = 0; i < linkNumber; i++ ) {
filename = allLinks[i].href;
linkList[i] = filename.match( /([^\/]+)(?=\.\w+$)/ )[0];
}
video.addEventListener( 'ended', function () {
allLinks[currentVideo].classList.remove( 'current-video' );
nextVideo = currentVideo + 1;
if ( nextVideo >= linkNumber ) {
nextVideo = 0;
}
playVideo( nextVideo );
} );
} () );

I changed video to have a src attribute, and I used setAttribute in the ended event handler.
var video = document.querySelector('video');
var links = document.querySelectorAll('.video-playlist > a');
var i = 0;
video.addEventListener('ended', function() {
i++;
if (i >= links.length) {
current = 0;
}
var a = links.item(i);
a.className = 'current-video';
video.setAttribute('src', a.href);
video.play();
});
<div id="video-box">
<video class="landing-video" autoplay muted src="https://www.w3schools.com/html/mov_bbb.mp4">
</video>
<div class="video-playlist">
</div>
</div>
I don't have your CSS so you can't see the <a> tags or the current-video class. I also don't have your video files so I grabbed some public videos for demonstration purposes.

Related

How to play multiple videos in html page

I want to play a video in a res of 720p (1280x720) with an autoplay and a loop whenever the video ends replace by another video in array.
the first video works fine, but it didn't autoplay, and after it end. it does not continue to play another video.
here's my code :
<div class="content-left">
<video controls id="myVideo" width="1280" height="720" autoplay></video>
<script>
var videoSource = new Array();
videoSource[0]='videos/bluevideo.mp4';
videoSource[1]='videos/redvideo.mp4';
videoSource[2]='videos/yellowvideo.mp4';
var videoCount = videoSource.length;
document.getElementById("myVideo").setAttribute("src",videoSource[0]);
function videoPlay(videoNum)
{
document.getElementById("myVideo").setAttribute("src",videoSource[videoNum]);
document.getElementById("myVideo").load();
document.getElementById("myVideo").play();
}
document.getElementById('myVideo').addEventListener('ended',myHandler,false);
function myHandler() {
i++;
if(i == (videoCount-1)){
i = 0;
videoPlay(i);
}
else{
videoPlay(i);
}
}
</script>
</div>
where did I do wrong? can anyone help me?thankyou very much.
You have a variable i which you increment in myHandler. However, it isn't declared anywhere. You should declare it outside the code of the event handler, and set the value to the first index:
var videoSource = new Array();
videoSource[0] = 'videos/bluevideo.mp4';
videoSource[1] = 'videos/redvideo.mp4';
videoSource[2] = 'videos/yellowvideo.mp4';
var videoCount = videoSource.length;
var i = 0;
document.getElementById("myVideo").setAttribute("src", videoSource[0]);
function videoPlay(videoNum) {
document.getElementById("myVideo").setAttribute("src", videoSource[videoNum]);
document.getElementById("myVideo").load();
document.getElementById("myVideo").play();
}
document.getElementById('myVideo').addEventListener('ended', myHandler, false);
function myHandler() {
i++;
if (i == videoCount) {
i = 0;
videoPlay(i);
} else {
videoPlay(i);
}
}

video play loop play another ja

I need a video to play and loop seamlessly a defined number of times, then skip to a next video and loop seamlessly a defined number of times, and so forth until the playlist ends.
In one page, a user defines videos to be played, as well as how many times it will "loop" (or iterate). These are stored using session variables as:
$_SESSION["Exer[" .$x. "]"]
$_SESSION["Reps[" . $x. "]"].
I'm ignoring this aspect (the php stuff) currently
I have code that independently works, one that loops and one that plays playlists, but I can't seem to manage the merger of them together to achieve functionality. The code is as followed:
HTML
<video width="320" height="240" id="myVideo" autoplay="autoplay">
</video>
JavaScript
For looping:
<script>
var iterations = 1;
document.getElementById('iteration').innerText = iterations;
document.getElementById('myVideo').src = "Video/01.mp4";
myVideo.addEventListener('ended', function () {
if (iterations < 3) {
this.currentTime = 0;
this.play();
iterations ++;
document.getElementById('iteration').innerText = iterations;
}
}, true);
</script>
For playlist:
<script>
var videoSource = new Array();
videoSource[0] = "Video/01.mp4";
videoSource[1] = "Video/02.mp4";
videoSource[2] = "Video/03.mp4";
videoSource[3] = "Video/04.mp4";
var i = 0; // define i
var videoCount = videoSource.length;
function videoPlay(videoNum) {
document.getElementById("myVideo").setAttribute("src", videoSource [videoNum]);
document.getElementById("myVideo").load();
document.getElementById("myVideo").play();
}
document.getElementById('myVideo').addEventListener('ended', myHandler, false);
videoPlay(0); // play the video
function myHandler() {
i++;
if (i == (videoCount - 1)) {
i = 0;
videoPlay(i);
} else {
videoPlay(i);
}
}
</script>
Any help is appreciated.
Please check this, this java script code will replay a video for mentioned number of times and then plays next video if exists in playlist:
var eachVdoLoop = 2;
var currentVdoLoop=0;
var videoSource = new Array();
videoSource[0] = "http://www.sample-videos.com/video/mp4/240/big_buck_bunny_240p_1mb.mp4";
videoSource[1] = "https://www.w3schools.com/html/mov_bbb.mp4";
var videoCount = videoSource.length;
var vdoIndex=0;
document.getElementById('myVideo').addEventListener('ended', myHandler, false);
nextVideo();
function myHandler() {
currentVdoLoop++;
if(currentVdoLoop < eachVdoLoop)
{
document.getElementById("myVideo").play();
}
else
{
vdoIndex++;
currentVdoLoop=0;
nextVideo();
}
}
function nextVideo() {
if(vdoIndex == videoSource.length)
{
alert("Playlist ended!!!")
return;
}
document.getElementById("myVideo").setAttribute("src", videoSource[vdoIndex]);
document.getElementById("myVideo").play();
}
An working jsfiddle (fiddle updated)

Trying to Loop an HTML5 Video Array

I'm running this array that plays the video array, but ends abruptly and doesn't loop. Of course I tried the HTML video attribute loop and loop="true" and loop="loop"... with no avail..
I just want to loop'it t'night:
var videos =
[
[
"img/poster.png",
"img/trippyInk.mp4"
],
[
"img/poster.png",
"img/brothaDive.webm"
],
[
"img/poster.png",
"img/wtuD97H.webm"
],
[
"img/poster.png",
"img/ride.webm"
]
];
function switchVideo(n) {
if (n >= videos.length) n = 0;
var mp4 = document.getElementById("mp4");
var parent = mp4.parentNode;
document._video.setAttribute("poster", videos[n][0]);
mp4.setAttribute("src", videos[n][1]);
document._video.load();
document._video.play();
I tried this command, this also didn't work.
$('video').attr('loop','loop');
}
Thanks!
Update
The key to making a series of video loop is to add your loop logic to the ended event.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>vidArray</title>
</head>
<body>
<video id="vid" src="https://glpjt.s3.amazonaws.com/so/av/vs2s3.mp4" poster="https://glpjt.s3.amazonaws.com/so/av/vs2s3.png" controls width="480" height="auto">
Your browser sux, why haven't you upgraded to Chrome or Firefox? Do you live in a cave?
</video>
<script>
var poster = ["https://glpjt.s3.amazonaws.com/so/av/vs8s3.png", "https://glpjt.s3.amazonaws.com/so/av/vs12s3.png", "https://glpjt.s3.amazonaws.com/so/av/vs21s3.png", "https://glpjt.s3.amazonaws.com/so/av/vs2s3.png"]
var videos = ["https://glpjt.s3.amazonaws.com/so/av/vs8s3.mp4", "https://glpjt.s3.amazonaws.com/so/av/vs12s3.mp4", "https://glpjt.s3.amazonaws.com/so/av/vs21s3.mp4", "https://glpjt.s3.amazonaws.com/so/av/vs2s3.mp4"]
var vid = document.getElementById("vid");
var n = videos.length;
var cnt = 0;
function playVideo(x) {
var png = poster[x];
console.log('poster: ' + png);
var mp4 = videos[x];
console.log('video: ' + mp4);
vid.setAttribute('poster', png);
vid.src = mp4;
vid.load();
vid.play();
}
vid.addEventListener('ended', next, false);
function next() {
cnt++;
if (cnt < n) {
playVideo(cnt);
} else {
cnt = 0;
playVideo(cnt);
}
}
</script>
</body>
</html>
I separated the arrays, it works. Added a button to cycle through the videos.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>vidArray</title>
</head>
<body>
<video id="vid" src="https://glpjt.s3.amazonaws.com/so/av/vs2s3.mp4" poster="https://glpjt.s3.amazonaws.com/so/av/vs2s3.png" loop controls width="480" height="auto">
Your browser sux, why haven't you upgraded to Chrome or Firefox? Do you live in a cave?
</video>
<button id="btn1">Next</button>
<script>
var poster = ["https://glpjt.s3.amazonaws.com/so/av/vs8s3.png", "https://glpjt.s3.amazonaws.com/so/av/vs12s3.png", "https://glpjt.s3.amazonaws.com/so/av/vs21s3.png", "https://glpjt.s3.amazonaws.com/so/av/vs2s3.png"]
var videos = ["https://glpjt.s3.amazonaws.com/so/av/vs8s3.mp4", "https://glpjt.s3.amazonaws.com/so/av/vs12s3.mp4", "https://glpjt.s3.amazonaws.com/so/av/vs21s3.mp4", "https://glpjt.s3.amazonaws.com/so/av/vs2s3.mp4"]
var n = videos.length;
var cnt = 0;
function switchVideo(n) {
var vid = document.getElementById("vid");
var png = poster[n];
console.log('poster: ' + png);
var mp4 = videos[n];
console.log('video: ' + mp4);
vid.setAttribute('poster', png);
vid.src = mp4;
vid.load();
vid.play();
}
var btn1 = document.getElementById("btn1");
btn1.addEventListener('click', function(e) {
cnt++;
if (cnt < n) {
switchVideo(cnt);
} else {
cnt = 0;
switchVideo(cnt);
}
}, false);
</script>
</body>
</html>
I think you're looking for:
$('video').attr('loop','loop');

HTML5/JavaScript audio playlist

I have found a nice tutorial on how to build a playlist using HTML5 and JavaScript in blog post HTML5 Audio and Video and how to make a playlist. I followed the instructions, but I did not get the correct outcome.
This code SHOULD play all three audio files in order and stop when the last song has ended, but it what it actually does is autoplay the first file then stops when the first file is completed. What did I do wrong?
<html>
<body>
<ul id="playlist">
<li class="active">
<a href="http://www.codenamejupiterx.com/song/soundtest.mp3">
soundtest
</a>
</li>
<li>
<a href="http://www.codenamejupiterx.com/song/soundtest2.mp3">
soundtest2
</a>
</li>
<li>
<a href="http://www.codenamejupiterx.com/song/soundtest3.mp3">
soundtest3
</a>
</li>
</ul>
<script>
var audio;
var playlist;
var tracks;
var current;
init();
function init(){
current = 0;
audio = $('#audio');
playlist = $('#playlist');
tracks = playlist.find('li a');
len = tracks.length - 1;
audio[0].volume = .10;
audio[0].play();
playlist.find('a').click(function(e){
e.preventDefault();
link = $(this);
current = link.parent().index();
run(link, audio[0]);
});
audio[0].addEventListener('ended',function(e){
current++;
if(current == len){
current = 0;
link = playlist.find('a')[0];
}
else{
link = playlist.find('a')[current];
}
run($(link),audio[0]);
});
}
function run(link, player){
player.src = link.attr('href');
par = link.parent();
par.addClass('active').siblings().removeClass('active');
audio[0].load();
audio[0].play();
}
</script>
</body>
</html>
1) JavaScript code is using jQuery (those $(...) statements), so it must be imported:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
</head>
<body>
...
2) The audio HTML element (the real "player") is missed:
<body>
<audio id="audio" preload="auto" tabindex="0" controls="" >
<source src="http://www.codenamejupiterx.com/song/soundtest.mp3">
</audio>
...
3) The code play only TWO songs. To play THREE:
...
len = tracks.length; //"-1" removed
...
4) The code play again and again the three songs. To stop it:
audio[0].addEventListener('ended',function(e){
current++;
if(current < len){
link = playlist.find('a')[current];
run($(link),audio[0]);
}
});
Using jQuery I do have achieved this by using the following control.
Add the audio Control tag with following parameters:
<audio id="audio1" controls="controls" autoplay="autoplay"> </audio>
And in JavaScript:
jQuery(function($) {
var supportsAudio = !!document.createElement('audio').canPlayType;
if (supportsAudio) {
url = URL.baseUrl + Books + authors + "/" + subject + "/data.json";
$.getJSON(url, function(data){
console.log("ddd"+JSON.stringify(data));
var index = 0,
trackCount = data.URL.length,
npAction = $('#npAction'),
npTitle = $('#npTitle'),
audioid = $('#audio1').bind('play', function() {
}).bind('ended', function() {
if((index + 1) < trackCount) {
index++;
loadTrack(index);
audioid.play();
}
else {
audioid.pause();
index = 0;
loadTrack(index);
}
}).get(0),
loadTrack = function(id) {
index = id;
audioid.src = data.URL[index].ayah;
};
loadTrack(index);
});
}
});

calling the next item in my array

right now I have an array of videos. How do I make it so when i click next and prev the next or previous video in the array loads.
<video id="video" controls autoplay width="1000">
<source src="videos/test.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"' />
<source src="videos/test.ogv" />
</video>
next
<script>
var vidURL=["videos/test.ogv","videos/test2.ogv","videos/test3.ogv","videos/test4.ogv","videos/test5.ogv" ]; // literal array
function vidSwap(vidURL) {
var myVideo = document.getElementsByTagName('video')[0];
myVideo.src = vidURL;
myVideo.load();
myVideo.play();
}
Using yout code, it'll be something like this.
What you need to do is have the video that you loaded on a javascript variable.
Then, when you click prev or next you can call a function that will put the correct video number and call it.
<script>
var vidURL=["videos/test.ogv","videos/test2.ogv","videos/test3.ogv","videos"]
var video = 0;
function vidSwap() {
var myVideo = document.getElementsByTagName('video')[video];
myVideo.src = vidURL[video];
myVideo.load();
myVideo.play();
}
function prevVideo() {
if(video == 0) {
video = vidUrl.length;
}
else {
video -= 1;
}
vidSwap();
}
function nextVideo() {
if(video == length) {
video = 0;
}
else {
video += 1;
}
vidSwap();
}
</script>
<video id="video" controls autoplay width="1000">
<source src="videos/test.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"' />
<source src="videos/test.ogv" />
</video>
prev
next
Introduce variable which will save current video index, then increment it or decrement it each time you press next/prev
</script>
var i = 0;
<script>
javascript:vidSwap(vidURL[i++])
It looks like you're missing another plus sign in your increment operator.
Try changing
next
To this
next
Wrapped up alternative with wrap-around;
next
prev
...
var Vids = (function() {
var _currentId = -1;
var _urls = ["videos/test.ogv","videos/test2.ogv","videos/test3.ogv","videos/test4.ogv","videos/test5.ogv" ]; // literal array
return {
next: function() {
if (++_currentId >= _urls.length)
_currentId = 0;
return this.play(_currentId);
},
prev: function() {
if (--_currentId < 0)
_currentId = _urls.length - 1;
return this.play(_currentId);
},
play: function(id) {
var myVideo = document.getElementsByTagName('video')[0];
myVideo.src = _urls[id];
myVideo.load();
myVideo.play();
return false;
}
}
})();

Categories