簡體   English   中英

如何將對象傳遞給 Windows Phone 中的后台項目?

[英]How to pass an object to background project in Windows Phone?

我的問題是我在前台有一個StorageFile對象,並想像這樣在BackgroundMediaPlayer 中播放它:

mediaPlayer.SetFileSource(soundStorageFile);

但是不能在前台使用SetFileSource() ,您應該在后台任務中調用它,或者在后台初始化第三個項目並從那里調用它。

那么如何將對象傳遞給后台項目呢?

(這是一個 Windows Phone 運行時應用程序)

UIBackgroundMediaPlayer之間的通信可以通過發送消息來完成:

一個簡單的通信機制在前台和后台進程中引發事件。 SendMessageToForeground 和 SendMessageToBackground 方法各自調用相應任務中的事件。 數據可以作為參數傳遞給接收任務中的事件處理程序。

您可以使用SendMessageToBackground 通過使用 ValueSet傳遞一個簡單的對象 一旦您將它發送到您的BMP 實例,就會引發MessageReceivedFromForeground 事件,您可以從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

我強烈建議您閱讀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));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM