Search code examples
c#xamluwpmedia-player

UWP MediaPlayer still playing music in redirected app instance


I wanted to make it so that when opening a media file (music or video), it opens in one application window, and not create another window with another file being played (for example, so that two tracks do not play at the same time or two videos do not play at the same time). I made a redirect in the Main method, and it works almost correctly, when opening another media file, the application opens it in an already existing window, as if overwriting the previous instance of the application. But the main problem is that the music in the player from the previous instance continues to play and overlaps with the sound from the new instance.

Main method with redirection: `static void Main() { IActivatedEventArgs activatedArgs = AppInstance.GetActivatedEventArgs();

    if (activatedArgs is FileActivatedEventArgs fileArgs)
    {
        IStorageItem file = fileArgs.Files.FirstOrDefault();
        if (file != null)
        {
            AppInstance instance;

            if (Constants.SupportedImagesFormates.Any(x => file.Name.Contains(x)))
            {
                instance = AppInstance.FindOrRegisterInstanceForKey(file.Name);
            }
            else
            {
                instance = AppInstance.FindOrRegisterInstanceForKey("playbackMedia");
            }

            if (instance.IsCurrentInstance)
            {
                Application.Start((p) => new App());
            }
            else
            {
                instance.RedirectActivationTo();
            }
        }
    }
    else
    {
        Application.Start((p) => new App());
    }
}`

Any ideas how to fix it? I hope I explained it clearly...


Solution

  • When opening a new instance, you need to pause the MediaPlayer manually.

    It is recommended to use MediaPlayer.Pause to pause your audio or video files when opening new instance.