How to play audio in the background (HTML)
[This article is for Windows 8.x and Windows Phone 8.x developers writing Windows Runtime apps. If you’re developing for Windows 10, see the latest documentation]
This tutorial shows you how to select the correct category for an audio-video (AV) stream to configure it to play in the background.
Note If a video stream is correctly categorized to play in the background, then when the video is switched to background mode, you will hear the audio portion but not see the accompanying video. This is by design and it reduces the power requirements of the device while it is playing the video in the background.
To see this feature in action as part of a complete media-playback sample, see Media playback, start to finish.
Prerequisites
You must be familiar with HTML, JavaScript, Windows events, and event handling.
You must have an installed instance of Microsoft Visual Studio.
You must have an app that is capable of streaming audio and video. For more information about the simplest way to do this, see Quickstart: audio in a Windows Store app and Quickstart: video and audio.
Instructions
Step 1: Make a background audio declaration in the app manifest
Open the project file for your app in Microsoft Visual Studio.
Double-click the Package.appmanifest file in the Solution Explorer to open the Package.appmanifest dialog box.
Click the Declarations tab, then select Background Tasks from the Available Declarations dropdown box.
Click Add, then click the Audio checkbox, and click OK.Note You can also make the declaration for background audio by adding the code manually. To make the declaration manually, add the following code between the <Application> and </Application> tags in the Package.appmanifest file:
<Extensions> <Extension Category="windows.backgroundTasks" StartPage="default.html"> <BackgroundTasks> <Task Type="audio" /> </BackgroundTasks> </Extension> </Extensions>
You can also make a background declaration for a video stream by using the same manifest file that you created for audio in the preceding steps. To do this, set the "Task Type" attribute to audio.
Add the start page of your project to the
Start page: field
. This is normally default.html.
Step 2: Set msAudioCategory attribute to correct value
In the Solution Explorer pane, click the HTML file to open it. For example, if the HTML file for your app is named MyApp.htm, then click that file to open it.
Add the "msAudioCategory" attribute to the <audio> tag, and set the attribute to either Communications or BackgroundCapabaleMedia as follows:
<audio msAudioCategory="BackgroundCapableMedia" controls="controls"> <source src="Somesong.mp3"/> </audio>
If you’re setting the msAudioCategory for a video stream, use the following code snippet:
<video msAudioCategory="BackgroundCapableMedia" controls="controls"> <source src="Somevideo.mp4"/> </video >
Step 3: Support SystemMediaTransportControls
Windows 8.1 introduces the SystemMediaTransportControls class which replaces the MediaControl class. You should use SystemMediaTransportControls in your app. For completeness, the steps to implement background audio support with MediaControl are included below, but you should only use SystemMediaTransportControls. See How to use the system media transport controls for a more in-depth how-to on using SystemMediaTransportControls.
Even if an app is declared to play audio in the background, the app must enable the SystemMediaTransportControls play and pause buttons by setting isPlayEnabled and isPauseEnabled to true. The app must also handle the buttonpressed event, which notifies the app when the system media transport control buttons are pressed. By providing this minimal event handling support, you make it possible for the user to play or pause the audio without bringing the app to the foreground.
In addition to handling the buttonpressed event, you must also notify the SystemMediaTransportControls when the media state changes, such as when it is paused or playing. To notify the SystemMediaTransportControl about media state changes, set its playbackStatus property to one of the values in MediaPlaybackStatus.
Here is some code that creates a video object with event handlers for paused, playing, and ended events and sets up the SystemMediaTransportControls. It enables the play and pause buttons and adds an event handler for the buttonpressed event. The event handlers for paused, playing, and ended are shown later in this example.
<video id="mediaVideo"
controls
src="https://www.contoso.com/clip.mp4"
onpause="mediaPaused(event)"
onplaying="mediaPlaying(event)"
onended="mediaEnded(event)" />
SystemMediaTransportControls systemControls;
public MainPage()
{
this.InitializeComponent();
// Hook up app to system transport controls.
systemControls = SystemMediaTransportControls.GetForCurrentView();
systemControls.ButtonPressed += SystemControls_ButtonPressed;
// Register to handle the following system transpot control buttons.
systemControls.IsPlayEnabled = true;
systemControls.IsPauseEnabled = true;
}
Here is some code that creates a buttonpressed event handler and helper methods to play and pause the video.
// Event handler for SystemMediaTransportControls' buttonpressed event
function systemMediaControlsButtonPressed(eventIn) {
var mediaButton = Windows.Media.SystemMediaTransportControlsButton;
switch (eventIn.button) {
case mediaButton.play:
playMedia();
break;
case mediaButton.pause:
pauseMedia();
break;
case mediaButton.stop:
stopMedia();
break;
// Insert additional case statements for other buttons you want to handle
}
}
// Plays the media.
function playMedia() {
var media = document.getElementById("mediaVideo");
media.play();
}
// Pauses the media.
function pauseMedia() {
var media = document.getElementById("mediaVideo");
media.pause();
}
// Stops the media.
function stopMedia() {
var media = document.getElementById("mediaVideo");
media.pause();
media.currentTime = 0;
}
Here is the code that handles the media events and updates the playbackStatus property of the SystemMediaTransportControls.
// The media Play event handler.
function mediaPlaying() {
// Update the SystemMediaTransportControl state.
systemMediaControls.playbackStatus = Windows.Media.MediaPlaybackStatus.playing;
}
// The media Pause event handler.
function mediaPaused() {
// Update the SystemMediaTransportControl state.
systemMediaControls.playbackStatus = Windows.Media.MediaPlaybackStatus.paused;
}
// The media Ended event handler.
function mediaEnded() {
// Update the SystemMediaTransportControl state.
systemMediaControls.playbackStatus = Windows.Media.MediaPlaybackStatus.stopped;
}
For more info on the SystemMediaTransportControl, see How to use the system media transport controls and the SystemMediaTransportControls sample
Step 4: Register for media transport controls (Windows 8)
Important
The SystemMediaTransportControls class introduced in Windows 8.1 replaces the old MediaControl class. You should use the new SystemMediaTransportControls instead of MediaControl. See How to use the system media transport controls for more info on using the SystemMediaTransportControls.
Even if an app is registered to play music or video in the background, the app must handle events for play, pause, and play/pause buttons. By providing this minimal event handling support, you make it possible for the user to play or pause the music or video stream in the background without bringing the application to the foreground.
To register a media button with your app, you must first create a MediaControl object and add an event listener to the object. Then the object can listen for the events that you specify. You must also define a function that will be called to handle the event when the event is raised.
In the Solution Explorer pane, click your app’s JavaScript file to open it. For example, if the JavaScript file for your app is named MyApp.js, click that file to open it.
Use the following code to register for the Play, Pause, and Play/Pause toggle buttons for your app:
// Declare a variable that you will use as an instance of an object var mediaControls; // Assign the button object to mediaControls mediaControls = Windows.Media.MediaControl; // Add an event listener for the Play, Pause Play/Pause toggle button mediaControls.addEventListener("playpausetogglepressed", playpausetoggle, false); mediaControls.addEventListener(“playpressed”, playbutton, false); mediaControls.addEventListener(“pausepressed”, pausebutton, false);
Use the following code to handle the events that are raised when the Play, Pause, and Play/Pause toggle buttons are pressed:
// The event handler for the play/pause button function playpausetoggle() { if(mediaControls.isPlaying === true) { document.getElementById("audiotag").pause(); } else { document.getElementById("audiotag").play(); } } // The event handler for the pause button function pausebutton() { document.getElementById("audiotag").pause(); } // The event handler for the play button function playbutton() { document.getElementById("audiotag").play(); }
Remarks
For more information about how to work with media transport controls, see the System Transport Controls Developer Guide white paper.
Note If you have an app that performs other tasks in addition to streaming audio or video, then when the app loses focus and is no longer the active window, your app should stop doing non-media related work. Your app can still stream audio and, in the case of an audio-video stream, video streaming will stop automatically. Quickstart: playing video in an app
Complete example
For complete examples of how to stream audio and video, see the Playback manager sample and the HTML media playback sample.
Related topics
System Transport Controls Developer Guide