导航到另一个Frame后,MediaPlayerElement正在播放音频.如果我再次导航到此框架,则可以听到两个音频实例,一个实例来自当前正在播放的视频的音频,另一个实例是我上次导航至此框架时的音频.导航到另一个Frame后如何停止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);
}
}
解决方法:
例如,根据您离开页面导航时想要发生的情况,可以通过将以下方法添加到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();
});
}
您可能还想停止它,然后在导航回Page时继续,因此您可能应该重写void OnNavigatedTo(NavigationEventArgs e)方法.