Mati
Mati

Reputation: 33

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

Upvotes: 0

Views: 2668

Answers (1)

Tom Aaron
Tom Aaron

Reputation: 21

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

Upvotes: 2

Related Questions