【问题标题】:How to pass an object to background project in Windows Phone?如何将对象传递给 Windows Phone 中的后台项目?
【发布时间】:2014-08-10 15:42:17
【问题描述】:

我的问题是我在前台有一个StorageFile 对象,想在BackgroundMediaPlayer 中播放它,如下所示:

mediaPlayer.SetFileSource(soundStorageFile);

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

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

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

【问题讨论】:

    标签: c# xaml windows-runtime windows-phone windows-phone-8.1


    【解决方案1】:

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

    一个简单的通信机制会在前台和后台进程中引发事件。 SendMessageToForeground 和 SendMessageToBackground 方法各自调用相应任务中的事件。数据可以作为参数传递给接收任务中的事件处理程序。

    您使用SendMessageToBackground 传递a simple object by using ValueSet。将其发送到您的 BMP 实例 后,MessageReceivedFromForeground event 会被引发,您可以从 MediaPlayerDataReceivedEventArgs 读取您传递的 object

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

    // 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));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-07
      • 2012-10-15
      • 1970-01-01
      • 2013-09-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多