我正在制作一个带有媒体播放器元素的UWP程序。我的代码如下:
XAML
<Grid>
<Grid.Background>
<SolidColorBrush Color="#FF000000"/>
</Grid.Background>
<MediaPlayerElement x:Name="Player"
Stretch="Uniform"
AreTransportControlsEnabled ="True"
AutoPlay="True"
IsHoldingEnabled="False"
IsRightTapEnabled="False">
<MediaPlayerElement.TransportControls>
<MediaTransportControls IsZoomButtonVisible="False" IsZoomEnabled="False" KeyDown="MediaTransportControls_KeyDown" RequiresPointer="WhenEngaged" />
</MediaPlayerElement.TransportControls>
</MediaPlayerElement>
<ProgressRing x:Name="EpisodeProgress" HorizontalAlignment="Center" VerticalAlignment="Center" Height="80" Width="80"/>
</Grid>
C#:
public sealed partial class Media_Player : Page
{
public Media_Player()
{
this.InitializeComponent();
Player.TransportControls.DoubleTapped += SingleMediaElement_DoubleTapped;
}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;
EpisodeProgress.IsActive = true;
Uri source = new Uri("https://mediaplatstorage1.blob.core.windows.net/windows-universal-samples-media/sintel_trailer-480p.mp4");
Player.Source = MediaSource.CreateFromUri(source);
EpisodeProgress.IsActive = false;
Window.Current.CoreWindow.KeyDown += CoreWindow_KeyDown;
}
private void CoreWindow_KeyDown(CoreWindow sender, KeyEventArgs args)
{
if (args.VirtualKey == Windows.System.VirtualKey.Space)
{
if (Player.MediaPlayer.PlaybackSession.PlaybackState == Windows.Media.Playback.MediaPlaybackState.Playing)
{
Player.MediaPlayer.Pause();
}
else if (Player.MediaPlayer.PlaybackSession.PlaybackState == Windows.Media.Playback.MediaPlaybackState.Paused)
{
Player.MediaPlayer.Play();
}
}
}
private void SingleMediaElement_DoubleTapped(object sender, DoubleTappedRoutedEventArgs e)
{
var view = ApplicationView.GetForCurrentView();
if (view.IsFullScreenMode)
view.ExitFullScreenMode();
else
view.TryEnterFullScreenMode();
}
}
所以我想做的是使用键盘上的空格键使用KeyDown事件暂停/播放视频。将此活动附加到的最佳位置是什么?将其附加到核心窗口仍然只在某些时间工作,因为在全屏模式下事件由于某种原因触发两次。此外,当它连接在当前设置中时,双击事件也不会再触发。在添加Key处理程序之前,双击工作完美。我做错了什么,我应该在哪里附加一个事件来监听窗口和全屏的密钥?
谢谢!
答案 0 :(得分:0)
当MediaPlayerElement
处于完全窗口模式时,空格键已经具有默认行为,按键将暂停/播放您不需要控制的视频。因此,您只需将按键事件附加到核心窗口,但添加一个条件来判断玩家是否处于完全窗口模式,然后确定是否执行自定义按键事件。否则,您的自定义行为和默认值将导致事件两次触发。更新了CoreWindow_KeyDown
代码,如下所示。
private void CoreWindow_KeyDown(CoreWindow sender, KeyEventArgs args)
{
if (args.VirtualKey == Windows.System.VirtualKey.Space && !Player.IsFullWindow)
{
if (Player.MediaPlayer.PlaybackSession.PlaybackState == Windows.Media.Playback.MediaPlaybackState.Playing)
{
Player.MediaPlayer.Pause();
}
else if (Player.MediaPlayer.PlaybackSession.PlaybackState == Windows.Media.Playback.MediaPlaybackState.Paused)
{
Player.MediaPlayer.Play();
}
}
}