get browser type in javascript - javascript

I need to load in different movie formats based on browser type. Specifically if the user is using firefox then I need to load in a .ocv video.
I have tried using:
alert(navigator.appName);
but this always returns 'Netscape' in both chrome and firefox??
Is there a better alternative?
Cheers

STOP!!! all proposed solutions are the reason the web is broken&breaking!
Don't assume a browser, based on the name you regexp out of the userAgent, can do something or not just because it sais its an IE, Firefox or Chrome. UserAgents can be and are faked! Do a feature detection either by hand or use something fullfeatured like Modernizr
What you want to do is provided via javascript. To check if the browser can do html5 video playback;
var canHtml5Video=function(){
return !!document.createElement("video").canPlayType;
}
To check if the Browser can play a certain type (mp4, ogg), use the canPlayType method of the audio/video element.
var elem=document.getElementsByTagName("video")[0];
if (elem.canPlayType("video/mp4")===""){
//handle firefox and all browser that cant pay the mp4 royality fee
}
else{
//handle mp4
}
Alternativ, you can just add multiple source elements to the video element. The Browser will chose what fits best.
<video>
<source src="http://....mp4" type="video/mp4" />
<source src="http://....ocv" type="video/ogg" />
</video>

Try
alert(navigator.userAgent);
For more information: http://www.w3schools.com/js/js_browser.asp

You want to use some like
this

Use navigator.userAgent to get the browser details
if (navigator.userAgent.toLowerCase().indexOf("firefox") > -1) {
// Inside firefox
}
if (navigator.userAgent.toLowerCase().indexOf("chrome") > -1) {
// Inside chrome
}
if (navigator.userAgent.toLowerCase().indexOf("msie") > -1) {
// Inside IE
}

for ie:
var ie = $.browser.msie;
for firefox:
var mozilla = $.browser.mozilla;
for chrome:
var chrome = $.browser.webkit && window.chrome;
for safari:
var safari = $.browser.webkit && !window.chrome;

Related

trying to add a multi source video player with more then one video?

Im trying to make a video player work in all browsers. There is
more then one video and every time you click on demo reel it plays the
video and if you click the video 1 the other video plays. How can i
make them both work in all browsers? Here is my html and javascript
html
<video id="myVideo" controls autoplay></video>
<div>
Demo Reel</div>
video 1</div>
</div>
javascript
function changeVid1() {
var changeStuff = document.getElementById("myVideo");
changeStuff.src = "video/demoreel.mp4"
}
function changeVid2() {
var changeStuff = document.getElementById("myVideo");
changeStuff.src = "video/video1.mp4";
}
After you switch the source of the video, you need to run .load() on it to force it to load the new file. Also, you need to provide multiple formats, because there is no video codec supported by all browsers.
First, set up your sources like this:
var sources = [
{
'mp4': 'http://video-js.zencoder.com/oceans-clip.mp4',
'webm':'http://video-js.zencoder.com/oceans-clip.webm',
'ogg':'http://video-js.zencoder.com/oceans-clip.ogv'
}
// as many as you need...
];
Then, your switch function should look like this:
function switchVideo(index) {
var s = sources[index], source, i;
video.innerHTML = '';
for (i in s) {
source = document.createElement('source');
source.src = s[i];
source.setAttribute('type', 'video/' + i);
video.appendChild(source);
}
video.load();
video.play(); //optional
}
See a working demo here.
This gives the browser a list of different formats to try. It will go through each URL until it finds one it likes. Setting the "type" attribute on each source element tells the browser in advance what type of video it is so it can skip the ones it doesn't support. Otherwise, it has to hit the server to retrieve the header and figure out what kind of file it is.
This should work in Firefox going back to 3.5 as long as you provide an ogg/theora file. And it will work in iPads, because you only have one video element on the page at a time. However, auto-play won't work until after the user clicks play manually at least once.
For extra credit, you can append a flash fallback to the video element, after the source tags, for older browsers that don't support html5 video. (i.e., IE < 9 - though you'll need to use jQuery or another shim to replace addEventListener.)

Check to see if a video loads in iPad with JavaScript

I am having a bit of an issue with checking to see if a video is being loaded in iPad. I need to check and see if loads because I am looping through to load all videos with an increment like video_1.mp4, video_2.mp4, video_3.mp4. However, it seems like it ignores the "readyState" and goes straight to the else statement.
Here is the code:
function loadMedia() {
var media = document.getElementsByTagName("video")[0];
if (media.readyState === 4) {
alert("Video has been loaded!");
} else {
alert("Video hasn't been loaded!");
}
}
Is readyState supported by iPad?
Edit: Added more code.
The loadMedia function is binded to window.onload via an anonymous function.
window.onload = (function () {
loadMedia();
});
Here is the HTML:
<video class="video" controls="controls" poster="images/posters/tb_1.jpg" preload="metadata">
<source src="media/tb_1.mp4" type="video/mp4; codecs='avc1.42E01E, mp4a.40.2'" />
We apologize, but your browser does not support this video. Please consider an upgrade.
</video>
Apple documentation seems to at least suggest that readyState for media elements has been around since iOS 3.0:
http://developer.apple.com/library/safari/#documentation/AudioVideo/Reference/HTMLMediaElementClassReference/HTMLMediaElement/HTMLMediaElement.html
That's sort of indirect documentation, perhaps, but it's something.
Since firing up a JS debugger on devices can be annoying, you might want to change this:
alert("Video hasn't been loaded!")
To this:
alert("Video hasn't been loaded! " + media.readyState);
If you turn on the console in the browser (and, if you like, switch to console.log() rather than alert()), this should tell you if your problem is that readyState is undefined (and therefore likely not supported) or if the problem is that maybe media is undefined (seems unlikely).
Of course, you may have also found a bug. You might want to search Apple's bug tracker, if they allow such things.

Changing <source> with HTML5 Audio works in Chrome but not Safari

I'm trying to make an HTML5 audio playlist that will work in each major browser: Chrome,Safari, Firefox, IE9+. However, I can't figure out how to change the sources in a cross browser compatible way.
UPDATED For example, changing the <source> tag's srcs works in Chrome but not Safari. While #eivers88's solution below using canPlayType works it seems easier to me just to change the <source> tag's srcs. Can anyone explain to me why my code directly below works in Chrome but not Safari?
JS:
var audioPlayer=document.getElementById('audioPlayer');
var mp4Source=$('source#mp4');
var oggSource=$('source#ogg');
$('button').click(function(){
audioPlayer.pause();
mp4Source.attr('src', 'newFile.mp4');
oggSource.attr('src', 'newFile.ogg');
audioPlayer.load();
audioPlayer.play();
});
HTML:
<button type="button">Next song</button>
<audio id="audioPlayer">
<source id="mp4" src="firstFile.mp4" type="audio/mp4"/>
<source id="ogg" src="firstFile.ogg" type="audio/ogg" />
</audio>
Inspecting the HTML after the button click, the <source src=""/> does change in Safari, its just that the HTTP request is not made, so they the files don't get load()ed and play()ed. Does anyone have any thoughts on this?
Here is a working exapmle. It's a little bit different from what you have but hopefully this can be helpful.
HTML:
<button type="button">Next song</button>
Javascript/jquery:
var songs = [
'1976', 'Ballad of Gloria Featherbottom', 'Black Powder'
]
var track = 0;
var audioType = '.mp3'
var audioPlayer = document.createElement('audio');
$(window).load(function() {
if(!!audioPlayer.canPlayType('audio/ogg') === true){
audioType = '.ogg' //For firefox and others who do not support .mp3
}
audioPlayer.setAttribute('src', 'music/' + songs[track] + audioType);
audioPlayer.setAttribute('controls', 'controls');
audioPlayer.setAttribute('id', 'audioPlayer');
$('body').append(audioPlayer);
audioPlayer.load();
audioPlayer.play();
});
$('button').on('click', function(){
audioPlayer.pause();
if(track < songs.length - 1){
track++;
audioPlayer.setAttribute('src', 'music/' + songs[track] + audioType);
audioPlayer.load();
audioPlayer.play();
}
else {
track = 0;
audioPlayer.setAttribute('src', 'music/' + songs[track] + audioType);
audioPlayer.load();
audioPlayer.play();
}
})
For some reason, Safari can't use the <source> tags for swapping between songs but Chrome can. Just changing what gets loaded into the src attribute on the <audio> tag works on both Chrome and Safari but then there is the ogg vs. mp3 issue.
I guess one way to get around this ogg vs. mp3 issue is to use Modernizr does feature detection to load the ogg mime-type in Firefox and the mp3 in Chrome/Safari. Here's a reference on that:
Detecting html5 audio support with Modernizr.
Just a quick addition to the topic (in 2023):
I had a similar problem. The code was working in Safari, but not Chrome.
I had Javascript code that swapped the src of the <source> element. That worked fine in Safari, but Chrome refused to recognize the file and showed a disabled player state. What I was missing, and what I learned here, is that you need to call load() as well.
So adding this fixed it for me.
audioPlayer.load();
Safari seems to auto-detect the source change, Chrome did not.

MediaElement.js setSrc not working for flash fallbacks on FF, IE7-8

I've seen a few discussions about this, but no real answers. I've had a lot of success getting mediaelement.js working for me except that it simply will not let me setSrc() on flash fallbacks. This is a huge bummer after so much work.
For a little background I'm using mediaelement-and-player.js v2.1.9 and using their player's API to change the media src via player.setSrc. I'm playing audio MP3s.
I'm getting this error in FF Mac:
this.media.setSrc is not a function
And this error in IE8 Win:
SCRIPT445: Object doesn't support this action
I find it hard to believe that this wasn't fully tested given that it seems a base part of their API. I've seen some other issues about similar problems but again, no real answers.
You would need to add "flashmediaelement.swf" to your code.
Had the same problem. Solved it by adding non-empty src and type="audio/mp3" attributes:
<audio id="player" controls src="#" type="audio/mp3" preload="none"></audio>
Presence of preload="none" is recommended here, because without it the element will send an additional request to a current page's URL in an attempt to download the audio.
Update: found an alternative way, zero-length WAV file can be embedded in src, thus you may use preload attribute normally and stop worrying about that an unneeded request will be sent if a user will click the play button before you set normal src.
<audio id="player" controls type="audio/mp3" src="data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEARKwAAIhYAQACABAAZGF0YQAAAAA=">
Don't worry about type and src incompatibility, because, according to audio element specification, type isn't legal attribute of audio tag at all (type is only a source tag's attribute), here it's placed only to fix MediaElement.js behavior.
I answered a similar question on github. Here's my solution:
This occurs when the setSrc method is called too soon after initializing the mediaElement player. Due to the flash fallback the swf (and therefore its api methods) will not be available until the success event is fired. After that setSrc works fine in IE8..
I didn't want to set the initial source from within the success handler. Therefore I used a boolean var to check whether the success event had occurred. In my source setting method I check for its value and use recursiveness (with a setTimeout to prevent overkill) whenever the boolean var equals false.. Did the trick for me.
//create the tag
var video = $("<video>",{id:"videoElement",width:640,height:360}).appendTo('body');//jquery
var mediaElementInitialized = true
//create the mediaelement
var mediaElement = new MediaElementPlayer("#videoElement",{
/**
* YOU MUST SET THE TYPE WHEN NO SRC IS PROVIDED AT INITIALISATION
* (This one is not very well documented.. If one leaves the type out, the success event will never fire!!)
**/
type: ["video/mp4"],
features: ['playpause','progress','current','duration','tracks','volume'],
//more options here..
success: function(mediaElement, domObject){
mediaElementInitialized = true;
},
error: function(e){alert(e);}
}
);
var setSource = function(src){
if(mediaElementInitialized == true){
if(mediaElement){
mediaElement.setSrc(src);
mediaElement.play();
}
} else {
//recursive.. ie8/flashplayer fallback fix..
var self = this;
setTimeout(function(){
self.setSource(src);
},100);
}
}
var plugin = new MediaElementPlayer(#mplay_audio_p',
{
//...params...
});
var url="http://www.somesite.com/audiofile.mp3";
plugin.setSrc(url);
plugin.load();
plugin.play();

changing source on html5 video tag

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

Categories

Resources