I am working in UWP and trying to make the following tutorial example work. In summary i am trying to get a frame from a MediaCapture and display it to an Image UWP Control element.
var previewProperties = _mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview) as VideoEncodingProperties;
VideoFrame videoFrame = new VideoFrame(BitmapPixelFormat.Bgra8, (int)previewProperties.Width, (int)previewProperties.Height);
var source = new SoftwareBitmapSource();
var previewFrame = await _mediaCapture.GetPreviewFrameAsync(videoFrame);
SoftwareBitmap previewBitmap = videoFrame.SoftwareBitmap;
await source.SetBitmapAsync(previewBitmap);
img.Source = source;
When the GetPreviewFrameASync function is execute i get a runtime exception reffering Invalid parameter type. Have anyone experiencing the same problem before and what was the cause of it?
Thanks in advance
Turns out there was absolutely no problem with my code,but somehow the CAMERA was to blame for the error. Many others that ran my project had no issues and when I changed my camera everything was fine.If you are unlucky enough to experience the same problem try running it with another cam.
I have tested your segment code and reproduced your issue, the problem is you have not started previewing before GetPreviewFrameASync method executed. The following is the method of starting to preview.
private async Task StartPreviewAsync()
{
try
{
_mediaCapture = new MediaCapture();
await _mediaCapture.InitializeAsync();
_displayRequest.RequestActive();
DisplayInformation.AutoRotationPreferences = DisplayOrientations.Landscape;
}
catch (UnauthorizedAccessException)
{
}
try
{
PreviewControl.Source = _mediaCapture;
await _mediaCapture.StartPreviewAsync();
_isPreviewing = true;
}
catch (System.IO.FileLoadException)
{
}
}
For more please refer to Basic photo, video, and audio capture with MediaCapture. I have upload code sample to github. Please check!
Related
I'm trying to develop a UWP application that will speak text to the user via a Windows.Media.Playback.MediaPlayer. I have this code that currently works:
private async Task Speak(string text)
{
var audio = await _Speech.SynthesizeTextToStreamAsync(text);
player.SetStreamSource(audio);
player.Play();
}
However, this causes a compiler warning: 'MediaPlayer.SetStreamSource(IRandomAccessStream)' is obsolete: 'Use Source instead of SetStreamSource. For more info, see MSDN.
However, I can't find on MSDN how to convert the SpeechSynthesisStream that SynthesizeTextToStreamAsync generates to a IMediaPlaybackSource that the MediaPlayer wants. The Windows.Media.Core.MediaStreamSource class looks promising, but it wants a IMediaStreamDescriptor which I have no idea how to get...
How do I replicate the functionality of this simple three-liner without using deprecated methods?
you can use the MediaSource.CreateFromStream() method for this purpose.
private async Task Speak(string text)
{
var audio = await _Speech.SynthesizeTextToStreamAsync(text);
player.Source = MediaSource.CreateFromStream(audio);
player.Play();
}
SynthesizeTextToStreamAsync returns a SpeechSynthesisStream object that you can use. This example from the MSDN documentation should lead you in the right direction
SpeechSynthesisStream stream = await synth.SynthesizeTextToStreamAsync("Hello World");
mediaElement.SetSource(stream, stream.ContentType);
https://learn.microsoft.com/en-us/uwp/api/windows.media.speechsynthesis.speechsynthesizer
I am working on a Xamarin Cross Platform App and I have a problem when I try to obtain my gps coords. I have this code to get the gps information:
protected async override void OnAppearing()
{
position = await GetPosition();
map.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(position.Latitude, position.Longitude), Distance.FromMiles(0.3)));
}
async Task<Plugin.Geolocator.Abstractions.Position> GetPosition()
{
var locator = CrossGeolocator.Current;
locator.DesiredAccuracy = 50;
Plugin.Geolocator.Abstractions.Position position = await locator.GetPositionAsync(TimeSpan.FromSeconds(5));
return position;
}
When it reaches the line:
Plugin.Geolocator.Abstractions.Position position = await locator.GetPositionAsync(TimeSpan.FromSeconds(5));
It gives me this exception:
Java.Lang.ClassNotFoundException: Didn't find class
"md57251f317a80041e1a60080af127573bd.GeolocationSingleListener" on
path: DexPathList[[zip file
"/data/app/com.companyname.PruebaMapas-1/base.apk"],nativeLibraryDirectories=[/data/app/com.companyname.PruebaMapas-1/lib/x86,
/system/fake-libs,
/data/app/com.companyname.PruebaMapas-1/base.apk!/lib/x86,
/system/lib, /vendor/lib]]
I don't know why. I add the "Plugin.Geolocator" using NuGet and it is on my PruebaMapas project and on my PruebaMapas.Android project too.
Can anyone help me? Thanks a lot!
Did your application works without using GeoPlugin ? If not it can be similar to this so u can try this solution. This is known issue in Xamarin android 8.1.
I'm using ZXing.Net.Mobile and have the following code to scan the QR code.
await scanner.Scan().ContinueWith(t =>
{
if (t.Result != null)
HandleScanResult(t.Result);
});
scanner.UseCustomOverlay = false;
scanner.ScanContinuously(async (res) =>
{
var msg = "Found Barcode: " + res.Text;
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
{
ViewHelper.showMessage(msg, "");
});
});
I've tried both ContinueWith and ScanContinuosly but none of them work.
I get a camera view with red line but it does not scan the QR code.
Where am I going wrong.
I suppose you're using the ZXing.NET package?
Mike Taulty wrote a whole blog post series on an app with Scanning on Windows 8.1, then porting it to Windows 10 and even running it on HoloLens. The final post also has a small companion app that runs on UWP for simple scanning (with speech to command the app to scan).
In that sample, he's using following method:
ZXingQrCodeScanner.ScanFirstCameraForQrCode(
result =>
{
this.txtResult.Text = result?.Text ?? "none";
},
TimeSpan.FromSeconds(30));
There’s an assumption that the first camera found on the system should be used for QR code scanning but the classes that underpin this would allow for taking a more flexible approach and that ScanFirstCameraForQrCode function expands out into the following steps below
public static class ZXingQrCodeScanner
{
public static async void ScanFirstCameraForQrCode(
Action<Result> resultCallback,
TimeSpan timeout)
{
Result result = null;
var mediaFrameSourceFinder = new MediaFrameSourceFinder();
// We want a source of media frame groups which contains a color video
// preview (and we'll take the first one).
var populated = await mediaFrameSourceFinder.PopulateAsync(
MediaFrameSourceFinder.ColorVideoPreviewFilter,
MediaFrameSourceFinder.FirstOrDefault);
if (populated)
{
// We'll take the first video capture device.
var videoCaptureDevice =
await VideoCaptureDeviceFinder.FindFirstOrDefaultAsync();
if (videoCaptureDevice != null)
{
// Make a processor which will pull frames from the camera and run
// ZXing over them to look for QR codes.
var frameProcessor = new QrCaptureFrameProcessor(
mediaFrameSourceFinder,
videoCaptureDevice,
MediaEncodingSubtypes.Bgra8);
// Remember to ask for auto-focus on the video capture device.
frameProcessor.SetVideoDeviceControllerInitialiser(
vd => vd.Focus.TrySetAuto(true));
// Process frames for up to 30 seconds to see if we get any QR codes...
await frameProcessor.ProcessFramesAsync(timeout);
// See what result we got.
result = frameProcessor.QrZxingResult;
}
}
// Call back with whatever result we got.
resultCallback(result);
}
}
Source:
Mike Taulty's blog post
Sample app on GitHub
I hope this approach helps you forward.
You can try my ready solution:
Barcode_Scanner_UWP on GitHub
I'v tried to make adoption of VideoScanZXingWinRT repo
Both of them are using ZXing.Net
But in compare with old Mike Taulty sample could catch QR "on the fly"
When retrieving the VideoProperties of a freshly created MediaCapture file, I am finding that frequently the properties are not set, i.e. all zero. To illustrate I've updated the CameraStarterKit sample in the Windows universal samples zip:
private async Task StopRecordingAsync()
{
Debug.WriteLine("Stopping recording...");
_isRecording = false;
await _mediaCapture.StopRecordAsync();
var videoproperties = await videoFile.Properties.GetVideoPropertiesAsync();
// This Assert will fail most of the time but not always
System.Diagnostics.Debug.Assert(videoproperties.Duration != TimeSpan.Zero);
Debug.WriteLine("Stopped recording!");
}
I'm not receiving any errors, just bad data. Viewing the file properties in File Explorer always shows the expected result. What am I doing wrong?
It has been 4 years since this question has been answered with this blog post.
Is there a standard way to create a UIImage with an image from a URL? Something like:
UIImage image = UIImage.FromFile("http://foo.com/bar.jpg");
I feel like I'm probably missing something really simple.
Not a one-liner, but with very few lines you can roll your own. E.g.
static UIImage FromUrl (string uri)
{
using (var url = new NSUrl (uri))
using (var data = NSData.FromUrl (url))
return UIImage.LoadFromData (data);
}
The calls, including the one from UIImage, are thread-safe.
With new await/async support you can do:
public async Task<UIImage> LoadImage (string imageUrl)
{
var httpClient = new HttpClient();
Task<byte[]> contentsTask = httpClient.GetByteArrayAsync (imageUrl);
// await! control returns to the caller and the task continues to run on another thread
var contents = await contentsTask;
// load from bytes
return UIImage.LoadFromData (NSData.FromArray (contents));
}
and you call this with:
someYourUIImageObjectOnUI.Image = await this.LoadImage ("some image url");
You want to be sure that you load the image async so that you do not block your UI thread. MonoTouch.Dialog includes an ImageLoader (see sec 5.3) class that you could use.
There are also a couple of variations of UrlImageStore out there to help with async loading images.
Finally, if you want to do it manually, there is a Xamarin Recipe you can use.
I tried the above, it looks like a great idea, but I get:
Cannot implicitly convert type System.Threading.Tasks.Task<MonoTouch.UIKit.UIImage>' toMonotouch.UIKit.UIImage'
[found a solution]
The problem was because the
obj.Image = await this.LoadImage (imageUrl)
must also be in a method marked async.
Then it works!
Thanks
Below code should work,
public static async Task<UIImage> LoadImage(string imageUrl)
{
var httpClient = new HttpClient();
var contents = await httpClient.GetByteArrayAsync(imageUrl);
return UIImage.LoadFromData(NSData.FromArray(contents));
}