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

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

Related

html5 video dropdown quality hls.js

I'm use a tag html5 video + hls.js for video streaming .m3u8
<div class="container-video">
<video id="video"
width="700"
height="400"
preload="auto"
controls>
<source [src]="videoLink" type="application/x-mpegURL">
</video>
</div>
playVideoLive(videoLink) {
const video = document.getElementsByTagName('video')[0];
if (Hls.isSupported()) {
var hls = new Hls();
hls.loadSource(videoLink);
hls.attachMedia(video);
hls.on(Hls.Events.MANIFEST_PARSED, function () {
video.play();
});
}
else if (video.canPlayType('application/vnd.apple.mpegurl')) {
video.src = videoLink;
video.addEventListener('canplay', function () {
video.play();
});
}
}
Hoe i can show the dropdown with the list of quality video?
You can use an extra package to add the a track selector - there may be others but this one seems quite popular: https://www.npmjs.com/package/videojs-hls-quality-selector
You can also add your own controls and do it via the API using: https://github.com/video-dev/hls.js/blob/master/docs/API.md#hlscurrentlevel
There is a demo which uses the API here (at the time of writing) - go to the bottom of the demo page to see the levels and you can click on them there: https://hls-js-dev.netlify.app/demo/

How do I make a random video play on pageload?

I'm trying to make a random video player in html/js.
It is supposed to play a different video on pageload and as soon as one video is over, it should play another one.
HTML
<video width="320" height="240" autoplay>
<source src="abcdefg.com/example1.mp4" type="video/mp4">
<source src="abcdefg.com/example2.mp4" type="video/mp4">
</video>
JS
<script>
var videos = [
[{type:'mp4', 'src':'abcdefg.com/example1.mp4'}],
[{type:'mp4', 'src':'abcdefg.com/example2.mp4'}],
];
$(function() {
var number = Math.floor(Math.random()*videos.length);
$(this).find('source').each(function(index){
videoSrc = videos[number][index].src;
$(this).attr('src', videoSrc);
$('video').load();
$('video').play();
});
});
</script>
However, my current code plays the same video every page reload and as soon as it's over, nothing happens.
How do I need to optimize my code so it automatically plays a different video on every pageload + when the previous video is over?
Try this,I have added an event listener to video end property and called the newvideo() function ,so that every time the video finishes a new random video is loaded from array.I could'nt find more video urls ,you can test and let me know if it works for you.
$(document).ready(function(){
var videos = [
[{type:'mp4', 'src':'http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4'}],
[{type:'mp4', 'src':'http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4'}],
[{type:'mp4', 'src':'http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4'}]
];
// selecting random item from array,you can make your own
var randomitem = videos[Math.floor(Math.random()*videos.length)];
// This function adds a new video source (dynamic) in the video html tag
function videoadd(element, src, type) {
var source = document.createElement('source');
source.src = src;
source.type = type;
element.appendChild(source);
}
// this function fires the video for particular video tag
function newvideo(src)
{
var vid = document.getElementById("myVideo");
videoadd(vid,src ,'video/ogg');
vid.autoplay = true;
vid.load();
//vid.play();
}
// function call
newvideo(randomitem[0].src)
// Added an event listener so that everytime the video finishes ,a new video is loaded from array
document.getElementById('myVideo').addEventListener('ended',handler,false);
function handler(e)
{
newvideo(randomitem[0].src)
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<video width="320" height="240" autoplay id="myVideo">
</video>

HTML5 Video If hash is equal to value set the audio to 1 else set the audio to 0 using Javascript Functions

Hello I am trying to set the HTML5's video audio level depending on the location hash for example if the hash is #home the video's audio should be 1.0 if the hash isn't #home then the audio level should be 0.0
I've had a play around and i can't seem to get it to work here is my code
and thank you for taking a look and for any help!
$(function() {
if (location.hash === "#home") {
videoAudio();
}
} else {
videoAudioMute();
});
function videoAudio() {
var vid = document.getElementById("myvideo");
vid.volume = 1.0;
}
function videoAudioMute() {
var vid = document.getElementById("myvideo");
vid.volume = 0.0;
}
html
<div class="background">
<video id="myvideo" poster="assets/img/slide1-background-img-pattern-01.jpg" controls="" autoplay="" loop="" >
<source src="assets/vid/Background.mp4" type="video/mp4">
<source src="assets/vid/Background.webm" type="video/webm">
<source src="assets/vid/Background.ogv" type="video/ogg">
</video>
</div>
You have a syntax error.
The correct version should be like:
$(function () {
if (location.hash === "#home") {
videoAudio();
} else {
videoAudioMute();
}
});
function videoAudio() {
var vid = document.getElementById("myvideo");
vid.volume = 1.0;
}
function videoAudioMute() {
var vid = document.getElementById("myvideo");
vid.volume = 0.0;
}
To give a proper answer to the question I think we need a little bit more information.
What you can do if you do not want to share more is console log location. This should give you an object with some properties in it. Hash is one of them. Check it and see if you are getting the data that you expect. If hash is not giving what you want you can try using some of the other properties as an identifier, like pathanme.
If the problem is not in the hash but it is in manipulating the audio level you can try jQuery. I have had a lot of headaches manipulating audio and video files with JavaScript but I have found that jQuery work the best.
Hope this helps.

HTML5 Video - How to do a seamless play and/or loop of several videos?

How can I reliably play several videos one after another seamlessly? As there is a small pause or flicker between playing 2 videos.
In my particular example I have 3 videos. I need to play all 3 of them seamlessly one after another, and I also need to loop middle video an arbitrary number of times (say 2 or 3). All of that needs to happen seamlessly and consistently across different browsers.
I've been trying everything under the moon, from starting video playback on video end, to using several video tags and hiding and replacing them, I even tried to implement this in Flash, but alas nothing works, and the same problem happens in current Flash as well.
I've seen this (or similar) question asked many times but I haven't seen a reliable solution yet.
Does anyone know a solution to this?
After trying various things I have finally been able to create what seems to be a working solution. I haven't tested this on older browsers or other OSes, but this works on latest versions of Chrome, IE, Firefox and Opera. (Although some more feedback of whether this works on other systems would be appreciated)
The idea is to have all 3 videos output frames to HTML5 canvas. The original videos are hidden and preloaded in advance to avoid pause between loading.
Here is the code:
var playCounter = 0;
var clipArray = [];
var $video1 = $("#video1");
var $video2 = $("#video2");
var $video3 = $("#video3");
$video1.attr("src", "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerEscapes.mp4");
$video2.attr("src", "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerJoyrides.mp4");
$video3.attr("src", "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerFun.mp4");
var timerID;
var $canvas = $("#myCanvas");
var ctx = $canvas[0].getContext("2d");
function stopTimer() {
window.clearInterval(timerID);
}
$('#startPlayback').click(function() {
stopTimer();
playCounter = $('#playbackNum').val();
clipArray = [];
// addd element to the end of the array
clipArray.push(1);
for (var i = 0; i < playCounter; i++) {
clipArray.push(2);
}
clipArray.push(3);
$video2[0].load();
$video3[0].load();
$video1[0].play();
});
function drawImage(video) {
//last 2 params are video width and height
ctx.drawImage(video, 0, 0, 640, 360);
}
// copy the 1st video frame to canvas as soon as it is loaded
$video1.one("loadeddata", function() {
drawImage($video1[0]);
});
// copy video frame to canvas every 30 milliseconds
$video1.on("play", function() {
timerID = window.setInterval(function() {
drawImage($video1[0]);
}, 30);
});
$video2.on("play", function() {
timerID = window.setInterval(function() {
drawImage($video2[0]);
}, 30);
});
$video3.on("play", function() {
timerID = window.setInterval(function() {
drawImage($video3[0]);
}, 30);
});
function onVideoEnd() {
//stop copying frames to canvas for the current video element
stopTimer();
// remove 1st element of the array
clipArray.shift();
//IE fix
if (!this.paused) this.pause();
if (clipArray.length > 0) {
if (clipArray[0] === 1) {
$video1[0].play();
}
if (clipArray[0] === 2) {
$video2[0].play();
}
if (clipArray[0] === 3) {
$video3[0].play();
}
} else {
// in case of last video, make sure to load 1st video so that it would start from the 1st frame
$video1[0].load();
}
}
$video1.on("ended", onVideoEnd);
$video2.on("ended", onVideoEnd);
$video3.on("ended", onVideoEnd);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div id="border">
<video id="video1" width="640" height="360" hidden>
<source type="video/mp4">
Your browser does not support playing this Video
</video>
<video id="video2" width="640" height="360" hidden>
<source type="video/mp4">
Your browser does not support playing this Video
</video>
<video id="video3" width="640" height="360" hidden>
<source type="video/mp4">
Your browser does not support playing this Video
</video>
<div>
<canvas id="myCanvas" width="640" height="360"> </canvas>
</div>
<div role="controls">
<div>
<label>
Times the middle video will repeat itself:
</label>
</div>
<div>
<input id="playbackNum" value="1" />
</div>
<p>
<button id="startPlayback">Start</button>
</p>
</div>
</div>
Please note, the code is not very pretty and would benefit from some cleanup and optimization, but at least this should show the way to work around the problem and implement a seamless playback of several videos in HTML5.
Also make sure to include jQuery source file in html file location for the code to work.
I have used VideoJS for some time and it allows seamless video playing.
http://videojs.com
You will be required jQuery for this. There are many other jQuery video players.

Prevent reset of currentTime when video loads?

I want to be able to reload the video into the HTML5 video without having to reset the currentTime when it is loaded. The way I am currently doing it is the following:
<button onclick="getCurTime()" type="button">Get current time position</button>
<button onclick="setCurTime()" type="button">Set time position to 5 seconds</button><br>
<div style="width:800px; height:445px;">
<video id="myVideo" width="100%" height="100%" controls="controls">
<source src="http://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_320x180.mp4" type="video/mp4">
</video>
<script>
var vid = document.getElementById("myVideo");
function setCurTime() {
vid.currentTime=100;
}
$(document).ready(function ()
{
$('#myVideo').videocontrols(
{
preview:
{
sprites: ['big_bunny_108p_preview.jpg'],
step: 10,
width: 200
},
theme:
{
progressbar: 'blue',
range: 'pink',
volume: 'pink'
}
});
vid.play();
});
setInterval(function(){
if(vid.currentTime > vid.duration-1)
{
myVideo.src = "http://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_320x180.mp4";
myVideo.load();
myVideo.play();
vid.currentTime = vid.duration-60*5
}
}, 1);
</script>
</div>
How would I go about doing this? Is there even a way to just update the data in the video player without having to reload the video? I want to be able to do this so if someone makes a modification to the video, it will just update the data in the video player so the user doesn't have to reload the whole video again.
per discussion in comment thread above, I'm still not 100% sure why you're reloading the same video so I may be missing some context, but the following code will let you change the video source but preserve the current time. It does assume jQuery for the event handler (though you can easily use the regular javascript event handler on the same event to do the same thing)
<video id="v" width="320" height="240" controls="controls" mute>
<source src="Video.mp4" />
</video>
<button onclick="reload()">Reload</button>
<script>
function reload() {
vid=document.getElementById("v")
// record the current time for the video that is playing
curTime = vid.currentTime
// set the source for the replacement video...
vid.src = "http://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_320x180.mp4";
// ... and load it
vid.load();
// add event handler for "canplay" to set the time, and then start the video
$("#v").on("canplay",function() {
vid.currentTime = curTime
vid.play();
// remove the event to stop it triggering multiple times
$("#v").off("canplay")
})
}
</script>

Categories

Resources