如何在导航到另一帧后停止MediaPlayerElement播放音频?

时间:2017-04-22 09:05:39

标签: c# xaml uwp win-universal-app windows-10-universal

MediaPlayerElement在导航到另一个帧后播放音频。如果我再次导航到此帧,我可以听到两个音频实例,一个来自当前正在播放的视频的音频,另一个来自我导航到此帧的最后一次。如何在导航到另一个帧后停止MediaPlayerElement?

供参考:

我的XAML框架部分的整个代码

<Page.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/Styles/MediaPlayerDictionary.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Page.Resources>
<Grid Background="Transparent">
    <MediaPlayerElement  Name="YoutubePlayer" MaxWidth="640" MaxHeight="360" AreTransportControlsEnabled="True">
        <MediaPlayerElement.TransportControls>
            <video:CustomMediaTransportControls x:Name="CustomMediaControl" IsSkipBackwardButtonVisible="True" IsSkipForwardButtonVisible="True" IsSkipBackwardEnabled="True" IsSkipForwardEnabled="True" IsFullWindowButtonVisible="True" IsFullWindowEnabled="True" QualityChanged="CustomMediaControl_QualityChangedAsync"/>
        </MediaPlayerElement.TransportControls>
    </MediaPlayerElement>
</Grid>

我的C#的整个代码框架的一部分

public sealed partial class VideosPage : Page
{

public VideosPage()
{
    this.InitializeComponent();
}

protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
    base.OnNavigatingFrom(e);
    YoutubePlayer.MediaPlayer.Dispose();
}

public async Task setVideoSourceAsync(YouTubeQuality videoQuality)
{

    try
    {
        var youtubeUrl = await YouTube.GetVideoUriAsync("QTYVJhy04rs", YouTubeQuality.Quality144P, videoQuality);
        YoutubePlayer.Source = MediaSource.CreateFromUri(youtubeUrl.Uri);
        YoutubePlayer.AutoPlay = true;
    }
    catch (Exception e)
    {
        //await setVideoSourceAsync();
    }
}

private async void Page_LoadedAsync(object sender, RoutedEventArgs e)
{
    if (ApplicationView.GetForCurrentView().IsViewModeSupported(ApplicationViewMode.CompactOverlay))
    {
        CustomMediaControl.IsCompactOverlayButtonVisible = true;
    }
    await setVideoSourceAsync(YouTubeQuality.Quality360P);
}

private async void CustomMediaControl_QualityChangedAsync(object sender, QualityChangedEventArgs e)
{
    await setVideoSourceAsync(e.NewQuality);
}
}

2 个答案:

答案 0 :(得分:3)

根据您离开页面时想要发生的事情,您可以通过将此方法添加到MediaPlayer所在页面中的代码隐藏来处理MediaPlayer:

protected async override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{  
    base.OnNavigatingFrom(e);
    await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,() =>
    {
        YoutubePlayer?.MediaPlayer.Dispose();
    });
}

您可能还想停止它并在导航回页面时继续,因此您应该覆盖void OnNavigatedTo(NavigationEventArgs e)方法。

答案 1 :(得分:0)

我也遇到了这个问题。即使在等待状态下,接受的答案也会导致未处理的异常。这是此处提供的示例代码中的覆盖处理程序应具有的外观。

protected async override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{  
    base.OnNavigatingFrom(e);
    YoutubePlayer.Source = null;
}