Can anyone say how to toggle flashlight in Windows Phone 8.1 using C#? It seems like there are lots of API changes in Windows Phone 8.1 and most of the API's in WP 8.0 are not supported. Answers are highly appreciated.
I'm able to use TorchControl on my Lumia 820 like this - first you have to specify which camera you will use - the default is front (I think that's why you may find some problems) and we want the back one - the one with flash light. Sample code:
// edit - I forgot to show GetCameraID:
private static async Task<DeviceInformation> GetCameraID(Windows.Devices.Enumeration.Panel desiredCamera)
{
DeviceInformation deviceID = (await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture))
.FirstOrDefault(x => x.EnclosureLocation != null && x.EnclosureLocation.Panel == desiredCamera);
if (deviceID != null) return deviceID;
else throw new Exception(string.Format("Camera of type {0} doesn't exist.", desiredCamera));
}
// init camera
async private void InitCameraBtn_Click(object sender, RoutedEventArgs e)
{
var cameraID = await GetCameraID(Windows.Devices.Enumeration.Panel.Back);
captureManager = new MediaCapture();
await captureManager.InitializeAsync(new MediaCaptureInitializationSettings
{
StreamingCaptureMode = StreamingCaptureMode.Video,
PhotoCaptureSource = PhotoCaptureSource.VideoPreview,
AudioDeviceId = string.Empty,
VideoDeviceId = cameraID.Id
});
}
// then to turn on/off camera
var torch = captureManager.VideoDeviceController.TorchControl;
if (torch.Supported) torch.Enabled = true;
// turn off
if (torch.Supported) torch.Enabled = false;
Note that it's a good idea to call captureManager.Dispose() after you finish with it.
Note also that on some phones to turn on torch/flashlight you will need to start preview first.
Windows Phone 8.1 is the first version with a dedicated API for controlling the camera light. This API stems from Windows 8.1 but is usable in Windows Phone 8.1 projects and in Windows Phone Silverlight 8.1 projects.
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;
}
Note:
Note: TorchControl.Supported returns false on most phones in WP8.1 developer preview. It is expected to be fixed by a firmware update by the time WP 8.1 is released. Tested Phones at the time of writing: Lumia 620, 822, 1020: not working, Lumia 1520: working.
In Nokia Lumia 1520, you use FlashControl to toggle the flash light instead of TorchControl.
//to switch OFF flash light
mediacapture.VideoDeviceController.FlashControl.Enabled = false;
//to switch ON flash light
mediacapture.VideoDeviceController.FlashControl.Enabled = true;
Doesn't work on my Lumia 1520. You need to start video recording to get flashlight working:
var videoEncodingProperties = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Vga);
var videoStorageFile = await KnownFolders.VideosLibrary.CreateFileAsync("tempVideo.mp4", CreationCollisionOption.GenerateUniqueName);
await captureManager.StartRecordToStorageFileAsync(videoEncodingProperties, videoStorageFile);
In my Lumia 1520. I need to start video recording and start preview to get flashlight working:
await captureManager.StartPreviewAsync();
Related
I'm trying to play the built-in webcam feed in a MediaElement within a UWP app. It works fine for a few users but there is no feed played for most and I'm lost on what could be the issue.
Some observations when the webcam feed doesn't play:
The code executes without any exceptions
The dialog that requests user permission to access the camera is shown
The LED indicating the webcam is in use turns on soon as it is executed, but there is no feed.
Skype and Camera apps work fine.
The app was working as expected until a week back. A few things that changed in the mean time that could have had an impact are
Installed Kaspersky
A bunch of windows updates
Uninstalled VS2017 professional edition & VS2019 Community edition and installed VS2019 Professional Edition
Some additional information that might be needed to narrow down the reason.
Webcam is enabled in the Package manifest of the app
App Target version: 18362
App Min version: 18362
Windows OS Version : 18362
Any help on this would be highly appreciated. Thanks much in advance!
Here is the piece of code used to play the webcam feed where VideoStreamer is a MediaElement.
private async Task PlayLiveVideo()
{
var allGroups = await MediaFrameSourceGroup.FindAllAsync();
var eligibleGroups = allGroups.Select(g => new
{
Group = g,
// For each source kind, find the source which offers that kind of media frame,
// or null if there is no such source.
SourceInfos = new MediaFrameSourceInfo[]
{
g.SourceInfos.FirstOrDefault(info => info.DeviceInformation?.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Front
&& info.SourceKind == MediaFrameSourceKind.Color),
g.SourceInfos.FirstOrDefault(info => info.DeviceInformation?.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back
&& info.SourceKind == MediaFrameSourceKind.Color)
}
}).Where(g => g.SourceInfos.Any(info => info != null)).ToList();
if (eligibleGroups.Count == 0)
{
System.Diagnostics.Debug.WriteLine("No source group with front and back-facing camera found.");
return;
}
var selectedGroupIndex = 0; // Select the first eligible group
MediaFrameSourceGroup selectedGroup = eligibleGroups[selectedGroupIndex].Group;
MediaFrameSourceInfo frontSourceInfo = selectedGroup.SourceInfos[0];
MediaCapture mediaCapture = new MediaCapture();
MediaCaptureInitializationSettings settings = new MediaCaptureInitializationSettings()
{
SourceGroup = selectedGroup,
SharingMode = MediaCaptureSharingMode.ExclusiveControl,
MemoryPreference = MediaCaptureMemoryPreference.Cpu,
StreamingCaptureMode = StreamingCaptureMode.Video,
};
try
{
await mediaCapture.InitializeAsync(settings);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("MediaCapture initialization failed: " + ex.Message);
return;
}
var frameMediaSource1 = MediaSource.CreateFromMediaFrameSource(mediaCapture.FrameSources[frontSourceInfo.Id]);
VideoStreamer.SetPlaybackSource(frameMediaSource1);
VideoStreamer.Play();
}
As mentioned by Faywang-MSFT here , it worked after marking the application as trusted in Kaspersky.
My issue is quite simple.
I want to turn the flash On (and keep it On) on a Windows 10 universal app project but nothing I try works.
This is the code
MediaCapture MyMediaCapture = new MediaCapture();
var allVideoDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
DeviceInformation cameraDevice =
allVideoDevices.FirstOrDefault(x => x.EnclosureLocation != null &&
x.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back);
cameraDevice = cameraDevice ?? allVideoDevices.FirstOrDefault();
if (cameraDevice == null)
{
Debug.WriteLine("No camera device found!");
}
else
{
await MyMediaCapture.InitializeAsync(new MediaCaptureInitializationSettings
{
VideoDeviceId = cameraDevice.Id
});
var MyVideoDeviceController = MyMediaCapture.VideoDeviceController;
var MyTorch = MyVideoDeviceController.TorchControl;
if (MyTorch.Supported)
{
var captureElement = new CaptureElement();
captureElement.Source = MyMediaCapture;
await MyMediaCapture.StartPreviewAsync();
FileStream tmp = new FileStream(System.IO.Path.GetTempFileName() + Guid.NewGuid().ToString() + ".mp4", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None, 10000, FileOptions.RandomAccess | FileOptions.DeleteOnClose);
var videoFile = await KnownFolders.VideosLibrary.CreateFileAsync(tmp.Name, CreationCollisionOption.GenerateUniqueName);
var encodingProfile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Wvga);
await MyMediaCapture.StartRecordToStorageFileAsync(encodingProfile, videoFile);
MyTorch.PowerPercent = 100;
MyTorch.Enabled = true;
}
}
Edit: add code
It looks like you're trying to use an old method of accessing the flashlight which we no longer have to use in Windows 10 UWP development. Take a look at the new Lamp feature in Windows.Devices.Lights in this sample on GitHub.
It's a great starting point for using the flash independent of access the camera APIs.
You're on the right path. Depending on the device (because of driver-specific implementations), you'll have to start the preview or maybe even start a video recording session for the light to turn on.
Because of that, and to guarantee compatibility with most devices, I'd recommend you actually do both.
I am trying to create a simple application which will have the functionality to switch on and off the flash light in a Windows Media Device.
I have initialized the camera as following:
var devices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
var rearCamera = devices.FirstOrDefault(item => item.EnclosureLocation != null &&
item.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back);
if (rearCamera != null)
{
DeviceName.Content = rearCamera.Name;
FlashButton.Visibility = System.Windows.Visibility.Visible;
mediaCapture = new MediaCapture();
await mediaCapture.InitializeAsync(new MediaCaptureInitializationSettings
{
VideoDeviceId = rearCamera.Id
});
LowLagPhotoCapture lowLagCaptureMgr = null;
// Image properties
ImageEncodingProperties imgFormat = ImageEncodingProperties.CreateJpeg();
// Create LowLagPhotoCapture object
lowLagCaptureMgr = await mediaCapture.PrepareLowLagPhotoCaptureAsync(imgFormat);
}
And to switch on the flash I have written the following code:
var MyVideoDeviceController = mediaCapture.VideoDeviceController;
var MyTorch = MyVideoDeviceController.TorchControl;
var MyFlash = MyVideoDeviceController.FlashControl;
if (MyTorch.Supported)
{
MyTorch.PowerPercent = 100;
MyTorch.Enabled = true;
}
else
{
if (MyFlash.Supported)
{
MyFlash.PowerPercent = 100;
MyFlash.Enabled = true;
}
else
{
MessageBox.Show("No Flash and Torch Support", "Flash and Torch");
}
}
But seems both TorchControl and FlashControl are not supported in the code. I am not sure if am using the right APIs too. I am trying to run this on a Motion F5m - Tablet PC
Thanks in advance
The TorchControl is used for constant video light, so if you're taking a photograph, it's not the most appropriate control to use. One reason is that on many devices, video light will be dimmer than a photo flash, but especially because on some devices, the torch will only turn on while a video recording is in progress. Depending on the capabilities of the device, this may interfere with the ability to take photos.
You have the right idea setting MyFlash.Enabled = true, but just to be safe, I would also set MyFlash.Auto = false, so that the flash will fire each time, and not only when it's dark.
The CameraManualControls sample on the Microsoft GitHub repository shows you how to use the Flash and Torch controls, and many more. It targets Windows 10, though, so if you're on 8.1 you'll have to adapt the code or upgrade your tablet.
Now, all of the above is assuming that the device you're running your app on has flash support in the first place. When you say that the controls are not supported, that means that the camera driver on the device is not advertising the capability to Windows. I assume that the built-in Microsoft Camera app doesn't allow you to use the flash either?
I see the manufacturer of your tablet lists an "Illuminator Light" on their camera specs list, but there is a chance that the only way to control it is through their proprietary application. In that case you'd have to reach out to them for support.
I have developed windows 8.1 store app, it need to be capture photo by using back camera and post.
MediaCaptureInitializationSettings _captureSettings = new var devices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
foreach (var device in devices)
{
if (device.EnclosureLocation != null && device.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back)
{
deviceId = device.Id;
break;
}
}
if (!string.IsNullOrEmpty(deviceId))
{
_captureSettings.AudioDeviceId = "";
_captureSettings.VideoDeviceId = deviceId;
_captureSettings.PhotoCaptureSource = Windows.Media.Capture.PhotoCaptureSource.Photo;
_captureSettings.StreamingCaptureMode = Windows.Media.Capture.StreamingCaptureMode.Video;
}
captureManager = new MediaCapture();
await captureManager.InitializeAsync(_captureSettings);
await captureManager.ClearEffectsAsync(MediaStreamType.Photo);
capturePreview1.Source = captureManager;
await captureManager.StartPreviewAsync();
</code>
Here i am getting two devices but that devices EnclosureLocation is null, so i can't find which one is front and back camera.
so have decided to get second device from list
<code>
deviceId = devices[1].Id;
</code>
but it throws an error like "The current capture source does not have an independent photo stream."
in the line of initializing MediaCapture
<code>
await captureManager.InitializeAsync(_captureSettings);
</code>
i have tried in windows surface pro 2 and acer devices.
Please advise. Thanks in advance.
Try to organise your code better, you got two equals signs on the same line and your code is not well formated so it's hard to read.
To use Camera in Windows 8.1 stop app I use this code :
// First need to find all webcams
DeviceInformationCollection webcamList = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture)
// Then I do a query to find the front webcam
DeviceInformation frontWebcam = (from webcam in webcamList
where webcam.EnclosureLocation != null
&& webcam.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Front
select webcam).FirstOrDefault();
// Same for the back webcam
DeviceInformation backWebcam = (from webcam in webcamList
where webcam.EnclosureLocation != null
&& webcam.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back
select webcam).FirstOrDefault();
// Then you need to initialize your MediaCapture
var captureManager = new MediaCapture();
await captureManager.InitializeAsync(new MediaCaptureInitializationSettings
{
// Choose the webcam you want (backWebcam or frontWebcam)
VideoDeviceId = backWebcam.Id,
AudioDeviceId = "",
StreamingCaptureMode = StreamingCaptureMode.Video,
PhotoCaptureSource = PhotoCaptureSource.VideoPreview
});
// Set the source of the CaptureElement to your MediaCapture
capturePreview1.Source = captureManager;
// Start the preview
await captureManager.StartPreviewAsync();
This way it's easier to read. The code is not very different, MediaCaptureInitializationSettings is not the same.
This code works for me on Surface 2 RT and Nokia 635 so it should work for you.
Edit:
Seems it works on devices with Windows RT but on full windows 8.1 devices it's always null.
Msdn says that:
If no enclosure location information is available, the property will
be null
so what you can do is first try to see if you find a backwebcam and if it's null take the last one;
DeviceInformation backWebcam = (from webcam in webcamList
where webcam.EnclosureLocation != null
&& webcam.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back
select webcam).FirstOrDefault();
if (backWebcam == null)
{
backWebcam = webcamList.Last();
}
But you are not sure the last one in the collection is the back one, so you should add a button to let the user switch camera
If you change camera,
await captureManager.StopPreviewAsync();
await captureManager.InitializeAsync(new MediaCaptureInitializationSettings
{
// Choose an other webcam
VideoDeviceId = //id of the new webcam,
AudioDeviceId = "",
StreamingCaptureMode = StreamingCaptureMode.Video,
PhotoCaptureSource = PhotoCaptureSource.VideoPreview
});
await captureManager.StartPreviewAsync();
this way you can be sure the user can choose the right camera even is you programmaticaly cannot tell which one is which
I try to use camera in WP 8.1 universal app. But app crash.
I try di this:
private MediaCapture mediaCaptureMgr = null;
async void ShowPreview()
{
if (mediaCaptureMgr == null)
{
mediaCaptureMgr = new MediaCapture();
await mediaCaptureMgr.InitializeAsync();
myCaptureElement.Source = mediaCaptureMgr;
await mediaCaptureMgr.StartPreviewAsync();
}
}
and I try this example:
http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh868171.aspx
but both crash app when I initialize MediaCapture
await mediaCaptureMgr.InitializeAsync();
VS output windows show me message
WinRT information: The text associated with this error code could not be found.
Can anybody help?