Play video in loop with different timing and function - javascript

I have 2 function which play the same video but with different timing.
I can't play make the function to work properly.
Looks like the function doesn't reset the other function
I tried to change variables names but still change the timing on click.
var video = document.getElementById('videoElm');
function playShortVideo() {
var starttime = 0; // start at 0 seconds
var endtime = 2; // stop at 2 seconds
video.addEventListener("timeupdate", function() {
if (this.currentTime >= endtime) {
this.currentTime = 0; // change time index here
}
}, false);
video.load();
video.play();
}
function playFullVideo() {
var starttime = 0; // start at 0 seconds
var endtime = 24; // stop at 2 seconds
video.addEventListener("timeupdate", function() {
if (this.currentTime >= endtime) {
this.currentTime = 0; // change time index here
}
}, false);
video.load();
video.play();
}
//play short video by default
playShortVideo();
//CLICK events
var btnshort = $('.shortvideo');
var btnfull = $('.fullvideo');
btnshort.click(function() {
playShortVideo();
});
btnfull.click(function() {
playFullVideo();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<video id="videoElm" autoplay muted controls loop>
<source src="http://clips.vorwaerts-gmbh.de/VfE_html5.mp4" type="video/webm">
</video>
</div>
<button class="shortvideo">play 2 secs only</a><br>
<button class="fullvideo">loop full video</button>

That's because the listener is still there, you need to remove it.
Remember, in order to remove it, you can't use anonymous function as callback so I turned it into defined function.
var video = document.getElementById('videoElm');
const playShort = function() {
if (this.currentTime >= 2) {
this.currentTime = 0; // change time index here
}
};
const playFull = function() {
if (this.currentTime >= 24) {
this.currentTime = 0; // change time index here
}
};
function playShortVideo() {
video.removeEventListener("timeupdate", playFull, false)
video.addEventListener("timeupdate", playShort, false);
video.load();
video.play();
}
function playFullVideo() {
video.removeEventListener("timeupdate", playShort, false)
video.addEventListener("timeupdate", playFull, false);
video.load();
video.play();
}
//play short video by default
playShortVideo();
//CLICK events
var btnshort = $('.shortvideo');
var btnfull = $('.fullvideo');
btnshort.click(function() {
playShortVideo();
});
btnfull.click(function() {
playFullVideo();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<video id="videoElm" autoplay muted controls loop>
<source src="http://clips.vorwaerts-gmbh.de/VfE_html5.mp4" type="video/webm">
</video>
</div>
<button class="shortvideo">play 2 secs only</a><br>
<button class="fullvideo">loop full video</button>
And here is the approach for starting the video at 49 sec (60 > 49 + 10)
const shortStartTime = 49;
const shortDuration = 10;
var video = document.getElementById('videoElm');
const playShort = function() {
if (this.currentTime > (shortStartTime + shortDuration)) {
this.currentTime = shortStartTime; // change time index here
}
};
const playFull = function() {
if (this.currentTime >= 24) {
this.currentTime = 0; // change time index here
}
};
function playShortVideo() {
video.removeEventListener("timeupdate", playFull, false)
video.addEventListener("timeupdate", playShort, false);
video.load();
video.currentTime = shortStartTime;
video.play();
}
function playFullVideo() {
video.removeEventListener("timeupdate", playShort, false)
video.addEventListener("timeupdate", playFull, false);
video.load();
video.play();
}
//play short video by default
playShortVideo();
//CLICK events
var btnshort = $('.shortvideo');
var btnfull = $('.fullvideo');
btnshort.click(function() {
playShortVideo();
});
btnfull.click(function() {
playFullVideo();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<video id="videoElm" autoplay muted controls loop>
<source src="http://clips.vorwaerts-gmbh.de/VfE_html5.mp4" type="video/webm">
</video>
</div>
<button class="shortvideo">play 2 secs only</a><br>
<button class="fullvideo">loop full video</button>

That happens because you're attaching a timeUpdate event listener multiple times.
You either need to use one-only or delete it before attaching a new one.
var video = document.getElementById('videoElm');
var listener;
var starttime = 0;
var endtime = 2;
function updateVideo(e) {
if (e.target.currentTime >= endtime) {
e.target.currentTime = 0; // change time index here
}
}
function playShortVideo() {
starttime = 0; // start at 0 seconds
endtime = 2; // stop at 2 seconds
if (!listener) {
listener = video.addEventListener("timeupdate", updateVideo, false);
}
video.load();
video.play();
}
function playFullVideo() {
starttime = 0; // start at 0 seconds
endtime = 24; // stop at 2 seconds
if (!listener) {
listener = video.addEventListener("timeupdate", updateVideo, false);
}
video.load();
video.play();
}
//play short video by default
playShortVideo();
//CLICK events
var btnshort = $('.shortvideo');
var btnfull = $('.fullvideo');
btnshort.click(function() {
playShortVideo();
});
btnfull.click(function() {
playFullVideo();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<video id="videoElm" autoplay muted controls loop>
<source src="http://clips.vorwaerts-gmbh.de/VfE_html5.mp4" type="video/webm">
</video>
</div>
<button class="shortvideo">play 2 secs only</a><br>
<button class="fullvideo">loop full video</button>

Related

Change Video in Everyday

I have a some videos, that need to be play continuously. But there is a condition, first video should be play upto 24 hours.it means, loop the first video for 24 hours. after that next video. Now the videos are playing continuously. But I Don't know how to set the time for playing videos. Please help me to solve this problem. Thank you.
Here is My code.
var videoSources = ["video/kid.mp4", "video/hands.mp4", "video/video5.mp4", "video/action.mp4"];
var currentIndex = 0;
// listener function changes src
function myNewSrc() {
var myVideo = document.getElementsByClassName('episodeVideo')[0];
myVideo.src = videoSources[currentIndex];
myVideo.load();
}
// add a listener function to the ended event
function myAddListener() {
var myVideo = document.getElementsByClassName('episodeVideo')[0];
currentIndex = (currentIndex + 1) % videoSources.length;
myVideo.src = videoSources[currentIndex];
myVideo.addEventListener('ended', myNewSrc, false);
}
<div class="video-wrapper-main">
<video onended="myAddListener()" class="episodeVideo" preload="auto" autoplay controls>
<source src="" type="video/mp4">
</video>
</div>
var videoSources = ["video/kid.mp4", "video/hands.mp4", "video/video5.mp4", "video/action.mp4"];
var startTime = Date.now();
var currentIndex = 0;
// listener function changes src
function myNewSrc() {
var myVideo = document.getElementsByClassName('episodeVideo')[0];
var newTime = Date.now();
var msIn24Hours = 1000 * 60 * 60 * 24;
var isAfter24Hours = newTime - startTime >= msIn24Hours;
if(isAfter24Hours) {
myVideo.src = videoSources[currentIndex];
startTime = newTime;
}
myVideo.load();
}
// add a listener function to the ended event
function myAddListener() {
var myVideo = document.getElementsByClassName('episodeVideo')[0];
currentIndex = (currentIndex + 1) % videoSources.length;
myVideo.src = videoSources[currentIndex];
myVideo.addEventListener('ended', myNewSrc, false);
}
You could then store the start into localStorage and use that value.

HTML5 - Fire event every few seconds while video is playing

I want to track user engagement for a video, by tracking how many users are dropping of at different time interval.
For this I need to fire a tracking event, every 15 seconds while the video is playing.
The playing event is triggered once. I need something which I can use throughout the life of the video.
var _video = $('video')[0],
timeoutID;
$(_video).on('playing', function(event){
timeoutID = window.setTimeout(function() {
console.log("video is playing");
}, 15000);
}).on('ended', function(event){
console.log("video eneded");
window.clearTimeout(timeoutID);
});
You can use the timeupdate event instead, it updates whenever the video's currentTime changes, or in other words it updates as the video is playing and gives you the amount of video the user has actually seen
var _video = $('video')[0];
$(_video).on('timeupdate', function() {
var hasPlayedTime = _video.currentTime;
});
var _video = $('video')[0];
$(_video).on('timeupdate', function(event){
var hasPlayedTime = _video.currentTime;
$('#result').html('<strong>Elapsed : </strong>' + hasPlayedTime);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<video controls="" style="width:240px;height:180px;">
<source src="http://www.html5rocks.com/en/tutorials/video/basics/devstories.webm" type="video/webm;codecs="vp8, vorbis"" />
<source src="http://www.html5rocks.com/en/tutorials/video/basics/devstories.mp4" type="video/mp4;codecs="avc1.42E01E, mp4a.40.2"" />
</video>
<span id="result" style="position:relative; top: -100px; left: 20px"></span>
To act only every fifteen seconds on an event such as that, we need to add some math and logic
var _video = $('video')[0],
debounce = true,
seconds = 5; // set to 15 instead
$(_video).on('timeupdate', function(event){
var hasPlayedTime = _video.currentTime;
var intPlayedTime = parseInt(hasPlayedTime, 10);
var isFifteen = intPlayedTime % seconds === 0 && intPlayedTime !== 0;
if (isFifteen && debounce) {
debounce = false;
$('#result span').html(intPlayedTime);
} else {
setTimeout(function() {
debounce = true;
}, 1000);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" controls="controls"></script>
<video controls="" style="width:240px;height:180px; position: relative; top: -20px; float:left">
<source src="http://www.html5rocks.com/en/tutorials/video/basics/devstories.webm" type="video/webm;codecs="vp8, vorbis"" />
<source src="http://www.html5rocks.com/en/tutorials/video/basics/devstories.mp4" type="video/mp4;codecs="avc1.42E01E, mp4a.40.2"" />
</video>
<span id="result" style="position:relative; top: 70px; left: 20px">
<p><u>Updates every five seconds</u></p>
<strong>Elapsed : </strong>
<span>0</span>
</span>
use window.setInterval instead of window.setTimeout
$(_video).on('playing', function(event){
timeoutID = window.setInterval(function() {
console.log("video is playing");
}, 15000);
}).on('ended', function(event){
console.log("video eneded");
window.clearInterval(timeoutID);
});
I did this
var lastSecond = null;
var secondsToCallFunction = 20;
$(_video).on('timeupdate', function(e) {
var seconds = Math.floor(e.target.currentTime);
if (seconds % secondsToCallFunction == 0 && lastSecond !== seconds) {
lastSecond = seconds
console.log(seconds);
}
});

Create own video player

I try to work with HTML5 tag and create my own palyer.
My html:
<video id="video">
<source src="video/v.mp4" />
<source src="video/v.ogg" />
<source src="video/v.webm" />
</video>
<br />
<button id="part1Button">
1
</button>
<button id="part2Button">
2
</button>
<button id="part3Button">
3
</button>
<button id="playButton">play</button>
<button id="pauseButton">pause</button>
My JavaScript:
<script type="text/javascript">
window.onload = function () {
var video = document.getElementById("video");
var p = v.duration / 3;
document.getElementById("part1Button").onclick = function () {
video.currentTime = 0;
};
document.getElementById("part2Button").onclick = function () {
video.currentTime = p;
};
document.getElementById("part3Button").onclick = function () {
video.currentTime = p * 2;
};
document.getElementById("playButton").onclick = function () {
video.play();
};
document.getElementById("pauseButton").onclick = function () {
video.pause();
};
}
</script>
All three buttons: 1,2,3 do not work in Google Chrome. I will have the next error when I click on them : "Uncaught TypeError: Failed to set the 'currentTime' property on 'HTMLMediaElement': The provided double value is non-finite".
When I replace video.currentTime = p * 2 on video.currentTime = (video.duration / 3) * 2 everything works fine.
Can somebody explan me why is this happening?
Many thanks.
The problem are these lines:
var video = document.getElementById("video");
var p = v.duration / 3;
I guess you wanted to write:
var p = video.duration / 3;
Hope it helps!
UPDATE 1:
And, as Derek 朕會功夫 has pointed out, if the video is not ready is not possible to calculate the duration. You can get more info here.
UPDATE 2:
I have added a snippet with all the buttons working.
var v = document.getElementById("video");
v.onloadedmetadata = function() {
var part = Math.floor(v.duration / 3);
document.getElementById("part1Button").onclick = function() {
v.currentTime = 0;
};
document.getElementById("part2Button").onclick = function() {
v.currentTime = part;
};
document.getElementById("part3Button").onclick = function() {
v.currentTime = part * 2;
};
document.getElementById("playButton").onclick = function() {
v.play();
};
document.getElementById("pauseButton").onclick = function() {
v.pause();
};
}
<video id="video" style="border: 2px solid gray;" height="200" width="200">
<source src="https://upload.wikimedia.org/wikipedia/commons/transcoded/4/4d/Wikipedia_Edit_2014.webm/Wikipedia_Edit_2014.webm.480p.webm" />
</video>
<br>
<button id="part1Button">
1
</button>
<button id="part2Button">
2
</button>
<button id="part3Button">
3
</button>
<button id="playButton">play</button>
<button id="pauseButton">pause</button>

Playlist with <audio> JavaScript

I'm creating a personal small website and I want to play some songs on it. What I've tried to do is the following:
<script type="text/javascript">
var i=1;
var nextSong= "";
var audioPlayer = document.getElementById('audio');
audioPlayer.onended = function(){
i++
nextSong = "Music/"+i+".mp3";
audioPlayer.src = nextSong;
audioPLayer.load();
audioPlayer.play();
if(i == 37) // this is the end of the songs.
{
i = 1;
}
}
</script>
<audio id="audio" src="Music/1.mp3"controls="controls" autoplay="autoplay" align=""> </audio>
However, I can't get this to work. It just plays the first song and doesn't execute the JS. I've tried alerting the state of i for example but it doesn't do anything.
Try this:
<script type="text/javascript">
var i=1;
var nextSong= "";
function setup() {
document.getElementById('audio').addEventListener('ended', function(){
i++;
nextSong = "Music/"+i+".mp3";
audioPlayer = document.getElementById('audio');
audioPlayer.src = nextSong;
audioPLayer.load();
audioPlayer.play();
if(i == 37) // this is the end of the songs.
{
i = 1;
}
}, false);
}
</script>
<body onLoad="setup();">
<audio id="audio" src="Music/1.mp3"controls="controls" autoplay="autoplay" align=""> </audio>
</body>
Amendment needed on this answer. You need to also identify the audio player, otherwise this won't work...
<script type="text/javascript">
function setup() {
var i=1;
var nextSong= "";
audioPlayer = document.getElementById('audio');
document.getElementById('audio').addEventListener('ended', function(){
i=i+1;
nextSong = "m"+i+".mp3";
audioPlayer.src = nextSong;
audioPlayer.load();
audioPlayer.play();
}, false);
}
</script>
<body onLoad="setup();">
<audio id="audio" src="m1.mp3" controls="controls" autoplay="autoplay" align=""> </audio>
</body>
var i=1; var nextSong= ""; function setup() { document.getElementById('audio').addEventListener('ended', function(){ i++; nextSong = "Music/"+i+".mp3"; audioPlayer = document.getElementById('audio'); audioPlayer.src = nextSong; audioPLayer.load(); audioPlayer.play(); if(i == 37) // this is the end of the songs. { i = 1; } }, false); }

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