gpt4 book ai didi

c# - 无法在 SaveState/LoadState 之后设置 MediaElement Source

转载 作者:行者123 更新时间:2023-11-30 12:10:06 26 4
gpt4 key购买 nike

(注意:所有代码都经过了严格的简化。)

问题

暂停/恢复后未设置 MediaElement 源。设置源后,CurrentState 迅速变为“Closed”。

我正在处理 MediaFailed 事件——它没有触发。我还在处理 MediaOpened 事件,它也没有触发。

详情

我有以下更新 MediaElement 源的方法。只要应用程序在暂停后尝试恢复,它就可以很好地工作。

  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 事件,它就被设置为 true。然后,在调用 SetSource() 的代码中,将其包装在 if(_mediaElementLoaded) block 中。

关于c# - 无法在 SaveState/LoadState 之后设置 MediaElement Source,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19405635/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com