UWP从其他页面访问MediaPlayerElement

时间:2017-12-11 14:26:58

标签: xaml uwp windows-10-universal uwp-xaml

在我的MainPage.xaml中我有

<Grid>
    <NavigationView x:Name="navView">
        <NavigationView.MenuItems>
            <NavigationViewItem x:Name="music" Content="My Music"/>
        </NavigationView.MenuItems>

        <Frame x:Name="myFrame">
            <Frame.ContentTransitions>
                <TransitionCollection>
                    <NavigationThemeTransition/>
                </TransitionCollection>
            </Frame.ContentTransitions>
        </Frame>
    </NavigationView>

    <Grid Grid.Row="1">
        <MediaPlayerElement x:Name="nowPlaying"
          AreTransportControlsEnabled="True" x:FieldModifier="public">
            <MediaPlayerElement.TransportControls>
                ...
            </MediaPlayerElement.TransportControls>
        </MediaPlayerElement>
    </Grid>
</Grid>

我想从其他页面(MyMusic)播放音乐(传递Uri),但我找不到访问MediaPlayerElement的方法。另一个页面在myFrame中打开。我想保留TransportControls。

1 个答案:

答案 0 :(得分:0)

您不应该依赖UI元素从其他页面播放媒体。而是使用MediaPlayer类:

https://docs.microsoft.com/en-us/windows/uwp/audio-video-camera/play-audio-and-video-with-mediaplayer#use-mediaplayerelement-to-render-video-in-xaml

因此,请指定您的MediaPlayerElement(确保将AreTransportControlsEnabled值设置为您需要的值):

<MediaPlayerElement x:Name="_mediaPlayerElement" AreTransportControlsEnabled="False" HorizontalAlignment="Stretch"  Grid.Row="0"/>

然后,您可以将元素链接到可以在代码中引用的MediaPlayer对象:

_mediaPlayerElement.SetMediaPlayer(mediaPlayer);

然后玩你需要的任何东西:

_mediaPlayerElement.Source = MediaSource.CreateFromUri(new Uri("ms-appx:///Assets/example_video.mkv"));
mediaPlayer = _mediaPlayerElement.MediaPlayer;
mediaPlayer.Play();