C# 如何更改Windows Phone 8.1摄像头上的亮度显示?

C# 如何更改Windows Phone 8.1摄像头上的亮度显示?,c#,xaml,windows-runtime,windows-phone-8.1,C#,Xaml,Windows Runtime,Windows Phone 8.1,我正在尝试更改摄像头视频信号的亮度设置。下面的代码是.cs文件和XAML文件 using System.Diagnostics; using System.Threading.Tasks; using Windows.Media.Capture; using Windows.Media.MediaProperties; using Capture.Common; using Capture.Data; using System; using System.Globalization; using

我正在尝试更改摄像头视频信号的亮度设置。下面的代码是.cs文件和XAML文件

using System.Diagnostics;
using System.Threading.Tasks;
using Windows.Media.Capture;
using Windows.Media.MediaProperties;
using Capture.Common;
using Capture.Data;
using System;
using System.Globalization;
using Windows.ApplicationModel.Resources;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

// The Pivot Application template is documented at http://go.microsoft.com/fwlink/?LinkID=391641

namespace Capture
{
public sealed partial class PivotPage : Page
    {
    private const string FirstGroupName = "FirstGroup";
    private const string SecondGroupName = "SecondGroup";

    private readonly NavigationHelper navigationHelper;
    private readonly ObservableDictionary defaultViewModel = new ObservableDictionary();
    private readonly ResourceLoader resourceLoader = ResourceLoader.GetForCurrentView( "Resources" );

    PivotPage rootPage;

    private Windows.Media.Capture.MediaCapture m_mediaCaptureMgr;



    public PivotPage()
        {
        this.InitializeComponent();

        this.NavigationCacheMode = NavigationCacheMode.Required;

        this.navigationHelper = new NavigationHelper( this );
        this.navigationHelper.LoadState += this.NavigationHelper_LoadState;
        this.navigationHelper.SaveState += this.NavigationHelper_SaveState;

        rootPage = this;
        }

    /// <summary>
    /// Gets the <see cref="NavigationHelper"/> associated with this <see cref="Page"/>.
    /// </summary>
    public NavigationHelper NavigationHelper
        {
        get { return this.navigationHelper; }
        }

    /// <summary>
    /// Gets the view model for this <see cref="Page"/>.
    /// This can be changed to a strongly typed view model.
    /// </summary>
    public ObservableDictionary DefaultViewModel
        {
        get { return this.defaultViewModel; }
        }

    /// <summary>
    /// Populates the page with content passed during navigation. Any saved state is also
    /// provided when recreating a page from a prior session.
    /// </summary>
    /// <param name="sender">
    /// The source of the event; typically <see cref="NavigationHelper"/>.
    /// </param>
    /// <param name="e">Event data that provides both the navigation parameter passed to
    /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and
    /// a dictionary of state preserved by this page during an earlier
    /// session. The state will be null the first time a page is visited.</param>
    private async void NavigationHelper_LoadState( object sender, LoadStateEventArgs e )
        {
        // TODO: Create an appropriate data model for your problem domain to replace the sample data
        var sampleDataGroup = await SampleDataSource.GetGroupAsync( "Group-1" );
        this.DefaultViewModel[ FirstGroupName ] = sampleDataGroup;
        }

    /// <summary>
    /// Preserves state associated with this page in case the application is suspended or the
    /// page is discarded from the navigation cache. Values must conform to the serialization
    /// requirements of <see cref="SuspensionManager.SessionState"/>.
    /// </summary>
    /// <param name="sender">The source of the event; typically <see cref="NavigationHelper"/>.</param>
    /// <param name="e">Event data that provides an empty dictionary to be populated with
    /// serializable state.</param>
    private void NavigationHelper_SaveState( object sender, SaveStateEventArgs e )
        {
        // TODO: Save the unique state of the page here.
        }

    /// <summary>
    /// Adds an item to the list when the app bar button is clicked.
    /// </summary>
    /// <summary>
    /// Invoked when an item within a section is clicked.
    /// </summary>
    private void ItemView_ItemClick( object sender, ItemClickEventArgs e )
        {
        // Navigate to the appropriate destination page, configuring the new page
        // by passing required information as a navigation parameter
        var itemId = ( (SampleDataItem)e.ClickedItem ).UniqueId;
        if ( !Frame.Navigate( typeof( ItemPage ), itemId ) )
            {
            throw new Exception( this.resourceLoader.GetString( "NavigationFailedExceptionMessage" ) );
            }
        }

    /// <summary>
    /// Loads the content for the second pivot item when it is scrolled into view.
    /// </summary>
    private async void SecondPivot_Loaded( object sender, RoutedEventArgs e )
        {
        var sampleDataGroup = await SampleDataSource.GetGroupAsync( "Group-2" );
        DefaultViewModel[ SecondGroupName ] = sampleDataGroup;
        }

    #region NavigationHelper registration

    /// <summary>
    /// The methods provided in this section are simply used to allow
    /// NavigationHelper to respond to the page's navigation methods.
    /// <para>
    /// Page specific logic should be placed in event handlers for the  
    /// <see cref="NavigationHelper.LoadState"/>
    /// and <see cref="NavigationHelper.SaveState"/>.
    /// The navigation parameter is available in the LoadState method 
    /// in addition to page state preserved during an earlier session.
    /// </para>
    /// </summary>
    /// <param name="e">Provides data for navigation methods and event
    /// handlers that cannot cancel the navigation request.</param>
    protected override void OnNavigatedTo( NavigationEventArgs e )
        {
        this.navigationHelper.OnNavigatedTo( e );
        }

    protected override void OnNavigatedFrom( NavigationEventArgs e )
        {
        navigationHelper.OnNavigatedFrom( e );
        }

    #endregion


    private async void StartAppBarButton_OnClick( object sender, RoutedEventArgs e )
        {
        await StartDevice();
        await StartPreview();
        }

    private void StopAppBarButton_OnClick( object sender, RoutedEventArgs e )
        {
        previewElement.Source = null;

        m_mediaCaptureMgr.RecordLimitationExceeded -= new Windows.Media.Capture.RecordLimitationExceededEventHandler( RecordLimitationExceeded );
        m_mediaCaptureMgr.Failed -= new Windows.Media.Capture.MediaCaptureFailedEventHandler( Failed );

        m_mediaCaptureMgr.Dispose();
        m_mediaCaptureMgr = null;
        }

    private void EnumerateVideoProperties( MediaStreamType mediaStreamType )
        {
        var res = m_mediaCaptureMgr.VideoDeviceController.GetAvailableMediaStreamProperties( mediaStreamType );
        if ( res.Count > 1 )
            {
            for ( int i = 0 ; i < res.Count ; i++ )
                {
                var vp = (VideoEncodingProperties)res[ i ];
                Debug.WriteLine( "{0}    Type: {1}    [W x H]: {2} x {3}", i + 1, vp.Subtype, vp.Width, vp.Height );
                }
            }
        }

    private async Task StartDevice()
        {
        try
            {
            ShowStatusMessage( "Starting device" );
            m_mediaCaptureMgr = new Windows.Media.Capture.MediaCapture();
            await m_mediaCaptureMgr.InitializeAsync();

            if ( m_mediaCaptureMgr.MediaCaptureSettings.VideoDeviceId != "" && m_mediaCaptureMgr.MediaCaptureSettings.AudioDeviceId != "" )
                {
                ShowStatusMessage( "Device initialized successful" );

                m_mediaCaptureMgr.RecordLimitationExceeded += new Windows.Media.Capture.RecordLimitationExceededEventHandler( RecordLimitationExceeded );
                m_mediaCaptureMgr.Failed += new Windows.Media.Capture.MediaCaptureFailedEventHandler( Failed );
                }
            else
                {
                ShowStatusMessage( "No VideoDevice/AudioDevice Found" );
                }
            }
        catch ( Exception exception )
            {
            ShowExceptionMessage( exception );
            }
        }

    public async void RecordLimitationExceeded( Windows.Media.Capture.MediaCapture currentCaptureObject )
        {
        await Dispatcher.RunAsync( Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
        {
            try
                {
                ShowStatusMessage( "Stopping Record on exceeding max record duration" );
                await m_mediaCaptureMgr.StopRecordAsync();
                ShowStatusMessage( "Stopped record on exceeding max record duration:" );

                if ( !m_mediaCaptureMgr.MediaCaptureSettings.ConcurrentRecordAndPhotoSupported )
                    {
                    //if camera does not support record and Takephoto at the same time
                    //enable TakePhoto button again, after record finished
                    }
                }
            catch ( Exception e )
                {
                ShowExceptionMessage( e );
                }
        } );
        }

    public async void Failed( Windows.Media.Capture.MediaCapture currentCaptureObject, MediaCaptureFailedEventArgs currentFailure )
        {
        try
            {
            await Dispatcher.RunAsync( Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                ShowStatusMessage( "Fatal error" + currentFailure.Message );
            } );
            }
        catch ( Exception e )
            {
            ShowExceptionMessage( e );
            }
        }

    private async Task StartPreview()
        {
        try
            {
            ShowStatusMessage( "Starting preview" );

            previewCanvas.Visibility = Windows.UI.Xaml.Visibility.Visible;
            previewElement.Source = m_mediaCaptureMgr;
            await m_mediaCaptureMgr.StartPreviewAsync();

            if ( ( m_mediaCaptureMgr.VideoDeviceController.Brightness != null ) && m_mediaCaptureMgr.VideoDeviceController.Brightness.Capabilities.Supported )
                {
                SetupVideoDeviceControl( m_mediaCaptureMgr.VideoDeviceController.Brightness, sldBrightness );
                }
            if ( ( m_mediaCaptureMgr.VideoDeviceController.Contrast != null ) && m_mediaCaptureMgr.VideoDeviceController.Contrast.Capabilities.Supported )
                {
                SetupVideoDeviceControl( m_mediaCaptureMgr.VideoDeviceController.Contrast, sldContrast );
                }

            ShowStatusMessage( "Start preview successful" );

            }
        catch ( Exception exception )
            {
            previewElement.Source = null;
            ShowExceptionMessage( exception );
            }
        }

    private void SetupVideoDeviceControl( Windows.Media.Devices.MediaDeviceControl videoDeviceControl, Slider slider )
        {
        try
            {
            if ( ( videoDeviceControl.Capabilities ).Supported )
                {
                slider.IsEnabled = true;
                slider.Maximum = videoDeviceControl.Capabilities.Max;
                slider.Minimum = videoDeviceControl.Capabilities.Min;
                slider.StepFrequency = videoDeviceControl.Capabilities.Step;
                double controlValue = 0;
                if ( videoDeviceControl.TryGetValue( out controlValue ) )
                    {
                    slider.Value = controlValue;
                    }
                }
            else
                {
                slider.IsEnabled = false;
                }
            }
        catch ( Exception e )
            {
            ShowExceptionMessage( e );
            }
        }

    // VideoDeviceControllers
    internal void sldBrightness_ValueChanged( Object sender, Windows.UI.Xaml.Controls.Primitives.RangeBaseValueChangedEventArgs e )
        {
        try
            {
            bool succeeded = m_mediaCaptureMgr.VideoDeviceController.Brightness.TrySetValue( sldBrightness.Value );
            if ( !succeeded )
                {
                ShowStatusMessage( "Set Brightness failed" );
                }
            else
                {
                var msg = "Set Brightness: " + sldBrightness.Value;
                ShowStatusMessage( msg );
                Debug.WriteLine( msg );
                }
            }
        catch ( Exception exception )
            {
            ShowExceptionMessage( exception );
            }
        }

    internal void sldContrast_ValueChanged( Object sender, Windows.UI.Xaml.Controls.Primitives.RangeBaseValueChangedEventArgs e )
        {
        try
            {
            bool succeeded = m_mediaCaptureMgr.VideoDeviceController.Contrast.TrySetValue( sldContrast.Value );
            if ( !succeeded )
                {
                ShowStatusMessage( "Set Contrast failed" );
                }
            else
                {
                var msg = "Set Contrast: " + sldContrast.Value;
                ShowStatusMessage( msg );
                Debug.WriteLine( msg );
                }
            }
        catch ( Exception exception )
            {
            ShowExceptionMessage( exception );
            }
        }

    private void ShowStatusMessage( String text )
        {
        StatusBlock.Text = text;
        }

    private void ShowExceptionMessage( Exception ex )
        {
        StatusBlock.Text = "Exception";
        }
    }

public enum NotifyType
    {
    StatusMessage,
    ErrorMessage
    };
}
以及XAML代码:

  <Page x:Class="Capture.PivotPage"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:local="using:Capture"
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  xmlns:data="using:Capture.Data"
  mc:Ignorable="d"
  DataContext="{Binding DefaultViewModel, RelativeSource={RelativeSource Self}}"
  Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Page.Transitions>
    <TransitionCollection>
        <NavigationThemeTransition>
            <NavigationThemeTransition.DefaultNavigationTransitionInfo>
                <CommonNavigationTransitionInfo IsStaggeringEnabled="True" />
            </NavigationThemeTransition.DefaultNavigationTransitionInfo>
        </NavigationThemeTransition>
    </TransitionCollection>
</Page.Transitions>

<Grid>
    <Pivot x:Uid="Pivot"
           Title="MY APPLICATION"
           x:Name="pivot"
           CommonNavigationTransitionInfo.IsStaggerElement="True">

        <!--Pivot item one-->
        <PivotItem x:Uid="PivotItem1"
                   Margin="19,14.5,0,0"
                   Header="first"
                   DataContext="{Binding FirstGroup}"
                   d:DataContext="{Binding Groups[0], Source={d:DesignData Source=/DataModel/SampleData.json, Type=data:SampleDataSource}}"
                   CommonNavigationTransitionInfo.IsStaggerElement="True">
            <!--Double line list with text wrapping-->

            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="*" />
                    <RowDefinition Height="Auto" />
                </Grid.RowDefinitions>

                <TextBlock Style="{StaticResource BasicTextStyle}"
                           HorizontalAlignment="Center"
                           VerticalAlignment="Center"
                           TextAlignment="Center"
                           Text="Preview"
                           Grid.Row="0" />

                <StackPanel Orientation="Vertical"
                            Margin="0,10,0,0"
                            Grid.Row="1">

                    <TextBlock TextWrapping="Wrap"
                               Text="Brightness"
                               Style="{StaticResource BasicTextStyle}"
                               Margin="10,0,10,0"
                               VerticalAlignment="Center" />

                    <Slider x:Name="sldBrightness"
                            IsEnabled="True"
                            ValueChanged="sldBrightness_ValueChanged"
                            Margin="20,0,20,0"
                            FontFamily="Global User Interface"
                            Minimum="0"
                            Maximum="255"
                            LargeChange="25" />

                    <TextBlock TextWrapping="Wrap"
                               Text="Contrast"
                               Style="{StaticResource BasicTextStyle}"
                               Margin="10,0,10,0"
                               VerticalAlignment="Center" />

                    <Slider x:Name="sldContrast"
                            IsEnabled="True"
                            ValueChanged="sldContrast_ValueChanged"
                            Margin="20,0,20,0"
                            Minimum="0"
                            Maximum="10"
                            LargeChange="2" />
                </StackPanel>

                <Canvas x:Name="previewCanvas"
                        Width="320"
                        Height="240"
                        Background="Gray"
                        Grid.Row="2"
                        VerticalAlignment="Center"
                        HorizontalAlignment="Center">

                    <CaptureElement x:Name="previewElement"
                                    Width="320"
                                    Height="240" />
                </Canvas>

                <TextBlock x:Name="StatusBlock"
                           Grid.Row="3"
                           Margin="12,0,12,5"
                           VerticalAlignment="Center"
                           HorizontalAlignment="Center" />
            </Grid>

        </PivotItem>

        <!--Pivot item two-->
        <!--<PivotItem x:Uid="PivotItem2"
                   Margin="19,14.5,0,0"
                   Header="second"
                   DataContext="{Binding SecondGroup}"
                   d:DataContext="{Binding Groups[1], Source={d:DesignDataSource=/DataModel/SampleData.json, Type=data:SampleDataSource}}">
            -->
        <!--Double line list no text wrapping-->
        <!--
        </PivotItem>-->
    </Pivot>
</Grid>

<Page.BottomAppBar>
    <CommandBar>
        <AppBarButton x:Uid="StartAppBarButton"
                      x:Name="StartAppBarButton"
                      Label="start"
                      Icon="Video"
                      Click="StartAppBarButton_OnClick"/>

        <AppBarButton x:Uid="StopAppBarButton"
                      x:Name="StopAppBarButton"
                      Label="stop"
                      Icon="Stop"
                      Click="StopAppBarButton_OnClick"/>

        <CommandBar.SecondaryCommands>
            <!--<AppBarButton x:Uid="SecondaryButton1"
                          x:Name="SecondaryButton1"
                          Label="secondary command 1" />

            <AppBarButton x:Uid="SecondaryButton2"
                          x:Name="SecondaryButton2"
                          Label="secondary command 2" />-->
        </CommandBar.SecondaryCommands>
    </CommandBar>
</Page.BottomAppBar>
似乎设置值的调用成功了,但是值没有改变。合同也是如此。同样的代码在Windows8上运行良好

知道我做错了什么吗


谢谢

经过进一步调查,我发现手机不支持它。电话:

_mediaCaptureMgr.VideoDeviceController.Brightness.Capabilities.Supported
返回false