在背景播放媒體Play media in the background

本文說明如何設定您的 app,當 app 從前景移至背景時,該媒體仍能繼續播放。This article shows you how to configure your app so that media continues to play when your app moves from the foreground to the background. 這表示即使使用者已最小化您的 App、回到主畫面,或以其他方式從您的 App 離開之後,您的 App 仍可繼續播放音訊。This means that even after the user has minimized your app, returned to the home screen, or has navigated away from your app in some other way, your app can continue to play audio.

背景音訊播放的案例包含:Scenarios for background audio playback include:

  • 長時間執行的播放清單: 使用者會短暫叫用前景 app 來選取和開始播放清單,完成這些動作後,使用者預期播放清單會在背景持續播放。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.

  • 使用工作切換器: 使用者會短暫叫用前景 app 來開始播放音訊,然後使用工作切換器,切換到另一個開啟的 app。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.

本文中描述的背景音訊實作可讓您的 app 在所有 Windows 裝置上執行,包括行動裝置、桌上型電腦及 Xbox。The background audio implementation described in this article will allow your app to run universally on all Windows devices including Mobile, Desktop, and Xbox.


本文中的程式碼是從 UWP 背景音訊範例改編而來。The code in this article was adapted from the UWP Background Audio sample.

單處理序模型的說明Explanation of one-process model

從 Windows 10 版本 1607 開始,引進了新的單一處理序模型,可大幅簡化啟用背景音訊的處理序。With Windows 10, version 1607, a new single-process model has been introduced that greatly simplifies the process of enabling background audio. 之前,除了前景 app 之外還要求您的 app 能夠管理背景處理程序,然後在這兩個處理程序之間手動傳遞狀態變更。Previously, your app was required to manage a background process in addition to your foreground app and then manually communicate state changes between the two processes. 在新模型中,您只需將背景音訊功能新增到您的應用程式資訊清單,而您的 app 將會在移至背景時自動繼續播放音訊。Under the new model, you simply add the background audio capability to your app manifest, and your app will automatically continue playing audio when it moves to the background. 有兩個新的應用程式週期事件 (EnteredBackgroundLeavingBackground) 可讓您的 app 知道它進入和離開背景的時機。Two new application lifecycle events, EnteredBackground and LeavingBackground let your app know when it is entering and leaving the background. 當您的 app 移到轉換為背景或轉換為前景的處理程序時,系統強制執行的記憶體限制可能會變更,讓您能夠使用這些事件來檢查您目前的記憶體耗用量並釋出資源,以維持在限制之下。When your app moves into the transitions to or from the background, the memory constraints enforced by the system may change, so you can use these events to check your current memory consumption and free up resources in order to stay below the limit.

藉由消除複雜的跨處理程序通訊與狀態管理,新模型可讓您藉由大幅減少程式碼,更快速地實作背景音訊。By eliminating the complex cross-process communication and state management, the new model allows you to implement background audio much more quickly with a significant reduction in code. 不過,目前的回溯相容性版本仍然支援兩個處理程序的模型。However, the two-process model is still supported in the current release for backwards compatibility. 如需詳細資訊,請參閱舊版的背景音效模型For more information, see Legacy background audio model.

背景音訊的需求Requirements for background audio

當您的 app 處於背景時,該 app 必須符合下列需求才能播放音訊。Your app must meet the following requirements for audio playback while your app is in the background.

  • 背景媒體播放功能新增到您的應用程式資訊清單,如本文稍後所述。Add the Background Media Playback capability to your app manifest, as described later in this article.
  • 如果您的 app 會停用 MediaPlayer 與系統媒體傳輸控制項 (SMTC) 的自動整合 (例如,將 CommandManager.IsEnabled 屬性設為 false),則您必須實作與 SMTC 的手動整合,以啟用背景媒體播放。If your app disables the automatic integration of MediaPlayer with the System Media Transport Controls (SMTC), such as by setting the CommandManager.IsEnabled property to false, then you must implement manual integration with the SMTC in order to enable background media playback. 如果您使用 MediaPlayer 以外的 API (例如 AudioGraph) 來播放音訊,而且想要在您的應用程式 移至背景時繼續播放音訊,也必須手動與 SMTC 整合。You must also manually integrate with SMTC if you are using an API other than MediaPlayer, such as AudioGraph, to play audio if you want to have the audio continue to play when your app moves to the background. 最低的 SMTC 整合需求請參閱系統媒體傳輸控制項的手動控制項的<針對背景音訊使用系統媒體傳輸控制項>一節中所述。The minimum SMTC integration requirements are described in the "Use the system media transport controls for background audio" section of Manual control of the System Media Transport Controls.
  • 當您的 app 處於背景時,您必須維持在系統針對背景 app 所設定的記憶體使用量限制之下。While your app is in the background, you must stay under the memory usage limits set by the system for background apps. 本文稍後將提供處於背景時用於管理記憶體的指導方針。Guidance for managing memory while in the background is provided later in this article.

背景媒體播放資訊清單功能Background media playback manifest capability

若要啟用背景音訊,您必須將背景媒體播放功能新增到應用程式資訊清單檔案 Package.appxmanifest。To enable background audio, you must add the background media playback capability to the app manifest file, Package.appxmanifest.

使用資訊清單設計工具以將功能新增到應用程式資訊清單To add capabilities to the app manifest using the manifest designer

  1. 在 Microsoft Visual Studio 的 方案總管中,按兩下 package.appxmanifest 專案以開啟應用程式資訊清單的設計工具。In Microsoft Visual Studio, in Solution Explorer, open the designer for the application manifest by double-clicking the package.appxmanifest item.
  2. 選取 [功能] 索引標籤。Select the Capabilities tab.
  3. 選取 [ 背景媒體播放 ] 核取方塊。Select the Background Media Playback check box.

若要藉由手動編輯應用程式資訊清單 xml 來設定功能,請先確認已在 Package 元素中定義 uap3 命名空間前置詞。To set the capability by manually editing the app manifest xml, first make sure that the uap3 namespace prefix is defined in the Package element. 如果沒有,請新增它,如下所示。If not, add it as shown below.

  IgnorableNamespaces="uap uap3 mp">

接下來,將 backgroundMediaPlayback 功能新增到 Capabilities 元素︰Next, add the backgroundMediaPlayback capability to the Capabilities element:

    <uap3:Capability Name="backgroundMediaPlayback"/>

處理前景與背景之間的轉換Handle transitioning between foreground and background

當您的 app 從前景移到背景時,會引發 EnteredBackground 事件。When your app moves from the foreground to the background, the EnteredBackground event is raised. 當您的 app 回到前景時,會引發 LeavingBackground 事件。And when your app returns to the foreground, the LeavingBackground event is raised. 因為這些是應用程式週期事件,您應該在建立 app 時登錄這些事件的處理常式。Because these are app lifecycle events, you should register handlers for these events when your app is created. 在預設專案範本中,這表示將它新增到 App.xaml.cs 中的 App 類別建構函式。In the default project template, this means adding it to the App class constructor in App.xaml.cs.

public App()
    this.Suspending += OnSuspending;

    this.EnteredBackground += App_EnteredBackground;
    this.LeavingBackground += App_LeavingBackground;

建立變數以追蹤您目前是否正在背景中執行。Create a variable to track whether you are currently running in the background.

bool _isInBackgroundMode = false;

引發 EnteredBackground 事件時,請設定追蹤變數,以指出您目前正在背景中執行。When the EnteredBackground event is raised, set the tracking variable to indicate that you are currently running in the background. 您不應該在 EnteredBackground 事件中執行長時間執行的工作,因為這會在轉換到背景時導致使用者看見緩慢的轉換過程。You should not perform long-running tasks in the EnteredBackground event because this may cause the transition to the background to appear slow to the user.

private void App_EnteredBackground(object sender, EnteredBackgroundEventArgs e)
    _isInBackgroundMode = true;

LeavingBackground 事件處理常式中,您應該設定追蹤變數,以指出您的 App 已不在背景執行。In the LeavingBackground event handler, you should set the tracking variable to indicate that your app is no longer running in the background.

private void App_LeavingBackground(object sender, LeavingBackgroundEventArgs e)
    _isInBackgroundMode = false;

記憶體管理需求Memory management requirements

處理前景和背景之間轉換最重要的部分,便是管理 App 使用的記憶體。The most important part of handling the transition between foreground and background is managing the memory that your app uses. 因為在背景中執行將會減少系統允許您 App 保留的記憶體資源,所以,您也應該註冊 AppMemoryUsageIncreasedAppMemoryUsageLimitChanging 事件。Because running in the background will reduce the memory resources your app is allowed to retain by the system, you should also register for the AppMemoryUsageIncreased and AppMemoryUsageLimitChanging events. 引發這些事件時,您應該檢查 App 目前的記憶體使用量與目前的限制,然後視需求降低記憶體使用量。When these events are raised, you should check your app's current memory usage and the current limit, and then reduce your memory usage if needed. 如需降低在背景執行時的記憶體使用量,請參閱當 App 移至背景時釋出記憶體For information about reducing your memory usage while running in the background, see Free memory when your app moves to the background.

背景媒體 App 的網路可用性Network availability for background media apps

所有網路感知的媒體來源 (不是從資料流或檔案建立的媒體來源) 會在擷取遠端內容時,讓網路連線保持使用中狀態,並且在不需擷取遠端內容時釋放網路連線。All network aware media sources, those that are not created from a stream or a file, will keep the network connection active while retrieving remote content, and they release it when they are not. MediaStreamSource 特別依賴應用程式使用 SetBufferedRange,正確地向平台報告正確的緩衝範圍。MediaStreamSource, specifically, relies on the application to correctly report the correct buffered range to the platform using SetBufferedRange. 針對整個內容完整進行緩衝處理之後,就不會再代替 app 保留網路了。After the entire content is fully buffered, the network will no longer be reserved on the app’s behalf.

如果您需要在無法下載媒體時,於背景中進行網路呼叫,則必須將它們包裝於適當的工作中,例如 MaintenanceTriggerTimeTriggerIf you need to make network calls that occur in the background when media is not downloading, these must be wrapped in an appropriate task like MaintenanceTrigger or TimeTrigger. 如需詳細資訊,請參閱 使用背景工作支援您的應用程式For more information, see Support your app with background tasks.