Running Background Audio in different pages of UWP App

喜欢而已 提交于 2019-12-08 06:33:31

问题


I am making a UWP App where I run Background Audio in the MainPage on a Button Click event. When I move to another page, there's also a different Media to play in Background Audio Task there.

How can I stop the currently playing Task to run the other? Should I define something globally? Any help regarding this issue?

Edit

I am using this sample: https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/BackgroundAudio While the backgroundAudio of the first Page is running, I go to the second page and on a click event I set a new List with the following code:

   // First update the persisted start track
   ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.TrackId, RadioFacade.mySongs[0].MediaUri.ToString()); //here
           ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.Position, new TimeSpan().ToString());

                // Start task
                StartBackgroundAudioTask();

But the new song takes more than the estimated time to run and enter the else of this method:

private void StartBackgroundAudioTask()
        {
            AddMediaPlayerEventHandlers();

            var startResult = this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                bool result = backgroundAudioTaskStarted.WaitOne(10000);
                //Send message to initiate playback
                if (result == true)
                {
                    MessageService.SendMessageToBackground(new UpdatePlaylistMessage(RadioFacade.mySongs));
                    MessageService.SendMessageToBackground(new StartPlaybackMessage());
                }
                else
                {
                    throw new Exception("Background Audio Task didn't start in expected time");
                }
            });
            startResult.Completed = new AsyncActionCompletedHandler(BackgroundTaskInitializationCompleted);
        }

and the old (first playing) song keeps playing.

I tried to Stop the current BackgroundMediaPlayer using BackgroundMediaPLayer.Shutdown() but it didn't work.

Any idea how to let the old song stop and the current song play?


回答1:


You can control the background media player by sending messages to it from the foreground. For example,

From the foreground app:

BackgroundMediaPlayer.SendMessageToBackground(new ValueSet
{
    {"playnew", "some value"}
});

In your background task:

public sealed class AudioPlayer : IBackgroundTask
{
    public void Run(IBackgroundTaskInstance taskInstance)
    {
        BackgroundMediaPlayer.MessageReceivedFromForeground += BackgroundMediaPlayer_MessageReceivedFromForeground;
        ...
        ...
    }

    private async void BackgroundMediaPlayer_MessageReceivedFromForeground(object sender, MediaPlayerDataReceivedEventArgs e)
    {
        object value;
        if (e.Data.TryGetValue("playnew", out value) && value != null)
        {
            // value will be whatever you pass from the foreground.
            BackgroundMediaPlayer.Current.Pause();
            BackgroundMediaPlayer.Current.Source = stream source;
            BackgroundMediaPlayer.Current.Play();
        }
    }

    ...
}

"playnew" can be a global constant in your application. You can use the ValueSet to pass the live stream url to the background task as the value.



来源:https://stackoverflow.com/questions/37538161/running-background-audio-in-different-pages-of-uwp-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!