【问题标题】:UWP Access MediaPlayerElement from other pageUWP 从其他页面访问 MediaPlayerElement
【发布时间】:2017-12-12 02:45:09
【问题描述】:

在我的 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 的方法。另一个 Page 在 myFrame 中打开。我想保留 TransportControls。

【问题讨论】:

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


    【解决方案1】:

    您不应依赖 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();
    

    【讨论】:

    • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接答案可能会失效。 - From Review
    • 更新了答案。
    猜你喜欢
    • 1970-01-01
    • 2020-11-23
    • 1970-01-01
    • 1970-01-01
    • 2013-12-22
    • 1970-01-01
    • 2014-05-20
    • 2018-12-15
    • 1970-01-01
    相关资源
    最近更新 更多