Random Fullscreen Video Background on Load (jsfiddle included) - javascript

Trying to get my site to display a random fullscreen background video from a folder of videos I will maintain. I'd like to keep adding to the folder (bg1.mp4, bg2.mp4, etc...) and have the code automatically choose a random video to loop when you load the page.
here is my current code: https://jsfiddle.net/nenr3kyn/2/ , which isn't fully functional. I have a specific video chosen as the source file:
<source src="http://thenewcode.com/assets/videos/polina.mp4" type="video/mp4">
because I can't seem to get the html to call the variable set by the javascript "vid", like this:
<source src=vid type="video/mp4">
Also, this code wouldn't allow me to simply add files to the folder, and is limiting me to the videos that are specifically listed in the code. I'd rather have the javascript able to count all the files currently in the folder and choose a random, but couldn't get that to work either.
Any ideas?
Any input is greatly appreciated.
Thanks so much!!

Don't use the loop attribute it wouldn't trigger the ended event.
videoPlayer.addEventListener('ended', function(){
var videoLink = ['link1', 'link2','link3'];
var nextVid = Math.floor( Math.random() * videoLink.length);
this.src = videoLink[nextVideo];
this.play();
});
Hope this will help

Related

Use javascript variable for video source in HTML [duplicate]

I'm trying to build a video player that works everywhere. so far I'd be going with:
<video>
<source src="video.mp4"></source>
<source src="video.ogv"></source>
<object data="flowplayer.swf" type="application/x-shockwave-flash">
<param name="movie" value="flowplayer.swf" />
<param name="flashvars" value='config={"clip":"video.mp4"}' />
</object>
</video>
(as seen on several sites, for example video for everybody)
so far, so good.
But now I also want some kind of playlist/menu along with the video player, from which I can select other videos. Those should be opened within my player right away. So I will have to "dynamically change the source of the video" (as seen on dev.opera.com/articles/everything-you-need-to-know-html5-video-audio/ - section "Let's look at another movie") with Javascript. Let's forget about the Flash player (and thus IE) part for the time being, I will try to deal with that later.
So my JS to change the <source> tags should be something like:
<script>
function loadAnotherVideo() {
var video = document.getElementsByTagName('video')[0];
var sources = video.getElementsByTagName('source');
sources[0].src = 'video2.mp4';
sources[1].src = 'video2.ogv';
video.load();
}
</script>
The problem is, this doesn't work in all browsers. Namely, in Firefox there is a nice page where you can observe the problem I'm having: http://www.w3.org/2010/05/video/mediaevents.html
As soon as I trigger the load() method (in Firefox, mind you), the video player dies.
Now I have found out that when I don't use multiple <source> tags, but instead just one src attribute within the <video> tag, the whole thing does work in Firefox.
So my plan is to just use that src attribute and determine the appropriate file using the canPlayType() function.
Am I doing it wrong somehow or complicating things?
I hated all these answers because they were too short or relied on other frameworks.
Here is "one" vanilla JS way of doing this, working in Chrome, please test in other browsers:
var video = document.getElementById('video');
var source = document.createElement('source');
source.setAttribute('src', 'http://techslides.com/demos/sample-videos/small.mp4');
source.setAttribute('type', 'video/mp4');
video.appendChild(source);
video.play();
console.log({
src: source.getAttribute('src'),
type: source.getAttribute('type'),
});
setTimeout(function() {
video.pause();
source.setAttribute('src', 'http://techslides.com/demos/sample-videos/small.webm');
source.setAttribute('type', 'video/webm');
video.load();
video.play();
console.log({
src: source.getAttribute('src'),
type: source.getAttribute('type'),
});
}, 3000);
<video id="video" width="320" height="240"></video>
External Link
Modernizr worked like a charm for me.
What I did is that I didn't use <source>. Somehow this screwed things up, since the video only worked the first time load() was called. Instead I used the source attribute inside the video tag -> <video src="blabla.webm" /> and used Modernizr to determine what format the browser supported.
<script>
var v = new Array();
v[0] = [
"videos/video1.webmvp8.webm",
"videos/video1.theora.ogv",
"videos/video1.mp4video.mp4"
];
v[1] = [
"videos/video2.webmvp8.webm",
"videos/video2.theora.ogv",
"videos/video2.mp4video.mp4"
];
v[2] = [
"videos/video3.webmvp8.webm",
"videos/video3.theora.ogv",
"videos/video3.mp4video.mp4"
];
function changeVid(n){
var video = document.getElementById('video');
if(Modernizr.video && Modernizr.video.webm) {
video.setAttribute("src", v[n][0]);
} else if(Modernizr.video && Modernizr.video.ogg) {
video.setAttribute("src", v[n][1]);
} else if(Modernizr.video && Modernizr.video.h264) {
video.setAttribute("src", v[n][2]);
}
video.load();
}
</script>
Hopefully this will help you :)
If you don't want to use Modernizr , you can always use CanPlayType().
Your original plan sounds fine to me. You'll probably find more browser quirks dealing with dynamically managing the <source> elements, as indicated here by the W3 spec note:
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 unncessarily[sic] complicated approach.
http://dev.w3.org/html5/spec/Overview.html#the-source-element
I solved this with this simple method
function changeSource(url) {
var video = document.getElementById('video');
video.src = url;
video.play();
}
Instead of getting the same video player to load new files, why not erase the entire <video> element and recreate it. Most browsers will automatically load it if the src's are correct.
Example (using Prototype):
var vid = new Element('video', { 'autoplay': 'autoplay', 'controls': 'controls' });
var src = new Element('source', { 'src': 'video.ogg', 'type': 'video/ogg' });
vid.update(src);
src.insert({ before: new Element('source', { 'src': 'video.mp4', 'type': 'video/mp4' }) });
$('container_div').update(vid);
According to the spec
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 unncessarily complicated approach.
So what you are trying to do is apparently not supposed to work.
Just put a div and update the content...
<script>
function setvideo(src) {
document.getElementById('div_video').innerHTML = '<video autoplay controls id="video_ctrl" style="height: 100px; width: 100px;"><source src="'+src+'" type="video/mp4"></video>';
document.getElementById('video_ctrl').play();
}
</script>
<button onClick="setvideo('video1.mp4');">Video1</button>
<div id="div_video"> </div>
Yaur: Although what you have copied and pasted is good advice, this does not mean that it is impossible to change the source element of an HTML5 video element elegantly, even in IE9 (or IE8 for that matter).(This solution does NOT involve replacing the entire video element, as it is bad coding practice).
A complete solution to changing/switching videos in HTML5 video tags via javascript can be found here and is tested in all HTML5 browser (Firefox, Chrome, Safari, IE9, etc).
If this helps, or if you're having trouble, please let me know.
This is my solution:
<video id="playVideo" width="680" height="400" controls="controls">
<source id="sourceVideo" src="{{video.videoHigh}}" type="video/mp4">
</video>
<br />
<button class="btn btn-warning" id="{{video.videoHigh}}" onclick="changeSource(this)">HD</button>
<button class="btn btn-warning" id="{{video.videoLow}}" onclick="changeSource(this)">Regular</button>
<script type="text/javascript">
var getVideo = document.getElementById("playVideo");
var getSource = document.getElementById("sourceVideo");
function changeSource(vid) {
var geturl = vid.id;
getSource .setAttribute("src", geturl);
getVideo .load()
getVideo .play();
getVideo .volume = 0.5;
}
</script>
I have a similar web app and am not facing that sort of problem at all. What i do is something like this:
var sources = new Array();
sources[0] = /path/to/file.mp4
sources[1] = /path/to/another/file.ogg
etc..
then when i want to change the sources i have a function that does something like this:
this.loadTrack = function(track){
var mediaSource = document.getElementsByTagName('source')[0];
mediaSource.src = sources[track];
var player = document.getElementsByTagName('video')[0];
player.load();
}
I do this so that the user can make their way through a playlist, but you could check for userAgent and then load the appropriate file that way. I tried using multiple source tags like everyone on the internet suggested, but i found it much cleaner, and much more reliable to manipulate the src attribute of a single source tag. The code above was written from memory, so i may have glossed over some of hte details, but the general idea is to dynamically change the src attribute of the source tag using javascript, when appropriate.
Another way you can do in Jquery.
HTML
<video id="videoclip" controls="controls" poster="" title="Video title">
<source id="mp4video" src="video/bigbunny.mp4" type="video/mp4" />
</video>
<div class="list-item">
<ul>
<li class="item" data-video = "video/bigbunny.mp4">Big Bunny.</li>
</ul>
</div>
Jquery
$(".list-item").find(".item").on("click", function() {
let videoData = $(this).data("video");
let videoSource = $("#videoclip").find("#mp4video");
videoSource.attr("src", videoData);
let autoplayVideo = $("#videoclip").get(0);
autoplayVideo.load();
autoplayVideo.play();
});
I come with this to change video source dynamically. "canplay" event sometime doesn't fire in Firefox so i have added "loadedmetadata". Also i pause previous video if there is one...
var loadVideo = function(movieUrl) {
console.log('loadVideo()');
$videoLoading.show();
var isReady = function (event) {
console.log('video.isReady(event)', event.type);
video.removeEventListener('canplay', isReady);
video.removeEventListener('loadedmetadata', isReady);
$videoLoading.hide();
video.currentTime = 0;
video.play();
},
whenPaused = function() {
console.log('video.whenPaused()');
video.removeEventListener('pause', whenPaused);
video.addEventListener('canplay', isReady, false);
video.addEventListener('loadedmetadata', isReady, false); // Sometimes Firefox don't trigger "canplay" event...
video.src = movieUrl; // Change actual source
};
if (video.src && !video.paused) {
video.addEventListener('pause', whenPaused, false);
video.pause();
}
else whenPaused();
};
Using the <source /> tags proved difficult for me in Chrome 14.0.835.202 specifically, although it worked fine for me in FireFox. (This could be my lack of knowledge, but I thought an alternate solution might be useful anyway.) So, I ended up just using a <video /> tag and setting the src attribute right on the video tag itself. The canPlayVideo('<mime type>') function was used to determine whether or not the specific browser could play the input video. The following works in FireFox and Chrome.
Incidently, both FireFox and Chrome are playing the "ogg" format, although Chrome recommends "webm". I put the check for browser support of "ogg" first only because other posts have mentioned that FireFox prefers the ogg source first (i.e. <source src="..." type="video/ogg"/> ). But, I haven't tested (and highly doubt) whether or not it the order in the code makes any difference at all when setting the "src" on the video tag.
HTML
<body onload="setupVideo();">
<video id="media" controls="true" preload="auto" src="">
</video>
</body>
JavaScript
function setupVideo() {
// You will probably get your video name differently
var videoName = "http://video-js.zencoder.com/oceans-clip.mp4";
// Get all of the uri's we support
var indexOfExtension = videoName.lastIndexOf(".");
//window.alert("found index of extension " + indexOfExtension);
var extension = videoName.substr(indexOfExtension, videoName.length - indexOfExtension);
//window.alert("extension is " + extension);
var ogguri = encodeURI(videoName.replace(extension, ".ogv"));
var webmuri = encodeURI(videoName.replace(extension, ".webm"));
var mp4uri = encodeURI(videoName.replace(extension, ".mp4"));
//window.alert(" URI is " + webmuri);
// Get the video element
var v = document.getElementById("media");
window.alert(" media is " + v);
// Test for support
if (v.canPlayType("video/ogg")) {
v.setAttribute("src", ogguri);
//window.alert("can play ogg");
}
else if (v.canPlayType("video/webm")) {
v.setAttribute("src", webmuri);
//window.alert("can play webm");
}
else if (v.canPlayType("video/mp4")) {
v.setAttribute("src", mp4uri);
//window.alert("can play mp4");
}
else {
window.alert("Can't play anything");
}
v.load();
v.play();
}
I have been researching this for quite a while and I am trying to do the same thing, so hopefully this will help someone else. I have been using crossbrowsertesting.com and literally testing this in almost every browser known to man. The solution I've got currently works in Opera, Chrome, Firefox 3.5+, IE8+, iPhone 3GS, iPhone 4, iPhone 4s, iPhone 5, iPhone 5s, iPad 1+, Android 2.3+, Windows Phone 8.
Dynamically Changing Sources
Dynamically changing the video is very difficult, and if you want a Flash fallback you will have to remove the video from the DOM/page and re-add it so that Flash will update because Flash will not recognize dynamic updates to Flash vars. If you're going to use JavaScript to change it dynamically, I would completely remove all <source> elements and just use canPlayType to set the src in JavaScript and break or return after the first supported video type and don't forget to dynamically update the flash var mp4. Also, some browsers won't register that you changed the source unless you call video.load(). I believe the issue with .load() you were experiencing can be fixed by first calling video.pause(). Removing and adding video elements can slow down the browser because it continues buffering the removed video, but there's a workaround.
Cross-browser Support
As far as the actual cross-browser portion, I arrived at Video For Everybody as well. I already tried the MediaelementJS Wordpress plugin, which turned out to cause a lot more issues than it resolved. I suspect the issues were due to the Wordpress plug-in and not the actually library. I'm trying to find something that works without JavaScript, if possible. So far, what I've come up with is this plain HTML:
<video width="300" height="150" controls="controls" poster="http://sandbox.thewikies.com/vfe-generator/images/big-buck-bunny_poster.jpg" class="responsive">
<source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.ogv" type="video/ogg" />
<source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4" type="video/mp4" />
<source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.webm" type="video/webm" />
<source src="http://alex-watson.net/wp-content/uploads/2014/07/big_buck_bunny.iphone.mp4" type="video/mp4" />
<source src="http://alex-watson.net/wp-content/uploads/2014/07/big_buck_bunny.iphone3g.mp4" type="video/mp4" />
<object type="application/x-shockwave-flash" data="http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf" width="561" height="297">
<param name="movie" value="http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf" />
<param name="allowFullScreen" value="true" />
<param name="wmode" value="transparent" />
<param name="flashVars" value="config={'playlist':['http://sandbox.thewikies.com/vfe-generator/images/big-buck-bunny_poster.jpg',{'url':'http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4','autoPlay':false}]}" />
<img alt="No Video" src="http://sandbox.thewikies.com/vfe-generator/images/big-buck-bunny_poster.jpg" width="561" height="297" title="No video playback capabilities, please download the video below" />
</object>
<strong>Download video:</strong> MP4 format | Ogg format | WebM format
</video>
Important notes:
Ended up putting the ogg as the first <source> because Mac OS Firefox quits trying to play the video if it encounters an MP4 as the first <source>.
The correct MIME types are important .ogv files should be video/ogg, not video/ogv
If you have HD video, the best transcoder I've found for HD quality OGG files is Firefogg
The .iphone.mp4 file is for iPhone 4+ which will only play videos that are MPEG-4 with H.264 Baseline 3 Video and AAC audio. The best transcoder I found for that format is Handbrake, using the iPhone & iPod Touch preset will work on iPhone 4+, but to get iPhone 3GS to work you need to use the iPod preset which has much lower resolution which I added as video.iphone3g.mp4.
In the future we will be able to use a media attribute on the <source> elements to target mobile devices with media queries, but right now the older Apple and Android devices don't support it well enough.
Edit:
I'm still using Video For Everybody but now I've transitioned to using FlowPlayer, to control the Flash fallback, which has an awesome JavaScript API that can be used to control it.
Try moving the OGG source to the top. I've noticed Firefox sometimes gets confused and stops the player when the one it wants to play, OGG, isn't first.
Worth a try.
You shouldn't try to change the src attribute of a source element, according to this spec note .
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
So lets say you have:
<audio>
<source src='./first-src'/>
</audio>
To modify the src:
<audio src='./second-src'/>
<source src='./first-src'/>
</audio>
if you already have a loaded video and you try to upload a new one over that one make sure to use the videoRef.load() on the second one, otherwise it wont load.
*videoRef should be the ref of the displayed <video></video> tag
Using JavaScript and jQuery:
<script src="js/jquery.js"></script>
...
<video id="vid" width="1280" height="720" src="v/myvideo01.mp4" controls autoplay></video>
...
function chVid(vid) {
$("#vid").attr("src",vid);
}
...
<div onclick="chVid('v/myvideo02.mp4')">See my video #2!</div>
I ended up making the accepted ansower into a function and improving the resume to keep the time. TLDR
/**
* https://stackoverflow.com/a/18454389/4530300
* This inspired a little function to replace a video source and play the video.
* #param video
* #param source
* #param src
* #param type
*/
function swapSource(video, source, src, type) {
let dur = video.duration;
let t = video.currentTime;
// var video = document.getElementById('video');
// var source = document.createElement('source');
video.pause();
source.setAttribute('src', src);
source.setAttribute('type', type);
video.load();
video.currentTime = t;
// video.appendChild(source);
video.play();
console.log("Updated Sorce: ", {
src: source.getAttribute('src'),
type: source.getAttribute('type'),
});
}

JS currentTime of video HTMLelement doesn't work

I have the problem in redmine. Video attachments absolutly cannot be seeking. I deleted all js scripts working on videos and tried to change 'currentTime'. It doesn't work. I checked it with different video files, changed webm/mp4, tried to use 'video-js'. Video still cannot be seeking.
Simplisticaly this code do nothing
media = document.querySelector('video')
console.log(media.duration) // 119.03
media.currentTime = 10 // do nothing
The event 'seeking' works only at the beggining.
Normally, code above should work.
Have your tried on different browsers.
const media = document.querySelector('video');
media.currentTime = 5;
<video src="https://glpjt.s3.amazonaws.com/so/av/vid5.mp4" width='240' controls></video>
I decide my trouble for rails. Its need to add for video file requests:
headers['Accept-Ranges'] = 'bytes'
Good luck, guys!

Changing video resolution on HTML 5.0 video with JavaScript

UPDATE: I was using the Fotorama plugin and it seems that the bottom menu was causing the problem. Disabling that menu by putting div-tags around the video-tags made the function for setting resolution work. Thanks for the help and encouragement. For the bottom menu I create a simple one using link buttons that link to a similar page with the next video.
I have written JavaScript code that changes the resolution of a video based on input of a option/select-element. It works. The problem is that it stops working when I put exactly the same code inside a function (so that the code can be executed multiple times - each time option/select-element is changed.)
Here is an image of the videoplayer and the option/select-element I have added
Here is the code for the option/select-element:
<li class="porfolionav">
<select id="selectQuality" onchange="changeVidQualityFunction()">
<option value="1080" selected="selected" disabled="disabled">Videokvalitet</option>
<option value="1080" id="1080">HD 1080</option>
<option value="480" id="480">SD 480</option>
<option value="320" id="320">SD 320</option>
</select>
</li>
Here is the code for the videos:
<div class="fotorama" data-width="1209px" data-height="680px" data-allowfullscreen="false" data-arrows="true" data-click="true" data-swipe="true" data-autoplay="false" data-transition="slide" data-clicktransition="slide" data-shuffle="false">
<video id="video1V" height="680px" controls data-caption="320 OGG" poster="videos/img/thumb1.jpg">
<source src="videos/test_q_320" id="video1">Your browser does not support HTML5 video.
</video>
<video id="video2V" height="680px" controls data-caption="480 OGG" poster="videos/img/thumb2.jpg">
<source id="video2" src="videos/test_q_480.ogg" id="video2">Your browser does not support HTML5 video.
</video>
<video id="video3V" height="680px" controls data-caption="1080 OGG" poster="videos/img/thumb3.jpg">
<source id="video3" src="videos/test_q_1080.ogg" id="video3">Your browser does not support HTML5 video.
</video>
</div>
And here is the code for the changing resolution (works when not in a function):
<script>
function changeVidQualityFunction(){
$chosenVidQuality = document.getElementById("selectQuality").value;
$trulycompletevideolink = document.getElementById("video1").src;
$step1 = document.getElementById("video1").src.split("_q_");
//COMMENT: step1[0] is the url from start and including the first part of the filename (not the "_q_"-part and the format)
$upToVidName = $step1[0];
//COMMENT: step1[1] is the resolution and format, e.g. 320.ogg
$step2 = $step1[1].split(".");
//COMMENT: step2[0] is the resoltion e.g. 720 ,step2[1] is the format (without the dot in front of the format type) e.g. ogg
$vidresolution = $step2[0];
$vidformat = $step2[1];
$vidresolution = $chosenVidQuality;
$result = $upToVidName+"_q_"+$vidresolution+"."+$vidformat;
$('#video1').attr('src', $result);
$('#video1V').attr('data-caption', $vidresolution+" OGG");
$('#video1V').load();
window.alert("video1 attr src:"+document.getElementById("video1").src); //shows updated URL
}
</script>
Thanks
On your head tag place this <script src="jquery-1.12.2.js" charset="utf-8"></script> to include jquery library since your are using functions from jquery.
and from this line
<select id="selectQuality" onchange="changeVidQualityFunction()">
change it to
<select id="selectQuality" name="video_selected">
and edit your script that follows the rule of jquery, make proper declarations as follows.
function changeVidQualityFunction() {
var ev = $('#selectQuality').val();
console.log(ev);
var chosenVidQuality = $('#selectQuality').val();
var trulycompletevideolink = document.getElementById("video1").src;
var step1 = document.getElementById("video1").src.split("_q_");
//COMMENT: step1[0] is the url from start and including the first part of the filename (not the "_q_"-part and the format)
var upToVidName = step1[0];
//COMMENT: step1[1] is the resolution and format, e.g. 320.ogg
var step2 = step1[1].split(".");
//COMMENT: step2[0] is the resoltion e.g. 720 ,step2[1] is the format (without the dot in front of the format type) e.g. ogg
var vidresolution = step2[0];
var vidformat = step2[1];
vidresolution = chosenVidQuality;
var result = upToVidName + "_q_" + vidresolution + "." + vidformat;
$('#video1').attr('src', result);
$('#video1V').attr('data-caption', vidresolution+" OGG");
$('#video1V').load();
window.alert("video1 attr src:"+document.getElementById("video1").src); //shows updated URL
}
notice that I remove $ of the variable although this is valid, an declare it with var so javascript will know that they are variables.
$(document).ready(function(){
$('#selectQuality').change(function(){
changeVidQualityFunction();
});
});
What the code do is, it will track for a change on your drop down, if change, the function will execute.
Hope this will help
I was using the Fotorama plugin and it seems that the bottom menu was causing the problem. Disabling that menu by putting div-tags around the video-tags made the function for setting resolution work. Thanks for the help and encouragement. For the bottom menu I create a simple one using link buttons that link to a similar page with the next video.

Playing music that is linked and not loaded?

This is probably an odd question, but for fun i recreated the Spotify layout to their app in codepen, now I want to add some functionality, is there a way I can get music to play using JS or jQuery?
My first thought was to embed the video and hide it behind the play button, but that doesn't quite work for me.
Is there a way I can set a var where I set it = to a url, then use an onclick or toggle command to play the url?
The only way I could think about going this would be:
var expirePrettyLow = 'url:www.fake.com'
$('#play').toggle(
function(){
//play youtube link?
);
I hope this makes sense, is there an api I can call to just get the mp3s? I don't want to upload them since it's just linking, not trying to make a product out of this, just to add to portfolio.
For reference here is my codepen link.
Thanks for whatever advice/direction you can give me!
EDIT: To clarify, by 'linked' and not 'loaded'
I would like to accomplish this by linking to a url (ie: href="") as opposed to saving it in my directory and loading it through a filepath (ie: music/tracks/expire-prettylow.mp3)
User a blank audio tag and set the play button's onClick to "var newSrc = newSource.com/song.mp3; playTrack()", and have the playTrack() function load and play the song. Here's an example of a code that changes the source of the audio element then plays the new source.
<script>
function playTrack(){
var music = document.getElementById("myAudio");
music.src = newSrc;
music.load();
music.play();
}
</script>
<audio id="myAudio" src="">
Audio tag not supported
</audio>
Click a song to play it:
<ul>
<li onClick="newSrc = 'http://fidelak.free.fr/reprises/The%20Doors%20-%20People%20are%20Strange.mp3'; playTrack()">People are Strange</li>
<li onClick="newSrc = 'http://mp3light.net/assets/songs/14000-14999/14781-december-1963-oh-what-a-night-four-seasons--1411568407.mp3'; playTrack()">Oh What a Night</li>
</ul>
Set the src with JavScript, music.load(), then music.play()

How to force a html5 video to load fully?

I have a few html5 videos on a page. When I first enter the page, they load correctly - I can see the correct frame size, play the video etc. etc. After going to another page and coming back to the video page the frames are not high enough and the video doesn't play, doesn't go fullscreen etc.
In my opinion it's something with video loading. I tried using onloadeddata without success (I might have used it wrong though, newbie here).
Is there any way the video can be forced to load? Like a loop checking if the videos are loaded, if not - loading them?
UPDATE: Here's the code.
var content = '';
var index;
$.post('api/getVideo.php', {id: id}, function(data) {
//console.log(data);
for (index = 0; index < data.length; index++) {
content = content + '<div class="col-md-6 video-col"> <button id="play" class="full-play-button"><i class="fa fa-play"></i></button>' +
'<video id="video1" class="video-small"> <source src="'+data[index]["Path"] + '"type="video/'+data[index]["Typ"]+'" class="video-file"> </video><h3 class="video-title">'+
data[index]["Tytul"]+'</h3></div>';
}
}, "json");
You might have a typo in your source tag. Try changing '"type="video/' to '"type=video/"'. Modern browsers don't require the type attribute, anymore, so try removing '"type="video/'+data[index]["Typ"]+' completely. I don't have enough info to test your code, but it looks like a syntax error.
From MediaAPI docs,
The Media API also contains a load() method which: "Causes the element to reset and start selecting and loading a new media resource from scratch." (
Load element causes browser to run media element load algorithm)
You can trigger load while returning back from the new page.
In short this is not fully possible. For short videos you can set the preload attribute to "auto" or the empty string "". This means, that you want the browser to preload the source entirly.
Unfortunatley, in case of long videos, the video isn't fully downloaded by most browsers. In case of mobile browser explicitly iOS. The preload attribute doesn't work. So the way to this look like this:
<video preload="" controls="">
<source src="my-video.mp4" type="video/mp4" />
<source src="my-video.webm" type="video/webm" />
</video>

Categories