Search code examples
c#windows-store-appsuwpwindows-10-universal

How to play audio in background using AudioGraph Api?


I am using windows 10 Audio Graphs APi to play tracks. The reason I am using this API is I need to play tracks in different Playback devices. So, using this API I can easily choose output playback device. But the problem I am facing right now is that whenever application goes in background or I minimize the app track stops playing.

How to keep playing audio in background while using AudioGraph Api?


Solution

  • How to keep playing audio in background while using AudioGraph Api?

    You need to follow guidance to enable Background audio in UWP app, if you only need to use AudioGraph and not the MediaPlayer, this will also work well.

    This document was adapted from the UWP Background Audio sample.

    The Background Media Playback capability is the right one we need to enable.

    There are two scenarios have been supported:

    1. Long-running playlists: The user briefly brings up a foreground app to select and start a playlist, after which the user expects the playlist to continue playing in the background.

    2. Using task switcher: The user briefly brings up a foreground app to start playing audio, then switches to another open app using the task switcher. The user expects the audio to continue playing in the background.

    I just create a sample to implement the first scenario and use AudioGraph API to play audio file, some points we need to check:

    1. Enable the Background Media Playback capability

    2. Set MediaPlaybackList for MediaPlayer, I followed the official sample to use PlaybackService:

      MediaPlayer Player => PlaybackService.Instance.Player;
      
      MediaPlaybackList PlaybackList
      {
          get { return Player.Source as MediaPlaybackList; }
          set { Player.Source = value; }
      }
      
      public MainPage()
      {
          this.InitializeComponent();
      
          // Handle page load events
          Loaded += Scenario1_Loaded;
      }
      
      private void Scenario1_Loaded(object sender, RoutedEventArgs e)
      {
          // Create a new playback list
          if (PlaybackList == null)
              PlaybackList = new MediaPlaybackList();
      }
      

    Please check my completed sample: LINK