c# – 在SaveState / LoadState之后无法设置MediaElement Source
作者:互联网
(注意:所有代码都已严格简化.)
问题
挂起/恢复后未设置MediaElement源.设置源后,CurrentState会快速更改为“已关闭”.
我正在处理MediaFailed事件 – 它不会触发.我也在处理MediaOpened事件,它也不会触发.
细节
我有以下方法更新MediaElement的Source.只要应用程序在被暂停后没有尝试恢复,它就能很好地工作.
private async void UpdateMediaElementSource(object sender, EventArgs e)
{
var videoSource = this.DefaultViewModel.CurrentSource; // a string
var file = await StorageFile.GetFileFromPathAsync(videoSource);
var videoStream = await file.OpenAsync(FileAccessMode.Read);
this.videoMediaElement.SetSource(videoStream, file.ContentType);
// The above line works many times as long as the app is not trying to Resume.
}
当应用程序处于暂停状态时,它会调用SaveState方法:
protected async override void SaveState(Dictionary<String, Object> pageState)
{
pageState["MediaElementSource"] = this.DefaultViewModel.CurrentSource;
// I also made the videoStream global so I can dispose it — but no dice.
this.videoStream.Dispose();
this.videoStream = null;
}
当应用程序恢复时,它会调用LoadState方法:
protected async override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
{
string source = string.Empty;
if (pageState != null)
{
if (pageState.ContainsKey("MediaElementSource"))
{
source = (string)pageState["MediaElementSource"];
}
}
var document = PublicationService.GetDocument(this.currentDocumentIdNumber);
this.DefaultViewModel = new DocumentViewModel(document);
this.DefaultViewModel.CurrentMarkerSourceChanged += UpdateMediaElementSource;
if (!string.IsNullOrEmpty(source))
{
// This causes the UpdateMediaElementSource() method to run.
this.DefaultViewModel.CurrentSource = source;
}
}
我感谢你对这个问题的任何帮助.如果您需要更多详细信息,请与我们联系.
解决方法:
因此,事实证明mediaElement的Source在被添加到可视化树之前被设置了.
通常,这样做不是问题:
mediaElement.Source = whatever;
但是这样做是一个问题:
mediaElement.SetSource(stream, MimeType);
结论
调用SetSource(…)时,请确保您的MediaElement是VisualTree的一部分.
让我的上述代码工作的一种简单方法是添加一个全局bool,一旦mediaElement.Loaded事件被触发,该bool设置为true.然后,在调用SetSource()的代码中,将其包装在if(_mediaElementLoaded)块中.
标签:c,windows-runtime,winrt-xaml 来源: https://codeday.me/bug/20190629/1324937.html