HTML video player - javascript

I want to play video file from local disk in browser so I found this code. Can You tell me why it does not work? On jsfiddle it works but when i copy it into project it won't work. Also can You tell me what gives function declaration like function name(x){variables}(window).
The error I get is Uncaught TypeError: Cannot read property 'addEventListener' of null
Thanks for Your help :)
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<script>
(function localFileVideoPlayerInit(win) {
var URL = win.URL || win.webkitURL,
playSelectedFile = function playSelectedFileInit(event) {
var file = this.files[0];
var type = file.type;
var videoNode = document.querySelector('video');
var canPlay = videoNode.canPlayType(type);
canPlay = (canPlay === '' ? 'no' : canPlay);
var message = 'Can play type "' + type + '": ' + canPlay;
var isError = canPlay === 'no';
displayMessage(message, isError);
if (isError) {
return;
}
var fileURL = URL.createObjectURL(file);
videoNode.src = fileURL;
},
inputNode = document.querySelector('input');
if (!URL) {
displayMessage('Your browser is not ' +
'supported!', true);
return;
}
inputNode.addEventListener('change', playSelectedFile, false);
}(window));
</script>
<h1>HTML5 local video file player example</h1>
<div id="message"></div>
<input type="file" accept="video/*"/>
<video controls autoplay></video>
</body>
</html>

The problem is, your code is running before the DOM is ready/loaded.
There's two way to fix this.
1) Move the the entire javascript code block below <video controls autoplay></video>
or
2) Use document.addEventListener("DOMContentLoaded", function() { }); like this:
<script>
document.addEventListener("DOMContentLoaded", function() {
var URL = window.URL || window.webkitURL,
playSelectedFile = function playSelectedFileInit(event) {
var file = this.files[0];
var type = file.type;
var videoNode = document.querySelector('video');
var canPlay = videoNode.canPlayType(type);
canPlay = (canPlay === '' ? 'no' : canPlay);
var message = 'Can play type "' + type + '": ' + canPlay;
var isError = canPlay === 'no';
displayMessage(message, isError);
if (isError) {
return;
}
var fileURL = URL.createObjectURL(file);
videoNode.src = fileURL;
},
inputNode = document.querySelector(("input[type=file]"));
if (!URL) {
displayMessage('Your browser is not ' +
'supported!', true);
return;
}
inputNode.addEventListener('change', playSelectedFile, false);
});
</script>

Related

How to create a screenshot of browser window and save it to another page

I would like to ask what is the logic behind capturing the screen of browser window.Can we open this screenshot image in popup where user have an option to save the screenshot.
Here is my code In this code the Problem is that my browser screen have image also it captures text but not capturing image I couldn't get where the problem is ? Here is my code
<html lang="en">
<head>
<title>Take Web Page Screenshot with HTML5 and JavaScript </title>
</head>
<body>
<div>
<div style="background-image:url('assets/images/act.png');height: 50px;width: 50px;"></div>
<div><a class="btn btn-success" href="javascript:void(0);" onclick="generate()">Generate
Screenshot ยป</a>
</div>
<div>fsaffsfasfasfasfasfasff</div>
</div>
<script type="text/javascript">
(function (exports) {
function urlsToAbsolute(nodeList) {
console.log(nodeList);
if (!nodeList.length) {
return [];
}
var attrName = 'href';
if (nodeList[0].__proto__ === HTMLImageElement.prototype || nodeList[0].__proto__===HTMLScriptElement.prototype) {
attrName = 'src';
}
nodeList = [].map.call(nodeList, function (el, i) {
var attr = el.getAttribute(attrName);
if (!attr) {
return;
}
var absURL = /^(https?|data):/i.test(attr);
console.log(absURL);
if (absURL) {
return el;
} else {
return el;
}
});
return nodeList;
}
function screenshotPage() {
urlsToAbsolute(document.images);
urlsToAbsolute(document.querySelectorAll("link[rel='stylesheet']"));
var screenshot = document.documentElement.cloneNode(true);
var b = document.createElement('base');
b.href = document.location.protocol + '//' + location.host;
var head = screenshot.querySelector('head');
head.insertBefore(b, head.firstChild);
screenshot.style.pointerEvents = 'none';
screenshot.style.overflow = 'hidden';
screenshot.style.webkitUserSelect = 'none';
screenshot.style.mozUserSelect = 'none';
screenshot.style.msUserSelect = 'none';
screenshot.style.oUserSelect = 'none';
screenshot.style.userSelect = 'none';
screenshot.dataset.scrollX = window.scrollX;
screenshot.dataset.scrollY = window.scrollY;
var script = document.createElement('script');
script.textContent = '(' + addOnPageLoad_.toString() + ')();';
screenshot.querySelector('body').appendChild(script);
var blob = new Blob([screenshot.outerHTML], {
type: 'text/html'
});
return blob;
}
function addOnPageLoad_() {
window.addEventListener('DOMContentLoaded', function (e) {
var scrollX = document.documentElement.dataset.scrollX || 0;
var scrollY = document.documentElement.dataset.scrollY || 0;
window.scrollTo(scrollX, scrollY);
});
}
function generate() {
window.URL = window.URL || window.webkitURL;
window.open(window.URL.createObjectURL(screenshotPage()));
}
exports.screenshotPage = screenshotPage;
exports.generate = generate;
})(window);
</script>
</body>
</html>

Unable to stream video over a websocket to Firefox

I have written some code stream video over a websocket so a sourcebuffer which works in Chrome and Edge.
However, when I run this in Firefox, the video never plays back, just a spinning wheel animation is displayed. When I check the <video> statistics, It reads HAVE_METADATA as the ready state and NETWORK_LOADING as the network state.
The code looks follows:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<video controls></video>
<script>
var mime = 'video/mp4; codecs="avc1.4D401E,mp4a.40.2"';
var address = 'ws://localhost:54132'
/* Media Source */
var source = new MediaSource();
var video = document.querySelector('video');
video.src = URL.createObjectURL(source);
source.addEventListener('sourceopen', sourceOpen);
/* Buffer */
var buffer;
var socket;
var queue = [];
var offset = -1;
var timescale;
// When the media source opens:
function sourceOpen() {
buffer = source.addSourceBuffer(mime);
buffer.addEventListener('updateend', processQueue);
socket = new WebSocket(address);
socket.binaryType = 'arraybuffer';
socket.onmessage = onMessage;
}
// When more data is received.
function onMessage(event) {
queue.push(event.data);
processQueue();
}
// Process queue if possible.
function processQueue() {
if ((queue.length == 0) || (buffer.updating)) {
return;
}
var data = queue.shift();
if (offset === -1) {
var parsed = parseMP4(data);
if (parsed.hasOwnProperty('moov')) {
timescale = parsed.moov.mvhd.timescale;
} else if (parsed.hasOwnProperty('moof')) {
offset = 0 - (parsed.moof.traf[0].tfdt.baseMediaDecodeTime / this.timescale - 0.4);
buffer.timestampOffset = offset;
}
}
// console.log('appending ' + data.byteLength + ' bytes');
buffer.appendBuffer(data);
}
// Parse out the offset.
function parseMP4(data) {
// SNIP for brevity
}
</script>
</body>
</html>
Could not reproduce <video> element not playing at firefox 47.
Merged approaches at Mocking Websocket Message Events to create mock WebSocket events; bufferAll.html demo at Let's Make a Netflix
An Intro to Streaming Media on the Web for MediaSource usage pattern.
Included <progress> and progress event to notify user of media loading status.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<progress min="0" value="0"></progress><br><label></label><br>
<video controls></video>
<script>
// http://nickdesaulniers.github.io/netfix/demo/bufferAll.html
// http://jsfiddle.net/adamboduch/JVfkt/
// The global web socket.
var sock, sourceBuffer;
sock = new WebSocket( "ws://mock" );
sock.onerror = function(e) {
console.log("sock error", e)
}
// This is unchanging production code that doesn"t know
// we"re mocking the web socket.
sock.onmessage = function( e ) {
console.log("socket message", e.data);
sourceBuffer.appendBuffer(e.data);
};
var video = document.querySelector("video");
var progress = document.querySelector("progress");
var label = document.querySelector("label");
var assetURL = "http://nickdesaulniers.github.io/netfix/"
+ "demo/frag_bunny.mp4";
// Need to be specific for Blink regarding codecs
// ./mp4info frag_bunny.mp4 | grep Codec
var mimeCodec = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"';
if ("MediaSource" in window
&& MediaSource.isTypeSupported(mimeCodec)) {
var mediaSource = new MediaSource;
//console.log(mediaSource.readyState); // closed
video.src = URL.createObjectURL(mediaSource);
mediaSource.addEventListener("sourceopen", sourceOpen);
} else {
console.error("Unsupported MIME type or codec: ", mimeCodec);
}
video.addEventListener("canplay", function() {
alert("video canplay")
})
function sourceOpen (_) {
//console.log(this.readyState); // open
var mediaSource = this;
sourceBuffer = mediaSource.addSourceBuffer(mimeCodec);
fetchAB(assetURL, function (buf) {
sourceBuffer.addEventListener("updateend", function (event) {
console.log("sourceBuffer updateend event;"
+ "mediaSource.readyState:"
, mediaSource.readyState);
// mediaSource.endOfStream();
// video.play();
// console.log(mediaSource.readyState); // ended
});
});
};
// mock `WebSocket` message
function fetchAB (url, cb) {
var xhr = new XMLHttpRequest;
xhr.open("get", url);
var file = url.split("/").pop();
xhr.responseType = "arraybuffer";
xhr.onload = function () {
// mock `WebSocket` message
sock.dispatchEvent( new MessageEvent( "message", {
data: xhr.response
}));
console.log("video sent to sock", sock);
cb();
};
xhr.onprogress = function(e) {
progress.max = e.total;
progress.value = e.loaded;
label.innerHTML = "loading " + file + " ...<br>"
+ e.loaded + " of "
+ e.total + " bytes loaded";
}
xhr.send();
};
</script>
</body>
</html>
plnkr http://plnkr.co/edit/RCIqDXTB2BL3lec9bhfz
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<progress min="0" value="0"></progress><br><label></label><br>
<video controls></video>
<script>
// http://nickdesaulniers.github.io/netfix/demo/bufferAll.html
// http://jsfiddle.net/adamboduch/JVfkt/
// The global web socket.
var sock, sourceBuffer;
sock = new WebSocket( "ws://mock" );
sock.onerror = function(e) {
console.log("sock error", e)
}
// This is unchanging production code that doesn"t know
// we"re mocking the web socket.
sock.onmessage = function( e ) {
console.log("socket message", e.data);
sourceBuffer.appendBuffer(e.data);
};
var video = document.querySelector("video");
var progress = document.querySelector("progress");
var label = document.querySelector("label");
var assetURL = "http://nickdesaulniers.github.io/netfix/"
+ "demo/frag_bunny.mp4";
// Need to be specific for Blink regarding codecs
// ./mp4info frag_bunny.mp4 | grep Codec
var mimeCodec = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"';
if ("MediaSource" in window
&& MediaSource.isTypeSupported(mimeCodec)) {
var mediaSource = new MediaSource;
//console.log(mediaSource.readyState); // closed
video.src = URL.createObjectURL(mediaSource);
mediaSource.addEventListener("sourceopen", sourceOpen);
} else {
console.error("Unsupported MIME type or codec: ", mimeCodec);
}
video.addEventListener("canplay", function() {
alert("video canplay")
})
function sourceOpen (_) {
//console.log(this.readyState); // open
var mediaSource = this;
sourceBuffer = mediaSource.addSourceBuffer(mimeCodec);
fetchAB(assetURL, function (buf) {
sourceBuffer.addEventListener("updateend", function (event) {
console.log("sourceBuffer updateend event;"
+ "mediaSource.readyState:"
, mediaSource.readyState);
// mediaSource.endOfStream();
// video.play();
// console.log(mediaSource.readyState); // ended
});
});
};
// mock `WebSocket` message
function fetchAB (url, cb) {
var xhr = new XMLHttpRequest;
xhr.open("get", url);
var file = url.split("/").pop();
xhr.responseType = "arraybuffer";
xhr.onload = function () {
// mock `WebSocket` message
sock.dispatchEvent( new MessageEvent( "message", {
data: xhr.response
}));
console.log("video sent to sock", sock);
cb();
};
xhr.onprogress = function(e) {
progress.max = e.total;
progress.value = e.loaded;
label.innerHTML = "loading " + file + " ...<br>"
+ e.loaded + " of "
+ e.total + " bytes loaded";
}
xhr.send();
};
</script>
</body>
</html>

Iframe Dom error :cannot read property "src" of null

I putted my editor.html in a iframe using this code :
<iframe name= "iframeEditor" id="ifrm" src="editor.html" width="1000" height="500" frameborder="0"></iframe>
then, i have to access to an element in a script balise in my "editor.html" :
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Diagram</title>
<script type="text/javascript" src="lib/jquery-1.8.1.js"></script>
<!-- I use many resources -->
<script>
function generatePNG (oViewer) {
var oImageOptions = {
includeDecoratorLayers: false,
replaceImageURL: true
};
var sResult = oViewer.generateImageBlob(function(sBlob) {
b = 64;
var reader = new window.FileReader();
reader.readAsDataURL(sBlob);
reader.onloadend = function() {
base64data = reader.result;
var image = document.createElement('img');
image.setAttribute("id", "GraphImage");
image.src = base64data;
document.body.appendChild(image);
}
}, "image/png", oImageOptions);
return sResult;
}
</script>
</head>
<body >
<div id="diagramContainer"></div>
</body>
</html>
I should access to image.src from the iframe that contain my editor.htm so i try with this code :
<script>
var if1 = document.getElementById("ifrm");
var fc = (if1.contentWindow || if1.contentDocument);
var img1 = fc.document.getElementById("GraphImage");
console.log(img1.src);
</script>
but i get an error : cannot read property "src" of null
You are running script that looks for image element before image is loaded, so it's not yet added to DOM.
move your script to separate function:
function yourScript() {
var if1 = document.getElementById("ifrm");
var fc = (if1.contentWindow || if1.contentDocument);
var img1 = fc.document.getElementById("GraphImage");
console.log(img1.src);
}
and run it at the end of onloadend callback:
function generatePNG (oViewer) {
var oImageOptions = {
includeDecoratorLayers: false,
replaceImageURL: true
};
var sResult = oViewer.generateImageBlob(function(sBlob) {
b = 64;
var reader = new window.FileReader();
reader.readAsDataURL(sBlob);
reader.onloadend = function() {
base64data = reader.result;
var image = document.createElement('img');
image.setAttribute("id", "GraphImage");
image.src = base64data;
document.body.appendChild(image);
yourScript(); // your script is run after appending image to body
}
}, "image/png", oImageOptions);
return sResult;
}

Disqus in Ionic APP

I am trying to implement disqus commments in my ionic app. I know I have to host it on the domain its setup for which I believe I have configured correctly. Any assistance will be welcomed
Here is the code in my app.js for the ionic app
$scope.showComments = function () {
$scope.currentView = "comments";
//loadComments(params["shortname"], params["url"], params["title"], params["identifier"]);
//
var disqus_title = "Venue 1";
var disqus_identifier = '/venue/' + $stateParams.id;
var disqus_url = 'liverpool.li/venue/' + $stateParams.id;
var url = "http://liverpool.li/app/disqus.html?";
$scope.url = url + "shortname=liverpoolli&url=" + encodeURIComponent(disqus_url) +
"&title=" + encodeURIComponent(disqus_title) + "&identifier=" + encodeURIComponent(disqus_identifier);
$scope.url = $sce.trustAsResourceUrl($scope.url);
};
$scope.$on("$destroy", function () {
if ($scope.lastScriptElm && $scope.lastScriptElm.parentNode) {
$scope.lastScriptElm.parentNode.removeChild($scope.lastScriptElm);
$scope.lastScriptElm = null;
}
});
And the page it points to (disqus.html) located on my domain
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
</head>
<body>
<div id="disqus_thread"></div>
<script type="text/javascript">
var params;
var disqus_url;
var disqus_title;
var disqus_shortname;
var disqus_identifier;
window.onload = function () {
var match,
pattern = /\+/g,
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pattern, " ")); },
query = window.location.search.substring(1);
params = {};
while (match = search.exec(query))
params[decode(match[1])] = decode(match[2]);
if (params["shortname"] === undefined || params["url"] === undefined || params["title"] === undefined) {
alert("Required arguments missing");
}
else {
loadComments(params["shortname"], params["url"], params["title"], params["identifier"]);
}
};
function loadComments(shortname, url, title, identifier) {
disqus_url = url;
disqus_title = title;
disqus_shortname = shortname;
if (identifier !== undefined)
disqus_identifier = identifier;
else
disqus_identifier = "";
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = false;
dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
}
</script>
<noscript>Please enable JavaScript to view the comments powered by Disqus.</noscript>
blog comments powered by <span class="logo-disqus">Disqus</span>
</body>
</html>
I get the following error
we were unable to load disqus. if you are a moderator please see our
troubleshooting guide.
It looks like you're almost there. The only issue I see is the disqus_url variable must also include the protocol to be valid. Try using this line instead:
var disqus_url = 'http://liverpool.li/venue/' + $stateParams.id;

Receiving "decodeAudioData error null" in Chrome

Hello Web Audio Developers,
I am receiving "decodeAudioData error null" in Chrome
and
"decodeAudioData error undefined" in Firebug.
Firebug also says
"The buffer passed to decodeAudioData contains an unknown content type."
Is there something wrong with this code or
is there something else that needs to be worked out with the
"Web Audio API"?
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<title>Together 2 </title>
</head>
<body>
<script type="text/javascript">
window.onload = init;
var context;
var bufferLoader;
function init() {
window.AudioContext = window.AudioContext || window.webkitAudioContext;
context = new AudioContext();
bufferLoader = new BufferLoader(context,
[ '../web-audio/path/chrono.mp3' ],
finishedLoading
);
bufferLoader.load();
}
function finishedLoading(bufferList) {
var source1 = context.createBufferSource();
source1.buffer = bufferList[0];
source1.connect(context.destination);
source1.start(0);
}
function BufferLoader(context, urlList, callback) {
this.context = context;
this.urlList = urlList;
this.onload = callback;
this.bufferList = new Array();
this.loadCount = 0;
}
BufferLoader.prototype.loadBuffer = function(url, index) { // Load buffer asynchronously
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.responseType = "arraybuffer";
var loader = this;
request.onload = function() {
// Asynchronously decode the audio file data in request.response
loader.context.decodeAudioData(
request.response,
function(buffer) {
if (!buffer) {
alert('error decoding file data: ' + url);
return;
}
loader.bufferList[index] = buffer;
if (++loader.loadCount == loader.urlList.length)
loader.onload(loader.bufferList);
},
function(error) {
console.error('decodeAudioData error', error);
}
);
}
request.onerror = function() {
alert('BufferLoader: XHR error');
}
request.send();
}
BufferLoader.prototype.load = function() {
for (var i = 0; i < this.urlList.length; ++i)
this.loadBuffer(this.urlList[i], i);
}
</script>
</body>
</html>
I had the same problem and it was down to the type of codec used on the wav file itself. Only PCM is supported whereas the files that were throwing me errors were MS-ADPCM. You can use QuickTime or VLC to get the codec information and convert them to PCM if necessary.
I'd imagine that it is a similar issue with your MP3.

Categories