Im testing some media features with ionic and im stuck while trying to set the camera output into a video tag using getUserMedia using this code:
navigator.getUserMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia;
if (navigator.getUserMedia) {
navigator.getUserMedia({ audio: false, video: { width: 500, height: 500 } },
function(stream) {
console.log("Im streaming!!", stream);
var video = document.querySelector('video');
console.log("video element", video);
video.src = window.URL.createObjectURL(stream);
video.onloadedmetadata = function(e) {
console.log("stream start");
video.play();
};
},
function(err) {
console.log("The following error occurred: " + err.name);
}
);
} else {
console.log("getUserMedia not supported");
}
this is the html:
<ion-pane>
<ion-header-bar class="bar-stable">
<h1 class="title">Ionic Blank Starter</h1>
</ion-header-bar>
<ion-content>
<video id="video" autoplay="autoplay" width="500" height="500"></video>
</ion-content>
</ion-pane>
i can actually get only a black screen. Is my approach right or im missing something?
I managed to reproduce the problem and solved it by using the constraints options. Using constraints you can set the sourceId that allows you to select between front or rear camera. Im sure that your device has no front camera and i guess this is why you are getting the black screen.
First we create our constraint options:
var constraints = {};
MediaStreamTrack.getSources (function(sources) {
sources.forEach(function(info) {
if (info.facing == "environment") {
constraints = {
video: {
optional: [{sourceId: info.id}]
}
};
}
})
})
Then we call the navigator.getUserMedia:
navigator.getUserMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia;
if (navigator.getUserMedia) {
navigator.getUserMedia(constraints,
function(stream) {
console.log("Im streaming!!", stream);
var video = document.querySelector('video');
console.log("video element", video);
video.src = window.URL.createObjectURL(stream);
video.onloadedmetadata = function(e) {
console.log("stream start");
video.play();
};
},
function(err) {
console.log("The following error occurred: " + err.name);
}
);
} else {
console.log("getUserMedia not supported");
}
Warning: MediaStreamTrack.getSources returns a promise so that means that if you try to run your navigator.getUserMedia code at once, it will fail. You will have to wrap it in a function and run it as a callback.
More info about camera and audio source selection can be found here:
https://developers.google.com/web/updates/2015/10/media-devices
also a nice example here:
https://simpl.info/getusermedia/sources/
The final solution to this problem is that getUserMedia require a runtime permission check to work. To achieve that i used this plugin. Then this worked like a charm:
cordova.plugins.diagnostic.requestRuntimePermission(function(status){
if(cordova.plugins.diagnostic.runtimePermissionStatus.GRANTED){
navigator.getUserMedia({video: true, audio: false}, function(localMediaStream) {
var video = document.querySelector('video');
video.src = window.URL.createObjectURL(localMediaStream);
video.onloadedmetadata = function(e) {
console.log('Stream is on!!', e);
};
}, errorCallback);
}
});
Related
I am developping a game for Facebook instant games with Phaser 2 CE, and i don't like the loading progress shown at the starting point, how can i get rid of it ?
I am using the default example given in the Quick Start page
FBInstant.initializeAsync()
.then(function() {
var images = ['phaser2'];
for (var i=0; i < images.length; i++) {
var assetName = images[i];
var progress = ((i+1)/images.length) * 100;
game.load.image('./assets/' + assetName + '.png');
// Informs the SDK of loading progress
FBInstant.setLoadingProgress(progress);
}
});
You can try something like given in this example like the code bellow then create your game, i know it's not clean but it works
FBInstant.initializeAsync()
.then(function() {
FBInstant.setLoadingProgress(50);
FBInstant.setLoadingProgress(100);
});
I have tryed something interesting but it doesn't answers the question according to this example
var sprite;
var PixelW = window.innerWidth;
var PixelH = window.innerHeight;
var game = new Phaser.Game(PixelW, PixelH, Phaser.AUTO, 'game', { preload: preload, create: create, update: update });
function preload() {
game.load.onLoadStart.add(loadStart, this);
game.load.onFileComplete.add(fileComplete, this);
startLoading();
}
function startLoading () {
game.load.image('logo1', 'assets/sprites/phaser1.png');
game.load.image('logo2', 'assets/sprites/phaser2.png');
game.load.image('dude', 'assets/sprites/phaser-dude.png');
game.load.image('ship', 'assets/sprites/phaser-ship.png');
game.load.image('mushroom', 'assets/sprites/mushroom.png');
game.load.image('mushroom2', 'assets/sprites/mushroom2.png');
game.load.image('diamond', 'assets/sprites/diamond.png');
game.load.image('bunny', 'assets/sprites/bunny.png');
game.load.start();
}
function create() {
game.stage.backgroundColor = 0x3b5998;
game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
sprite = game.add.sprite(game.world.centerX, game.world.centerY, 'dude');
sprite.inputEnabled = true;
sprite.events.onInputDown.add(myHandler, this);
var text = game.add.text(10, 10, PixelW + " " + " " + PixelH, { font: "65px Arial", fill: "#ffff00", align: "center" });
}
function loadStart() {
}
// This callback is sent the following parameters:
function fileComplete(progress, cacheKey, success, totalLoaded, totalFiles) {
FBInstant.setLoadingProgress(progress);
//console.log(cacheKey + " " + progress);
}
function myHandler() {
sprite.anchor.setTo(0.5, 0.5);
sprite.x = Math.floor(Math.random() * PixelW);
sprite.y = Math.floor(Math.random() * PixelH);
}
function update() {
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<script src="https://connect.facebook.net/en_US/fbinstant.6.0.js"></script>
<script src="phaser.min.js" type="text/javascript"></script>
<title></title>
</head>
<body>
<script type="text/javascript">
var p = 0;
FBInstant.initializeAsync()
.then(function() {
//FBInstant.setLoadingProgress(50);
//FBInstant.setLoadingProgress(100);
});
// Once all assets are loaded, tells the SDK
// to end loading view and start the game
FBInstant.startGameAsync()
.then(function() {
// Retrieving context and player information can only be done
// once startGameAsync() resolves
var contextId = FBInstant.context.getID();
var contextType = FBInstant.context.getType();
var playerName = FBInstant.player.getName();
var playerPic = FBInstant.player.getPhoto();
var playerId = FBInstant.player.getID();
// Once startGameAsync() resolves it also means the loading view has
// been removed and the user can see the game viewport
// game.start();
});
</script>
<div id="game"></div>
<script src="game.js" type="text/javascript"></script>
</body>
</html>
I use the methods below, I increase the loading percent after each file is loaded with Phaser. Also I include a try catch so that when testing local game play the game does not crash.
preload: function () {
try{
FBInstant.initializeAsync()
.then(function() {
});
}
catch(err) {
console.log('FB Instant Games Error: No Internet Connected');
}
this.load.image('gameItem1', 'assets/sprite/game_item1.png');
this.load.image('gameItem2', 'assets/sprite/game_item2.png');
}
And then...
startFacebookGame: function(){
try{
FBInstant.startGameAsync()
.then(function() {
// Retrieving context and player information can only be done
// once startGameAsync() resolves
var contextId = FBInstant.context.getID();
var contextType = FBInstant.context.getType();
var playerName = FBInstant.player.getName();
var playerPic = FBInstant.player.getPhoto();
var playerId = FBInstant.player.getID();
// Once startGameAsync() resolves it also means the loading view has
// been removed and the user can see the game viewport
});
}
catch(err) {
console.log('Analytics Connection Error');
}
},
fileComplete: function(progress, cacheKey, success, totalLoaded, totalFiles) {
try{
FBInstant.setLoadingProgress(progress);
}
catch(err) {
console.log('FB Instant Games progress Failed: No Internet Connected.');
}
//console.log("Progress: " + progress);
},
Here's how I do it. You can build out from there.
function preload() {
// Load some assets
FBInstant.setLoadingProgress(100)
}
function create() {
FBInstant
.startGameAsync()
.then(() => {
// Here you can now get users name etc.
console.log(this)
})
}
FBInstant.initializeAsync()
.then(() => {
new Phaser.Game({
type: Phaser.AUTO,
width: window.innerWidth,
height: window.innerHeight,
scene: {
preload,
create
}
})
})
i am working on a cross-platform mobile app using appcelerator titanium alloy. the code below opens the native camera functionality and works fine on apple devices. on android devices, the camera opens but the button to actually take a picture is disabled (greyed out). the buttons for taking video or changing camera settings work fine, just the take picture button is not working. any ideas? thanks in advance
the code below called on click of takePic button to open camera
takePic.addEventListener('click', function(e) {
var win = Titanium.UI.createWindow({ //Open Camera
});
Titanium.Media.showCamera({
success:function(event){
Ti.API.debug('Our type was: '+event.mediaTpe);
if(event.mediaType == Ti.Media.MEDIA_TYPE_PHOTO){
***win = Titanium.UI.currentWindow;
if(osName == "android"){
win.open();
}***
try {
var image_name = "siteing.jpg";
var fileImage = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, image_name);
fileImage.write(event.media);
Ti.API.log(event.media);
picURL = fileImage;//event.media;
picRaw = event.media; //Raw bytes of picture to save to database
pictureSet = true;
$.videoButton.enabled = false;
$.videoButton.backgroundColor = "#DDDDDD";
//$.audioButton.enabled = false;
format = "Picture";
$.savePic.show();
} catch(e){
alert("An Error:" + e.message);
}
} else {
var alert = createErrorAlert({text:"An error occured getting the media. Please check file size and format and try again."});
$.yesLatLon.add(alert);
alert.show();
}
if(osName == "android"){
win.open();
}
}, cancel:function(){
//called when user cancels taking a picture
if(osName == "android"){
//win.close();
}
}, error:function(error){
//called when there's an error
var a = Titanium.UI.createAlertDialog({title:'Camera'});
if(error.code == Titanium.Media.NO_CAMERA){
a.setMessage('Please run this test on device');
} else {
a.setMessage('Unexpected error: ' + error.code);
}
a.show();
}, saveToPhotoGallery:true,
//allowEditing and mediaTypes are iOS-only settings
allowEditing:true,
mediaTypes:[Ti.Media.MEDIA_TYPE_VIDEO, Ti.Media.MEDIA_TYPE_PHOTO]
});
alert.hide();
$.yesLatLon.removeEventListener('androidback', arguments.callee);
});
screenshot_from_phone
It's been a long time, but I did get this working and thought I'd post my code in case it helps someone else. Fair warning, I now face a different issue with the camera on certain Android devices (Samsung S-series and Google Pixel cannot open camera), which I'm posting in a separate question. However, the original issue with camera button being disabled was successfully resolved last year with the below code.
takePic.addEventListener('click', function(e) {
var win = Titanium.UI.createWindow({//Open Camera
});
Titanium.Media.showCamera({
success : function(event) {
if (event.mediaType == Ti.Media.MEDIA_TYPE_PHOTO) {
win = Titanium.UI.currentWindow;
if (osName == "android") {
var img_view = Titanium.UI.createImageView({
height : '100%',
width : '100%',
});
win.add(img_view);
}
try {
picURL = event.media;
picRaw = event.media;
pictureSet = true;
$.videoButton.enabled = false;
$.videoButton.backgroundColor = "#DDDDDD";
$.savePic.show();
format = "Picture";
} catch(e) {
alert("An Error:" + e.message);
}
} else {
var alert = createErrorAlert({
text : "An error occured getting the media. Please check file size and format and try again."
});
$.yesLatLon.add(alert);
alert.show();
}
},
cancel : function() {
//called when user cancels taking a picture
},
error : function(error) {
//called when there's an error
var a = Titanium.UI.createAlertDialog({
title : 'Camera'
});
if (error.code == Titanium.Media.NO_CAMERA) {
a.setMessage('Please run this test on device');
} else {
a.setMessage('Unexpected error: ' + error.code);
}
a.show();
},
saveToPhotoGallery : true,
allowEditing : false,
autohide : true, //Important!
mediaTypes : [Ti.Media.MEDIA_TYPE_PHOTO]
});
alert.hide();
});
I have a div that i want to screenshot and save,
here is my code
function _download(uri, filename)
{
var el = $('.sf-download-button');
if (el.length)
{
var link = document.createElement('a');
if (typeof link.download === 'string')
{
link.href = uri;
link.download = filename;
document.body.appendChild(link);
//simulate click // this causes page to download an empty html file not sure why
link.click();
//remove the link when done
document.body.removeChild(link);
}
else
{
window.open(uri);
}
}
}
function _save()
{
window.takeScreenShot = function ()
{
var a =document.getElementById("my-div");
html2canvas(document.getElementById("the-div-that-i-want-to-screenshot"), {
onrendered: function (canvas)
{
document.body.appendChild(canvas);
a.append(canvas);
},
width: 220,
height: 310
});
};
$("#btnSave2").click(function ()
{
html2canvas(document.getElementById("data"), {
onrendered: function (canvas)
{
_download_card(canvas.toDataURL(), 'save.png');
}
});
});
}
This is the code i got it from web and added some of my own stuff.code was working i believe but right now, when I click on the button show me the image, it creates the image i can see it but it is just blank.
I tried every possible code combination from jsfiddle and all that and couldn't get anything different as a result.
What could be going wrong here?
I solved the problem by simply changing the browser,
It was not working with Chrome but works perfectly on Mozilla.
Also i changed the code to this,
$("#btnSave").click(function() {
html2canvas($("#card"), {
onrendered: function(canvas) {
theCanvas = canvas;
document.body.appendChild(canvas);
// Convert and download as image
$("#img-out").append(canvas);
// Clean up
//document.body.removeChild(canvas);
}
});
});
Works perfect on Mozilla only.
I have tried numerous ways of adding a cast button to video.js player but cannot do this for the life of me. Can anyone help?
I'm using the hellovideo cms for videos and need plugins added but have no idea about jquery etc.. so please if anyone can help?
There is a really nice plugin for this: https://github.com/kim-company/videojs-chromecast
Just follow the setup instructions (adding the js and css to your page).
I tried kim-company/videojs-chromecast. It only works with an older version of videojs, I used 5.4.6. It's quite buggy. Another I tried was benjipott/video.js-chromecast, which claims to work with newer videojs, but I didn't like it at all. So I gave up on videojs, I always found the native HTML5 video player more reliable and easier to work with (videojs just wraps this anyway). For the chromecast stuff, I provide a nearby button that links to chromecast.link, where I wrote a full web chromecast sender app. Pass the video and poster URL in the fragment, per this example:
https://chromecast.link/#content=http://host/some.mp4,poster=http://host/poster.jpg,subtitles=http://host/webvtt.srt
I recently answered this question, you can check it out here: How to implement chromecast support for html5 player for more information
var session = null;
$( document ).ready(function(){
var loadCastInterval = setInterval(function(){
if (chrome.cast.isAvailable) {
console.log('Cast has loaded.');
clearInterval(loadCastInterval);
initializeCastApi();
} else {
console.log('Unavailable');
}
}, 1000);
});
function initializeCastApi() {
var applicationID = chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID;
var sessionRequest = new chrome.cast.SessionRequest(applicationID);
var apiConfig = new chrome.cast.ApiConfig(sessionRequest,
sessionListener,
receiverListener);
chrome.cast.initialize(apiConfig, onInitSuccess, onInitError);
};
function sessionListener(e) {
session = e;
console.log('New session');
if (session.media.length != 0) {
console.log('Found ' + session.media.length + ' sessions.');
}
}
function receiverListener(e) {
if( e === 'available' ) {
console.log("Chromecast was found on the network.");
}
else {
console.log("There are no Chromecasts available.");
}
}
function onInitSuccess() {
console.log("Initialization succeeded");
}
function onInitError() {
console.log("Initialization failed");
}
$('#castme').click(function(){
launchApp();
});
function launchApp() {
console.log("Launching the Chromecast App...");
chrome.cast.requestSession(onRequestSessionSuccess, onLaunchError);
}
function onRequestSessionSuccess(e) {
console.log("Successfully created session: " + e.sessionId);
session = e;
}
function onLaunchError() {
console.log("Error connecting to the Chromecast.");
}
function onRequestSessionSuccess(e) {
console.log("Successfully created session: " + e.sessionId);
session = e;
loadMedia();
}
function loadMedia() {
if (!session) {
console.log("No session.");
return;
}
var videoSrc = document.getElementById("myVideo").src;
var mediaInfo = new chrome.cast.media.MediaInfo(videoSrc);
mediaInfo.contentType = 'video/mp4';
var request = new chrome.cast.media.LoadRequest(mediaInfo);
request.autoplay = true;
session.loadMedia(request, onLoadSuccess, onLoadError);
}
function onLoadSuccess() {
console.log('Successfully loaded video.');
}
function onLoadError() {
console.log('Failed to load video.');
}
$('#stop').click(function(){
stopApp();
});
function stopApp() {
session.stop(onStopAppSuccess, onStopAppError);
}
function onStopAppSuccess() {
console.log('Successfully stopped app.');
}
function onStopAppError() {
console.log('Error stopping app.');
}
I was trying to recreate the multiple iframes example detailed here for a slideshow. It works flawlessly in all browsers, including desktop safari, except on iphone and ipad.
http://codepen.io/lakshminp/pen/mepIB
Js:
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var players = {}
var YT_ready = (function() {
var onReady_funcs = [],
api_isReady = false;
return function(func, b_before) {
if (func === true) {
api_isReady = true;
for (var i = 0; i < onReady_funcs.length; i++) {
// Removes the first func from the array, and execute func
onReady_funcs.shift()();
}
}
else if (typeof func == "function") {
if (api_isReady) func();
else onReady_funcs[b_before ? "unshift" : "push"](func);
}
}
})();
function onYouTubeIframeAPIReady() {
jQuery(window).bind("load", function() {
YT_ready(true);
});
}
YT_ready(function() {
var identifier = "v9d09JLBVRc";
players[identifier] = new YT.Player(identifier, {
events: {
'onReady': onPlayerReady,
"onStateChange": createYTEvent(identifier)
}
});
});
function onPlayerReady(event) {
event.target.playVideo();
}
// Returns a function to enable multiple events
function createYTEvent(identifier) {
var player = players[identifier]; // Get cached player instance
return function (event) {
console.log(event.data);
}
}
HTML:
<div id="yt-container">
<iframe width="640" height="480" id="v9d09JLBVRc" class="media-youtube-player" src="//www.youtube.com/embed/v9d09JLBVRc?enablejsapi=1&autoplay=0" frameborder="0" allowfullscreen></iframe>
</div>
According to this
functions and parameters such as autoplay, playVideo(), loadVideoById() won't work in all mobile environments
and in your YTReady function, you load dynamically a video and for the moment that's not possible on iOS.
You can also try the YouTubeDemoPage and try to load another id and you will see that it can't be done.
You should also check this.