2
votes

My problem is that I have an StorageFile object in foreground and want to play it in BackgroundMediaPlayer like this:

mediaPlayer.SetFileSource(soundStorageFile);

but it is not possible to use SetFileSource() in the foreground, you should call it in the background task, or initialize a third project in the background and call it from there.

So how can I pass an object to the background project?

(It's a Windows Phone Runtime app)

1

1 Answers

2
votes

Communication between UI and BackgroundMediaPlayer can be done 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.

You use SendMessageToBackground to pass a simple object by using ValueSet. Once you send it to your BMP Instance, then the MessageReceivedFromForeground event is raised and you can read your passed object from MediaPlayerDataReceivedEventArgs.

In your case, you can for example pass a string with a file path to your Player:

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

Then as I've said - the appropriate event is (should be) raised by Player instance:

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

I strongly recommend to read the mentioned overview at MSDN, debug your program and see how it works.


On the other hand if you want just to set track from file you can try like this (you can't set FileSource in UI - that's true, but you can use 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));