gpt4 book ai didi

c# - 如何将对象传递给 Windows Phone 中的后台项目?

转载 作者:太空宇宙 更新时间:2023-11-03 10:41:23 25 4
gpt4 key购买 nike

我的问题是我在前台有一个 StorageFile 对象并想在 BackgroundMediaPlayer 中播放它像这样:

mediaPlayer.SetFileSource(soundStorageFile);

但是不能在前台使用SetFileSource(),您应该在后台任务中调用它,或者在后台初始化第三个项目并从那里调用它。

那么如何将对象传递给后台项目呢?

(这是一个 Windows Phone 运行时应用程序)

最佳答案

UIBackgroundMediaPlayer 之间的通信可以完成 by sending messages :

A simple communication mechanism raises events in both the foreground and background processes. The SendMessageToForeground and SendMessageToBackground methods each invoke events in the corresponding task. Data can be passed as an argument to the event handler in the receiving task.

您使用 SendMessageToBackground通过a simple object by using ValueSet .一旦您将它发送到您的BMP 实例,然后MessageReceivedFromForeground event已引发,您可以从 MediaPlayerDataReceivedEventArgs 读取您传递的对象

在您的情况下,例如,您可以将带有文件路径的字符串传递给您的播放器:

// the UI code - send from Foreground to Background
ValueSet message = new ValueSet();
message.Add("SetTrack", yourStorageFile.Path); // send path (string)
BackgroundMediaPlayer.SendMessageToBackground(message);

然后正如我所说 - Player 实例(应该)引发适当的事件:

private async void BMP_MessageReceivedFromForeground(object sender, MediaPlayerDataReceivedEventArgs e)
{
foreach (string key in e.Data.Keys)
{
switch (key)
{
case "SetTrack":
string passedPath = (string)e.Data.Values.FirstOrDefault();
//here code you want to perform - change track/stop other
// that depends on your needs
break;
// rest of the code

强烈推荐阅读the mentioned overview at MSDN ,调试你的程序,看看它是如何工作的。


另一方面,如果您只想从文件设置轨道,您可以这样尝试(您不能在 UI 中设置 FileSource - 这是真的,但您可以使用 SetUriSource):

// for example playing the first file from MusicLibrary (I assume that Capabilities are set properly)
StorageFile file = (await KnownFolders.MusicLibrary.GetFilesAsync()).FirstOrDefault();
BackgroundMediaPlayer.Current.SetUriSource(new Uri(file.Path, UriKind.RelativeOrAbsolute));

关于c# - 如何将对象传递给 Windows Phone 中的后台项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25230225/

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