UWP Media Capture Not Recording Video through WebCam - c#

I am trying to develop a UWP app where I need to record video via webcam. I have followed microsoft tutorial about it here but the problem is I am getting following error again and again and recording does not work.
Error
"This object needs to be initialized before the requested operation
can be carried out.\r\nThis object needs to be initialized before the
requested operation can be carried out."
Here is my code:
int counter = 1;
var myVideos = await Windows.Storage.StorageLibrary.GetLibraryAsync(Windows.Storage.KnownLibraryId.Videos);
StorageFile file = await myVideos.SaveFolder.CreateFileAsync("survillance "+DateTime.Now.ToString("dd-MM-yyyy")+"_"+counter+".wmv", CreationCollisionOption.GenerateUniqueName);
try
{
MediaEncodingProfile recordProfile = null;
recordProfile = MediaEncodingProfile.CreateWmv(VideoEncodingQuality.Auto);
_mediaRecording = await _mediaCapture.PrepareLowLagRecordToStorageFileAsync(recordProfile,file);
await _mediaRecording.StartAsync();
status.Text = "Video recording in progress...";
}
catch (Exception ex)
{
status.Text = "Failed to Capture...";
var msg = new MessageDialog(ex.Message, "Capturing Error").ShowAsync();
}
Please help me in figuring out the problem. Thanks

You forgot to call MediaCapture.InitializeAsync() before starting the capture.
MediaEncodingProfile recordProfile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto);
_mediaCapture = new MediaCapture();
_mediaCapture.InitializeAsync();
_mediaRecording = await _mediaCapture.PrepareLowLagRecordToStorageFileAsync(recordProfile,file);
await _mediaRecording.StartAsync();

Related

Xamarin computer vision

I am trying to create a Xamarin application using Azure computer vision API, I got the API key and endpoint URL whenever i click a picture and set in image view and then describe image function not working and i am not getting output captions, my code is below:
private async void Button_Clicked(object sender, EventArgs e)
{
await CrossMedia.Current.Initialize();
try
{
if(!CrossMedia.Current.IsTakePhotoSupported&&!CrossMedia.Current.IsPickPhotoSupported)
{
await DisplayAlert("INFO", "CAMERA NOT AVAILABEL", "OK");
}
else
{
var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
{
Directory="Images",
Name="test.jpg"
});
if (file==null)
{
await DisplayAlert("ERROR", "FILE NOT FOUND", "OK");
return;
}
img.Source = ImageSource.FromStream(() =>
{
var stream = file.GetStream();
return stream;
});
var visionapi = new ComputerVisionClient(new ApiKeyServiceClientCredentials(""));
visionapi.Endpoint = "";
var desc = await visionapi.DescribeImageInStreamAsync(file.GetStream());
foreach (var tag in desc.Captions)
{
cap.Text = cap.Text + "\n" + tag;
}
}
}
catch(Exception )
{
await DisplayAlert("", "ERROR", "OK");
}
}
DescribeImageInStreamAsync functon is not working it is moving into catch block after few minutes with the below error:
Microsoft.Azure.CognitiveServices.Vision.ComputerVisionErrororException: Operation returned an invalid status code 'Not Found'
Exception

How to open and auto capture camera using MediaCapture class

we are trying to automatically capture an image from the webcam using MediaCapture class. We are trying to create an application which opens the camera, waits for a moment and captures the image in front of it without someone to tap the screen to capture. we tried using LowLagPhotoCapture class but does not work as desired. Sample code -
async private void InitMediaCapture()
{
MediaCapture _mediaCapture = new MediaCapture();
await _mediaCapture.InitializeAsync();
_displayRequest.RequestActive();
PreviewControlCheckIn.Source = _mediaCapture;
await _mediaCapture.StartPreviewAsync();
await Task.delay(500);
CaptureImage();
}
async private void CaptureImage()
{
storeFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync ("TestPhoto.jpg",CreationCollisionOption.GenerateUniqueName);
ImageEncodingProperties imgFormat = ImageEncodingProperties.CreateJpeg();
await _mediaCapture.CapturePhotoToStorageFileAsync(imgFormat, storeFile);
await _mediaCapture.StopPreviewAsync();
}
Any info would be great, thanks in advance for the help.
I have completed your provided code and achieved your requirement. Please refer to the following code. Please note that you should declare camera and the microphone capabilities in your Universal Windows Platform (UWP) app's package manifest to access certain API.
async private void InitMediaCapture()
{
_mediaCapture = new MediaCapture();
var cameraDevice = await FindCameraDeviceByPanelAsync(Windows.Devices.Enumeration.Panel.Back);
var settings = new MediaCaptureInitializationSettings { VideoDeviceId = cameraDevice.Id };
await _mediaCapture.InitializeAsync(settings);
_displayRequest.RequestActive();
PreviewControl.Source = _mediaCapture;
await _mediaCapture.StartPreviewAsync();
var picturesLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures);
_captureFolder = picturesLibrary.SaveFolder ?? ApplicationData.Current.LocalFolder;
await Task.Delay(500);
CaptureImage();
}
async private void CaptureImage()
{
var storeFile = await _captureFolder.CreateFileAsync("PreviewFrame.jpg", CreationCollisionOption.GenerateUniqueName);
ImageEncodingProperties imgFormat = ImageEncodingProperties.CreateJpeg();
await _mediaCapture.CapturePhotoToStorageFileAsync(imgFormat, storeFile);
await _mediaCapture.StopPreviewAsync();
}
private static async Task<DeviceInformation> FindCameraDeviceByPanelAsync(Windows.Devices.Enumeration.Panel desiredPanel)
{
// Get available devices for capturing pictures
var allVideoDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
// Get the desired camera by panel
DeviceInformation desiredDevice = allVideoDevices.FirstOrDefault(x => x.EnclosureLocation != null && x.EnclosureLocation.Panel == desiredPanel);
// If there is no device mounted on the desired panel, return the first device found
return desiredDevice ?? allVideoDevices.FirstOrDefault();
}
The photo will be saved to Pictures library. And I have upload the code sample to github. Please check!

Download txt file from google drive in windows phone 8.1

I'm doing a windows phone project, and need to download a text file from the internet and read its content.
This is what I have tried (but it didn't work)
private async Task pobierz()
{
string source = "https://drive.google.com/file/d/0BzgKBwKyU4oORkxxSlVITGswb1E/view?usp=sharing";
string LocalName = "hej.txt";
var srce = new Uri(source, UriKind.Absolute);
// var destinationFile =await KnownFolders.PicturesLibrary.CreateFileAsync()
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri(#"ms-appx:///Assets/hej.txt"));
var downloader = new BackgroundDownloader();
DownloadOperation download = downloader.CreateDownload(srce,file);
}
Please see https://msdn.microsoft.com/en-us/library/windows/apps/xaml/jj152726.aspx?f=255&MSPPError=-2147217396 for detailed description of how to use the BackgroundDownloader.
You need to implement and call the following method:
private async void HandleDownloadAsync(DownloadOperation download, bool start)
{
try
{
// Store the download so we can pause/resume.
activeDownloads.Add(download);
Progress<DownloadOperation> progressCallback = new Progress<DownloadOperation>(DownloadProgress);
if (start)
{
// Start the download and attach a progress handler.
await download.StartAsync().AsTask(cts.Token, progressCallback);
}
else
{
// The download was already running when the application started, re-attach the progress handler.
await download.AttachAsync().AsTask(cts.Token, progressCallback);
}
ResponseInformation response = download.GetResponseInformation();
Log(String.Format("Completed: {0}, Status Code: {1}", download.Guid, response.StatusCode));
}
catch (TaskCanceledException)
{
Log("Download cancelled.");
}
catch (Exception ex)
{
LogException("Error", ex);
}
finally
{
activeDownloads.Remove(download);
}
}

Try to add custom tile to Microsoft Band from UWP app

I want to add a custom tile to the Microsoft Band through Microsoft Band SDK in a UWP app for Windows Phone. Here is my sample code.
private async void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
try
{
// Get the list of Microsoft Bands paired to the phone.
var pairedBands = await BandClientManager.Instance.GetBandsAsync();
if (pairedBands.Length < 1)
{
Debug.WriteLine("This sample app requires a Microsoft Band paired to your device.Also make sure that you have the latest firmware installed on your Band, as provided by the latest Microsoft Health app.");
return;
}
// Connect to Microsoft Band.
using (var bandClient = await BandClientManager.Instance.ConnectAsync(pairedBands[0]))
{
// Create a Tile with a TextButton on it.
var myTileId = new Guid("12408A60-13EB-46C2-9D24-F14BF6A033C6");
var myTile = new BandTile(myTileId)
{
Name = "My Tile",
TileIcon = await LoadIcon("ms-appx:///Assets/SampleTileIconLarge.png"),
SmallIcon = await LoadIcon("ms-appx:///Assets/SampleTileIconSmall.png")
};
// Remove the Tile from the Band, if present. An application won't need to do this everytime it runs.
// But in case you modify this sample code and run it again, let's make sure to start fresh.
await bandClient.TileManager.RemoveTileAsync(myTileId);
// Create the Tile on the Band.
await bandClient.TileManager.AddTileAsync(myTile);
// Subscribe to Tile events.
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
private async Task<BandIcon> LoadIcon(string uri)
{
StorageFile imageFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri(uri));
using (IRandomAccessStream fileStream = await imageFile.OpenAsync(FileAccessMode.Read))
{
WriteableBitmap bitmap = new WriteableBitmap(1, 1);
await bitmap.SetSourceAsync(fileStream);
return bitmap.ToBandIcon();
}
}
If I run this code nothing happend. The app connected to Microsoft Band, but is not able to add a tile. The method AddTileAsync(myTile); Returns false and doesn't add a tile to the Microsoft Band.
If I try this code in a Windows Phone 8.1 app it works, but not in the UWP app.
Any ideas?
Update
Here is the sample app as download. Maybe this can help.
maybe this would help, coming from the documentation of MS Band
using Microsoft.Band.Tiles;
...
try
{
IEnumerable<BandTile> tiles = await bandClient.TileManager.GetTilesAsync();
}
catch (BandException ex)
{
//handle exception
}
//determine if there is space for tile
try
{
int tileCapacity = await bandClient.TileManager.GetRemainingTileCapacityAsync();
}
catch (BandException ex)
{
//handle ex
}
//create tile
WriteAbleBitmap smallIconBit = new WriteAbleBitmap(24, 24);
BandIcon smallIcon = smallIconBit.ToBandIcon();
WriteAbleBitmap largeIconBit = new WriteAbleBitmap(48, 48);//46, 46 for MS band 1
BandIcon largeIcon = largeIconBit.ToBandIcon();
Guid guid = Guid.NewGuid();
BandTile tile = new BandTile(guid)
{
//enable Badging
IsBadgingEnabled = true,
Name = "MYNAME"
SmallIcon = smallIcon;
TileIcon = largeIcon;
};
try
{
if(await bandClient.TileManager.AddTileAsync(tile))
{
///console print something
}
}
catch(BandException ex)
{
//blabla handle
}
I think the issue may be you're setting the writeable bitmap size to (1,1)?
I have this method working:
public static class BandIconUtil
{
public static async Task<BandIcon> FromAssetAsync(string iconFileName, int size = 24)
{
string uri = "ms-appx:///" + iconFileName;
StorageFile imageFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri(uri, UriKind.RelativeOrAbsolute));
using (IRandomAccessStream fileStream = await imageFile.OpenAsync(FileAccessMode.Read))
{
WriteableBitmap bitmap = new WriteableBitmap(size, size);
await bitmap.SetSourceAsync(fileStream);
return bitmap.ToBandIcon();
}
}
}

OneDrive file only uploads when app is terminated

I'm having a problem uploading a file to OneDrive from a universal app that I can't understand or figure out how to debug. I used this guide to go through the process of getting file IDs and such and it worked great until a few hours ago.
Now I can get folder and file ids, so I assume that I am still successfully connecting to OneDrive and my internet connection is still working. But when I step into the BackgroundUploadAsync the thread or whatever that was was executing before never returns. In the code below, the message "Uploading new file to OneDrive..." never disappears.
Strangely, while it is uploading I can refresh my OneDrive folder on ie and I'll never see what I'm trying to upload. But once I stop the debugger, or terminate the app on the phone, I can instantly refresh and the file will be there.
Here is the method for uploading:
public async Task UploadToOneDrive(string folderID, string localFileName)
{
try
{
StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(localFileName);
string fileName = "backup-" + DateTime.Now.ToString("dd-MM") + ".db";
await file.CopyAsync(ApplicationData.Current.LocalFolder, fileName, NameCollisionOption.ReplaceExisting);
file = await ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
await connectClient.BackgroundUploadAsync(folderID,
fileName, file, OverwriteOption.Overwrite);
}
catch (LiveConnectException)
{
MessageDialog m = new MessageDialog("Could not connect to to OneDrive. Cloud sync will be stopped.");
m.ShowAsync();
}
catch (LiveAuthException)
{
MessageDialog m = new MessageDialog("Error authenticating OneDrive service. Please try cloud sync again later.");
m.ShowAsync();
}
catch (Exception ex)
{
MessageDialog m = new MessageDialog("Unknown exception occurred.\n\nError:{0}", ex.Message);
m.ShowAsync();
}
}
And here is the sync process
public async Task sync()
{
var sb = StatusBar.GetForCurrentView();
sb.ProgressIndicator.Text = "Syncing with OneDrive...";
await sb.ProgressIndicator.ShowAsync();
string cloudFolderID = await syncManager.CreateOrGetOneDriveFolderID("GlucoseCalculator", "Documents/");
string cloudFileID = await syncManager.GetFileID(DataManager.sqlFileName, "Documents/GlucoseCalculator/");
try
{
if (cloudFileID != null)
{
if (!(await dbManager.DoesFileExist(DataManager.sqlFileName)))
{
sb.ProgressIndicator.Text = "Downloading file from OneDrive...";
await syncManager.DownloadFromOneDrive(cloudFileID, DataManager.sqlFileName);
goto BREAK;
}
DateTime cloudLastEditDateTime = DateTime.Parse(await syncManager.GetFileProperty(cloudFileID, "updated_time"));
DateTime localLastEditDateTime = ApplicationData.Current.LocalFolder.GetFileAsync(DataManager.sqlFileName).GetResults().GetBasicPropertiesAsync().GetResults().DateModified.DateTime;
if (cloudLastEditDateTime > localLastEditDateTime)
{
sb.ProgressIndicator.Text = "Downloading file from OneDrive...";
await syncManager.DownloadFromOneDrive(cloudFileID, DataManager.sqlFileName);
}
else if (cloudLastEditDateTime < localLastEditDateTime)
{
sb.ProgressIndicator.Text = "Uploading file to OneDrive...";
await syncManager.UploadToOneDrive(cloudFolderID, DataManager.sqlFileName);
}
}
else if (cloudFileID == null)
{
sb.ProgressIndicator.Text = "Uploading new file to OneDrive...";
await syncManager.UploadToOneDrive(cloudFolderID, DataManager.sqlFileName);
}
}
catch (Exception)
{
sb.ProgressIndicator.Text = "Cloud synchronization failed.";
sb.ProgressIndicator.HideAsync();
return;
}
sb.ProgressIndicator.Text = "Synchronization complete!";
BREAK:;
await sb.ProgressIndicator.HideAsync();
}
Most likely, you are creating some object that implements IDisposible, but it is not in a using block. Maybe the StorageFile.

Categories