Why Background Audio Isn’t Working?

27/12/2012

Using HTML 5 we can play audio very easily in your Windows Store app, all you need to do is setting an audio element specify the object properties and that’s it.

var audioElement= document.createElement('audio'); 
audioElement.setAttribute("id", "audtag"); 
audioElement.setAttribute("controls", "true"); 
audioElement.setAttribute("src", fileToPlay); 
audioElement.setAttribute("autoplay", "true"); 
audioElement.load();

What if you want to keep playing this audio even if the user has switch to another application?

In order to to that you’ll need to use “Background Audio” ability.

First you need to declare the “Background Tasks” in your app package manifest file.

image

Then you need to add the “msAudioCategory” attribute to the audio element:

audtag.setAttribute("msAudioCategory", "BackgroundCapableMedia");

Now if you run the application you’ll hear the audio playing but once you navigate to another app the audio will stop.

The reason is, you must specify MediaControl event in order to allow Background Audio.

var mediaControl = Windows.Media.MediaControl;  
mediaControl.addEventListener("playpausetogglepressed", function () { }, false); 
mediaControl.addEventListener("playpressed", function () { }, false); 
mediaControl.addEventListener("stoppressed", function () { }, false); 
mediaControl.addEventListener("pausepressed", function () { }, false);

Now if you run your app that audio will keep on playing even if you switch to another application.

Full Code:

var mediaControl = Windows.Media.MediaControl;
// These are necessary to play streams of type 'backgroundCapableMedia'
mediaControl.addEventListener("playpausetogglepressed", function () { }, false);
mediaControl.addEventListener("playpressed", function () { }, false);
mediaControl.addEventListener("stoppressed", function () { }, false);
mediaControl.addEventListener("pausepressed", function () { }, false);

var audtag = document.createElement('audio');
audtag.setAttribute("id", "audtag");
audtag.setAttribute("controls", "false");
audtag.setAttribute("msAudioCategory", "BackgroundCapableMedia");
audtag.setAttribute("src", source);
audtag.setAttribute("autoplay", "true");
audtag.load();
Add comment
facebook linkedin twitter email

Leave a Reply