目录

Background Playback

In actual application scenarios, most audio and video applications require background playback. This topic describes how to implement long-duration background playback.

Basic Concepts

Before diving in, you should understand the following basic concepts to effectively implement background playback based on your player type.

Application Access Standards

If an application does not meet the above access standards, playback in the background will be muted and frozen by the system, preventing normal background playback. Playback will only resume and unmute when the application is brought back to the foreground.

How to Develop

The basic steps for audio and video applications to achieve background playback are as follows:

[h2]Starting the Player

An application can use AudioRenderer, AVPlayer, or another third-party or self-developed player to play audio and video.

[h2]Accessing AVSession

When creating an audio stream of type STREAM_USAGE_MUSIC, STREAM_USAGE_MOVIE, STREAM_USAGE_AUDIOBOOK, or STREAM_USAGE_GAME, whether to continue playback in the background or start playback in the background, you must access AVSession.

You are advised to create an AVSession object before the application starts or begins playback, and release it when the application process ends or exits playback. This avoids frequent creation and release of AVSession, which may affect playback continuity. During background playback, ensure that the AVSession object always exists to prevent it from being reclaimed by the system. For example, save the object in a class member variable instead of a local variable.

After creating AVSession, set the following metadata and register the following control commands to ensure user experience.

For details about how to access AVSession, see Accessing AVSession.

[h2]Requesting Continuous Tasks

You can request various types of continuous tasks. For example, when the background audio playback task type is AUDIO_PLAYBACK, whether the application is playing audio, playing video, or casting through the AVCastPicker component in the background, you can request a continuous task of type AUDIO_PLAYBACK.

For details, see Continuous Task (ArkTS).

[h2]Listening for Foreground and Background States

If the application does not have background playback service, you can use the lifecycle function onBackground to determine whether the application has entered the background and proactively stop playback. Otherwise, it will be affected by AVSession and continuous task module management, impacting the application's normal playback. If you need to restart playback when the application returns to the foreground, use the lifecycle function onForeground to determine whether the application is back in the foreground.

Setting the Background Playback Mode

Before an application switches to the background, it can call setBackgroundPlayMode to set the background playback mode, informing the system whether the application will continue playback in the background. For audio and video applications, the system determines whether to display the live view when the application switches to the background based on this value.

[h2]Playback Mode Description

The system supports the following playback modes:

  1. For applications whose AVSessionType is audio, the default value is ENABLE_BACKGROUND_PLAY. For applications whose AVSessionType is video, the default value is DISABLE_BACKGROUND_PLAY.

  2. Audio and video applications should set the correct background playback mode before switching to the background, so that the system live view is displayed correctly. If an application provides a switch such as "support background playback", the background playback mode set by the application must be consistent with the switch state.

[h2]How to Develop

To implement background playback for an audio or video application, perform the following steps:

  1. Before setting the background playback mode, create an AVSession session. You are advised to create a session when the application starts or begins playback. For details, see Accessing AVSession.

  2. After creating the AVSession session, call setBackgroundPlayMode before the application switches to the background to set the correct background playback mode.

import { avSession } from '@kit.AVSessionKit';
import { BusinessError } from '@kit.BasicServicesKit';
// ...

@Entry
@Component
struct Index {
  @State message: string = 'hello world';
  // ...

  build() {
    Column() {
      // ...
      Text(this.message)
        .onClick(async () => {
          let currentAVSession: avSession.AVSession | undefined = undefined;
          let tag = 'createNewSession';
          let context: Context = this.getUIContext().getHostContext() as Context;
          // Assume that a session has been created. For details about how to create a session, see the preceding examples.
          avSession.createAVSession(context, tag, 'audio', (err: BusinessError, data: avSession.AVSession) => {
            if (err) {
              console.error(`CreateAVSession BusinessError: code: ${err.code}, message: ${err.message}`);
            } else {
              currentAVSession = data;
            }
          });
          // Set the background playback mode.
          if (currentAVSession !== undefined) {
            try {
              (currentAVSession as avSession.AVSession)
                .setBackgroundPlayMode(avSession.BackgroundPlayMode.ENABLE_BACKGROUND_PLAY);
              // ...
            } catch (err) {
              console.error(`setBackgroundPlayMode BusinessError: code: ${err.code}, message: ${err.message}`);
              // ...
            }
          }
        })
    }
    .width('100%')
    .height('100%')
  }
}

Complete Sample Code

Basic Playback Control and Playback Control Enhancement