CaptureElement preview not available sometimes - windows-runtime

I have problem with initialization camera on Windows Universal Apps. This code works and never throw any exception, but i have wrapped it into dialog control. Problem is sometimes (1/10 dialog openings) i don't see preview from camera. Have you any idea how to fix that or at least check if preview is displayed?
private async Task InitCameraAsync()
{
var devices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
var backCam = devices.FirstOrDefault(q => q.EnclosureLocation != null && q.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back);
var mediaCapture = new MediaCapture();
if (backCam != null)
{
await mediaCapture.InitializeAsync(new MediaCaptureInitializationSettings()
{
VideoDeviceId = backCam.Id,
AudioDeviceId = String.Empty,
StreamingCaptureMode = StreamingCaptureMode.Video,
PhotoCaptureSource = PhotoCaptureSource.VideoPreview
});
}
else
{
await mediaCapture.InitializeAsync();
}
CameraControl.Source = mediaCapture;
SetImageEncodingProperties(); // get encoding properties to save images
await SetPreviewResolutionAsync();
await CameraControl.Source.StartPreviewAsync();
}
}

Are you sure that you are calling the function from the UI thread to access the camera for the API to run reliably?
https://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.core.coredispatcher.runasync.aspx

Related

how to turn on flashlight on windows phone 8.1

I created project based on:
https://github.com/Microsoft/real-time-filter-demo/tree/master/RealtimeFilterDemoWP
My question is how to enable flash light (torch) on WP8.1
Should I use MediaCapture() ?
var mediaDev = new MediaCapture();
await mediaDev.InitializeAsync();
var videoDev = mediaDev.VideoDeviceController;
var tc = videoDev.TorchControl;
if (tc.Supported)
{
if (tc.PowerSupported)
tc.PowerPercent = 100;
tc.Enabled = true;
}
when I used it it crash on
var videoDev = mediaDev.VideoDeviceController;
by unhandled exception
How to add flashlight to this sample project ?
You haven't initialized the MediaCaptureSettings, thus when you attempt to initialize the videoController the exception occurs. You need to initialize the settings, let MediaCapture know what device you'd like to use, and setup the VideoDeviceController. In addition, for Windows Phone 8.1 camera drivers, some require you to start the preview, or others require you to start video recording to turn on flash. This is due to the flash being tightly coupled with the camera device.
Here's some general code to give you the idea. *Disclaimer, this is untested. Best sure to call this in an async Task method so you can assure the awaited calls complete before you attempt to toggle the Torch Control property.
private async Task InitializeAndToggleTorch()
{
// Initialize Media Capture and Settings Objects, mediaCapture declared global outside this method
mediaCapture = new MediaCapture();
MediaCaptureInitializationSettings settings = new MediaCaptureInitializationSettings();
// Grab all available VideoCapture Devices and find rear device (usually has flash)
DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
DeviceInformation device = devices.FirstOrDefault(x => x.EnclosureLocation != null && x.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back);
// Set Video Device to device with flash obtained from DeviceInformation
settings.VideoDeviceId = device.Id;
settings.AudioDeviceId = "";
settings.PhotoCaptureSource = PhotoCaptureSource.VideoPreview;
settings.StreamingCaptureMode = StreamingCaptureMode.Video;
mediaCapture.VideoDeviceController.PrimaryUse = Windows.Media.Devices.CaptureUse.Video;
// Initialize mediacapture now that settings are configured
await mediaCapture.InitializeAsync(settings);
if (mediaCapture.VideoDeviceController.TorchControl.Supported)
{
// Get resolutions and set to lowest available for temporary video file.
var resolutions = mediaCapture.VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.VideoRecord).Select(x => x as VideoEncodingProperties);
var lowestResolution = resolutions.OrderBy(x => x.Height * x.Width).ThenBy(x => (x.FrameRate.Numerator / (double)x.FrameRate.Denominator)).FirstOrDefault();
await mediaCapture.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.VideoRecord, lowestResolution);
// Get resolutions and set to lowest available for preview.
var previewResolutions = mediaCapture.VideoDeviceController.GetAvailableMediaStreamProperties (MediaStreamType.VideoPreview).Select(x => x as VideoEncodingProperties);
var lowestPreviewResolution = previewResolutions.OrderByDescending(x => x.Height * x.Width).ThenBy(x => (x.FrameRate.Numerator / (double)x.FrameRate.Denominator)).LastOrDefault();
await mediaCapture.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.VideoPreview, lowestPreviewResolution);
// Best practice, you should handle Media Capture Error events
mediaCapture.Failed += MediaCapture_Failed;
mediaCapture.RecordLimitationExceeded += MediaCapture_RecordLimitationExceeded;
}
else
{
// Torch not supported, exit method
return;
}
// Start Preview
var captureElement = new CaptureElement();
captureElement.Source = mediaCapture;
await mediaCapture.StartPreviewAsync();
// Prep for video recording
// Get Application temporary folder to store temporary video file folder
StorageFolder tempFolder = ApplicationData.Current.TemporaryFolder;
// Create a temp Flash folder
var folder = await tempFolder.CreateFolderAsync("TempFlashlightFolder", CreationCollisionOption.OpenIfExists);
// Create video encoding profile as MP4
var videoEncodingProperties = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto);
// Create new unique file in the Flash folder and record video
var videoStorageFile = await folder.CreateFileAsync("TempFlashlightFile", CreationCollisionOption.GenerateUniqueName);
// Start recording
await mediaCapture.StartRecordToStorageFileAsync(videoEncodingProperties, videoStorageFile);
// Now Toggle TorchControl property
mediaCapture.VideoDeviceController.TorchControl.Enabled = true;
}
Phew! That's a lot of code just to toggle flash huh? Good news is this is fixed in Windows 10 with new Windows.Devices.Lights.Lamp API. You can do same work in just a few lines of code:
Windows 10 Sample for Windows.Devices.Lights.Lamp
For reference, check this thread:
MSDN using Win8.1 VideoDeviceController.TorchControl

Why is my WinRT app closing when trying to debug my background task?

I am trying to experiment with downloading files on a regular basis with background tasks for windows store applications, and am having trouble.
I followed the sample at https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh977055.aspx, and even downloaded/ran it and everything worked perfectly (including being able to step into the timer background task).
So with that I created my own background task in a brand new Windows namespace
Win8BackgroundTest
{
public class TestBackgroundTask
{
public async void Run(IBackgroundTaskInstance taskInstance)
{
var deferral = taskInstance.GetDeferral();
var uri = new Uri("http://download.blender.org/peach/bigbuckbunny_movies/big_buck_bunny_480p_h264.mov");
var folder = ApplicationData.Current.LocalFolder;
var downloadFile = await folder.CreateFileAsync(uri.Segments.Last(), CreationCollisionOption.GenerateUniqueName);
var dataFile = await folder.CreateFileAsync("downloadData", CreationCollisionOption.GenerateUniqueName);
var downloader = new BackgroundDownloader();
var operation = downloader.CreateDownload(uri, downloadFile);
await FileIO.WriteTextAsync(dataFile, "Success at " + DateTime.Now);
deferral.Complete();
}
public static async void RegisterTask()
{
const string taskName = "TestBackgroundTask";
try
{
var status = await BackgroundExecutionManager.RequestAccessAsync();
if (status == BackgroundAccessStatus.Denied)
{
return;
}
}
catch
{
// already accepted
}
var tasks = BackgroundTaskRegistration.AllTasks
.Where(x => x.Value.Name == taskName)
.ToArray();
if (tasks.Any())
{
return;
}
var builder = new BackgroundTaskBuilder
{
Name = taskName,
TaskEntryPoint = "Win8BackgroundTest.TestBackgroundTask",
};
builder.SetTrigger(new TimeTrigger(60, false));
var registeredTask = builder.Register();
}
}
}
I set up the application's manifest with a Background Tasks declaration, checking the Timer properties checkbox, and set the EntryPoint to Win8BackgroundTest.TestBackgroundTask.
I then added the following at the end of my App.xaml.cs's OnLaunched() method:
TestBackgroundTask.RegisterTask();
Stepping through seems to have task registration work successfully with no exceptions. I then go back to visual studio, added a breakpoint to the first line in my task's Run() method, I then go to the debug locations toolbar, click the down arrow and select TestBackgroundTask. A few seconds later visual studio exits (as does my app).
Does anyone see what I am doing wrong that is causing background tasks to fail?
So after much frustration and a lot of trial and error the issue was a combination of both of the comments.
So first of all, it appears like you cannot have a background task in the same project as the rest of your windows store application. It must be in it's own windows runtime component project.
Finally, there are times where it just doesn't work and for whatever reason deleting the bin and obj folders fix it.

Chrome speech API network error

I'm trying to create a PHP web application using Chrome web speech API. I'm always getting network errors. But, I have a good network connection.
window.SpeechRecognition = window.SpeechRecognition
|| window.webkitSpeechRecognition || null;
if (window.SpeechRecognition === null) {
} else {
var recognizer = new window.SpeechRecognition();
recognizer.continuous = false;
recognizer.lang = 'en-US';
recognizer.onstart = function() {
recognizing = true;
};
recognizer.onresult = function(event) {
};
}
recognizer.onerror = function(event) {
alert(event.error);
ignore_onend = true;
if (event.error == 'not-allowed') {
alert("Allow to access your microphone");
}
recognizer.stop();
recognizer.start();
};
Thanks
I have similar problem since the last Google update and I am sure that there is a bug in the last Update. I have similar thread at RecognizerIntent gives error after latest Google Search update
My android app gives network error for recognizerintent. Till then, there was no network problem.
In summary the error is W/JavaNetConnection﹕ Failed to get connection status. java.io.FileNotFoundException: https://www.google.com/m/voice-search/down?pair=6239918a-dc45-4eea-ac6f-b9bf8de57ced

What could cause Launcher.LaunchFileAsync to fail intermittently

In my windows store app, I allow users to open up a file, it does not exist locally then app will download it and save it the local folder of the app and then try to open it using the code below.
This works intermittently, other time the call returns false.
var launcherOption = new LauncherOptions();
launcherOption.DesiredRemainingView = Windows.UI.ViewManagement.ViewSizePreference.Default;
launcherOption.DisplayApplicationPicker = userSettings.ShowApplicationPicker;
bool success;
// fileResponse.File is a StorageFile object
if (fileResponse.OpenAs == ContentOpenOption.LocalFile)
success = await Launcher.LaunchFileAsync(fileResponse.File, launcherOption);
else
success = await Launcher.LaunchUriAsync(fileResponse.WebUri, launcherOption);
Things I have checked for:
The file is not restricted by windows ( eg: I am testing with txt, jpg files, not exe, bin, bat )
My app is visible at the time this call is made
The call is made on the UI Thread by using the code below:
var launcherOption = new LauncherOptions();
launcherOption.DesiredRemainingView = Windows.UI.ViewManagement.ViewSizePreference.UseHalf;
launcherOption.DisplayApplicationPicker = userSettings.ShowApplicationPicker;
var dispatcherObject = CoreApplication.MainView.CoreWindow.Dispatcher;
if (dispatcherObject != null && dispatcherObject.HasThreadAccess == false)
{
await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
Windows.UI.Core.CoreDispatcherPriority.Normal,
async () =>
{
if (fileResponse.OpenAs == ContentOpenOption.LocalFile)
success = await Launcher.LaunchFileAsync(fileResponse.File, launcherOption);
else
{
launcherOption.TreatAsUntrusted = true;
success = await Launcher.LaunchUriAsync(fileResponse.WebUri, launcherOption);
}
});
}
else
{
if (fileResponse.OpenAs == ContentOpenOption.LocalFile)
success = await Launcher.LaunchFileAsync(fileResponse.File, launcherOption);
else
{
launcherOption.TreatAsUntrusted = true;
success = await Launcher.LaunchUriAsync(fileResponse.WebUri, launcherOption);
}
}
if (!success)
{
content.IsContentUpdating = false;
content.ContentStatus = string.Empty;
logger.LogMessage(string.Format("Unable to open file. {0}",
content.Name), LoggingLevel.Error);
}
}
Made sure that the file is not blocked by windows by checking it's properties.
Any other ideas what I might be missing here?

PDFTron Convert from HTML to PDF on WinRT

I'm writing a Windows 8 Store App using WinJS. My app needs to generate PDFs with text and graphs. I was under the impression that PDFtron could convert HTML to PDF, but that does not seem to be the case for an App Store application. Is this true?
The front end uses WinJS/HTML and Telerik Radcharts to render graphs in SVG. I then pipe the DOM down to disk as an HTML file. It shows the graph and numbers nicely. I want to convert the HTML to a PDF to preserve the styling as well as the content.
The WinRT version does not come with the HTML2PDF assembly or the .Convert() method. Is it somewhere else? I've searched the docs, samples, and the web.
PDFTron's PDFNet SDK on WinRT does not support HTML to PDF conversion (as at version 6.2).
Here is the response I received from PDFTron support on this question:
While the PDFNet SDK on WinRT cannot itself convert from HTML
to PDF, the PDFNet SDK on Windows desktop can do so. You can find
sample code for for HTML to PDF conversion at
http://www.pdftron.com/pdfnet/samplecode.html#HTML2PDF.
Some of our clients send HTML to a server of theirs, where
PDFNet can convert the HTML to PDF. Note that on Windows
desktop there are many conversion options, including converting Office
to PDF and converting any printable document format to PDF.
EVO has implemented the following solution to convert HTML to PDF in WinRT and Windows Store Applications. You can find a compelte code sample in that page.
The copy of the code sample is:
private async void buttonConvertUrlToPdf_Click(object sender, RoutedEventArgs e)
{
// If another conversion is in progress then ignore current request
bool ignoreRequest = false;
lock(pendingConversionSync)
{
if (pendingConversion)
ignoreRequest = true;
else
{
msgUrlToPdfInProgress.Visibility = Windows.UI.Xaml.Visibility.Visible;
pendingConversion = true;
}
}
if (ignoreRequest)
return;
try
{
String serverIP = textBoxServerIP.Text;
uint port = uint.Parse(textBoxServerPort.Text);
HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter(serverIP, port);
// set service password if necessary
if (textBoxServicePassword.Text.Length > 0)
htmlToPdfConverter.ServicePassword = textBoxServicePassword.Text;
// set HTML viewer width
htmlToPdfConverter.HtmlViewerWidth = int.Parse(textBoxHtmlViewerWidth.Text);
// set HTML viewer height if necessary
if (textBoxHtmlViewerHeight.Text.Length > 0)
htmlToPdfConverter.HtmlViewerHeight = int.Parse(textBoxHtmlViewerHeight.Text);
// set navigation timeout
htmlToPdfConverter.NavigationTimeout = int.Parse(textBoxHtmlViewerWidth.Text);
// set conversion delay if necessary
if (textBoxConversionDelay.Text.Length > 0)
htmlToPdfConverter.ConversionDelay = int.Parse(textBoxConversionDelay.Text);
// set PDF page size
htmlToPdfConverter.PdfDocumentOptions.PdfPageSize = SelectedPdfPageSize();
// set PDF page orientation
htmlToPdfConverter.PdfDocumentOptions.PdfPageOrientation = SelectedPdfPageOrientation();
// set margins
htmlToPdfConverter.PdfDocumentOptions.LeftMargin = int.Parse(textBoxLeftMargin.Text);
htmlToPdfConverter.PdfDocumentOptions.RightMargin = int.Parse(textBoxRightMargin.Text);
htmlToPdfConverter.PdfDocumentOptions.TopMargin = int.Parse(textBoxTopMargin.Text);
htmlToPdfConverter.PdfDocumentOptions.BottomMargin = int.Parse(textBoxBottomMargin.Text);
// add header
if (checkBoxAddHeader.IsChecked != null && (bool)checkBoxAddHeader.IsChecked)
{
htmlToPdfConverter.PdfDocumentOptions.ShowHeader = true;
DrawHeader(htmlToPdfConverter, true);
}
// add footer
if (checkBoxAddFooter.IsChecked != null && (bool)checkBoxAddFooter.IsChecked)
{
htmlToPdfConverter.PdfDocumentOptions.ShowFooter = true;
DrawFooter(htmlToPdfConverter, true, true);
}
string urlToConvert = textBoxUrl.Text;
string errorMessage = null;
// Convert the HTML page from give URL to PDF in a buffer
byte[] pdfBytes = await Task.Run<byte[]>(() =>
{
byte[] resultBytes = null;
try
{
resultBytes = htmlToPdfConverter.ConvertUrl(urlToConvert);
}
catch (Exception ex)
{
errorMessage = String.Format("Conversion failed. {0}", ex.Message);
return null;
}
return resultBytes;
});
if (pdfBytes == null)
{
MessageDialog errorMessageDialog = new MessageDialog(errorMessage, "Conversion failed");
await errorMessageDialog.ShowAsync();
return;
}
// Save the PDF in a file
Windows.Storage.StorageFolder installedLocation = Windows.Storage.ApplicationData.Current.LocalFolder;
StorageFile outStorageFile = installedLocation.CreateFileAsync("EvoHtmlToPdf.pdf", CreationCollisionOption.ReplaceExisting).AsTask().Result;
FileIO.WriteBytesAsync(outStorageFile, pdfBytes).AsTask().Wait();
// Open the file in a PDF viewer
await Windows.System.Launcher.LaunchFileAsync(outStorageFile);
}
finally
{
lock (pendingConversionSync)
{
msgUrlToPdfInProgress.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
pendingConversion = false;
}
}
}