【WP8】WP8调用官方API使用LED灯

时间:2022-03-27 15:20:55

在WP7中没有相关的API可以直接使用摄像头的LED等,只能通过录像时打开LED等来使用,在WP8中添加了相关的调用接口,可以方便的使用LED灯,并且支持后台,废话不多说,直接上代码

1、在 WMAppManifest.xml 文件中添加对ID_CAP_ISV_CAMERAID_CAP_MICROPHONE功能的引用

<Capabilities>
    <Capability Name="ID_CAP_ISV_CAMERA"/>
    <Capability Name="ID_CAP_MICROPHONE"/>
</Capabilities>


2、通过 AudioVideoCaptureDevice 类来操作摄像头的LED开关

private AudioVideoCaptureDevice avDevice = null;

try
{
    if (avDevice == null)
    {
        //初始化
        avDevice = await AudioVideoCaptureDevice.OpenAsync(SensorLocation,
                                                           AudioVideoCaptureDevice
                                                               .GetAvailableCaptureResolutions(
                                                                   SensorLocation).First());

        //获取支持的Mode
        IReadOnlyList<object> supportedCameraModes = AudioVideoCaptureDevice.GetSupportedPropertyValues(SensorLocation,
                                                                                                        KnownCameraAudioVideoProperties
                                                                                                            .VideoTorchMode);
        if (!supportedCameraModes.ToList().Contains((UInt32)VideoTorchMode.On))
        {
            //不支持LED灯,使用屏幕照明
            ShowWhiteScreenInsteadOfCameraTorch();
            return;
        }
        
        //打开LED灯
        avDevice.SetProperty(KnownCameraAudioVideoProperties.VideoTorchMode, VideoTorchMode.On);
        avDevice.SetProperty(KnownCameraAudioVideoProperties.VideoTorchPower,
                             AudioVideoCaptureDevice.GetSupportedPropertyRange(SensorLocation,
                                                                               KnownCameraAudioVideoProperties
                                                                                   .VideoTorchPower).Max);    
                                                                                   
        //关闭LED灯
        //avDevice.SetProperty(KnownCameraAudioVideoProperties.VideoTorchMode, VideoTorchMode.Off);
        //avDevice.SetProperty(KnownCameraAudioVideoProperties.VideoTorchPower,
        //                     AudioVideoCaptureDevice.GetSupportedPropertyRange(SensorLocation,
        //                                                                       KnownCameraAudioVideoProperties
        //                                                                           .VideoTorchPower).Min);    
        
        
    }
}
catch (Exception)
{
    ShowWhiteScreenInsteadOfCameraTorch();
}

3、使用完手电筒的时候要释放资源

            if (avDevice != null)
            {
                avDevice.Dispose();
                avDevice = null;
            }