Windows 8 Audio playing in background - javascript

I have read previous posts on this and documents by microsoft but cannot seem to get my app to run Sound in the background. It plays 100% but when ever the app is then suspended the music also stops. I have added "Background Tasks" declarations selecting Audio and my audio tag looks like this
<audio id="musicplayr" msAudioCategory="BackgroundCapableMedia" controls="controls"><source src="song.mp3"/> </audio
and finally my javascript includes the references to MediaControls
var MediaControls = Windows.Media.MediaControl;
// Add event listeners for the buttons
MediaControls.addEventListener("playpressed", play, false);
MediaControls.addEventListener("pausepressed", pause, false);
MediaControls.addEventListener("playpausetogglepressed", playpausetoggle, false);
// Add event listeners for the audio element
document.getElementById("musicplayr").addEventListener("playing", playing, false);
document.getElementById("musicplayr").addEventListener("paused", paused, false);
document.getElementById("musicplayr").addEventListener("ended", ended, false);
and below in the code i have the event handlers
// Define functions that will be the event handlers
function play() {
document.getElementById("musicplayr").play();
}
function pause() {
document.getElementById("musicplayr").pause();
}
function playpausetoggle() {
if(MediaControls.isPlaying === true) {
document.getElementById("musicplayr").pause();
} else {
document.getElementById("musicplayr").play();
}
}
function playing() {
Windows.Media.MediaControl.isPlaying = true;
}
function paused() {
Windows.Media.MediaControl.isPlaying = false;
}
function ended() {
Windows.Media.MediaControl.isPlaying = false;
}
*Note musicplayr is the reference for the html5 tag
Any help appreciated why this is not working?

You also need an event handler for the stoppressed event. Without any of the four handlers--playpressed, pausepressed, playpausetogglepressed, and stoppressed--background audio won't be enabled. See http://social.msdn.microsoft.com/Forums/en-IN/winappswithhtml5/thread/2ca0c122-df31-401c-a444-2149dd3e8d68 on the MSDN forums where the same problem was raised.
.Kraig

Related

Can't stop the audio with Js

I have a problem with Javascript:
I want to stop the audio in a Js program when the game comes to an end. For this I define a variable "endGame" and I make it false, so that when I call it true in an event, the audio stops. But the problem is that the audio does not stop when this variable is set to true.
Here's the piece of code that I need some help with:
let endGame = false
main.addEventListener("click", (e) => {
themeSong.play()
if(endGame == true) {
themeSong.pause()
}
EventListeners will not be triggered when the variable change. You should do it manually.
let endGame = false;
main.addEventListener("click", (e) => {
themeSong.play();
});
// The function which updates the endGame variable and stop the audio
function fnEndGame() {
endGame = true;
themeSong.pause();
}
// You should call fnEndGame() to stop the game, DO NOT update the variable directly.
By using a custom event, and then throwing that event whenever you want, you can pause your music execution the moment you want to.
So instead of using an "endgame" variable, I suggest you throw a custom event named "supergame_endgame" and listen to that event, and halt all relevant audio's in that event listener.
See my comments in the code below for more explanation.
let audio = document.querySelector('audio');
let start = document.getElementById('play');
let stop = document.getElementById('stop');
/** simple starter of the sound **/
start.addEventListener('click', () => {
audio.play();
});
/** Event handler for own custom event, named `stop_my_audio_play`
* This will actually stop audio play, regardless from where the event `stop_my_audio_play` is
* cast from
*/
window.addEventListener('stop_my_audio_play', (e) => {
audio.pause();
});
/** Throw an event `stop_my_audio_play` with the attribute bubbles set to true
* So it can be caught at window level
*/
stop.addEventListener('click', () => {
stop.dispatchEvent(new Event('stop_my_audio_play', {bubbles:true}))
});
audio {
display:none;
}
<audio controls="controls" autobuffer="autobuffer" autoplay="autoplay" loop>
<source src="data:audio/wav;base64,UklGRhwMAABXQVZFZm10IBAAAAABAAEAgD4AAIA+AAABAAgAZGF0Ya4LAACAgICAgICAgICAgICAgICAgICAgICAgICAf3hxeH+AfXZ1eHx6dnR5fYGFgoOKi42aloubq6GOjI2Op7ythXJ0eYF5aV1AOFFib32HmZSHhpCalIiYi4SRkZaLfnhxaWptb21qaWBea2BRYmZTVmFgWFNXVVVhaGdbYGhZbXh1gXZ1goeIlot1k6yxtKaOkaWhq7KonKCZoaCjoKWuqqmurK6ztrO7tbTAvru/vb68vbW6vLGqsLOfm5yal5KKhoyBeHt2dXBnbmljVlJWUEBBPDw9Mi4zKRwhIBYaGRQcHBURGB0XFxwhGxocJSstMjg6PTc6PUxVV1lWV2JqaXN0coCHhIyPjpOenqWppK6xu72yxMu9us7Pw83Wy9nY29ve6OPr6uvs6ezu6ejk6erm3uPj3dbT1sjBzdDFuMHAt7m1r7W6qaCupJOTkpWPgHqAd3JrbGlnY1peX1h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X59fn9+f35+f35/gH+Af4B/gICAgICAgICAgICAgYCBgIGAgIGAgYGBgoGCgYKBgoGCgYKBgoGCgoKDgoOCg4KDgoOCg4KDgoOCg4KDgoOCg4KDgoOCg4KDgoOCg4KDgoOCg4KDgoOCg4KDgoOCg4KDgoOCg4KCgoGCgYKBgoGCgYKBgoGCgYKBgoGCgYKBgoGCgYKBgoGCgYKBgoGCgYKBgoGBgYCBgIGAgYCBgIGAgYCBgIGAgYCBgIGAgYCBgIGAgYCAgICBgIGAgYCBgIGAgYCBgIGAgYCBgExJU1RCAAAASU5GT0lDUkQMAAAAMjAwOC0wOS0yMQAASUVORwMAAAAgAAABSVNGVBYAAABTb255IFNvdW5kIEZvcmdlIDguMAAA" />
</audio>
<button id="play">Play</button>
<button id="stop">Stop</button>

AudioContext does not have a pause property?

I have used javascript Audio() before, but now I need to add some reverb effect in the audio and I am using reverb.js which uses the AudioContext api. I have the start property available, but no pause property? How do I pause or stop the audio??
Here is my code:
<script src="http://reverbjs.org/reverb.js"></script>
<script>
// 1) Setup your audio context (once) and extend with Reverb.js.
var audioContext = new (window.AudioContext || window.webkitAudioContext)();
reverbjs.extend(audioContext);
// 2) Load the impulse response; upon load, connect it to the audio output.
var reverbUrl = "http://reverbjs.org/Library/SaintLawrenceChurchMolenbeekWersbeekBelgium.m4a";
var reverbNode = audioContext.createReverbFromUrl(reverbUrl, function() {
reverbNode.connect(audioContext.destination);
});
// 3) Load a test sound; upon load, connect it to the reverb node.
var sourceUrl = "./sample.mp3";
var sourceNode = audioContext.createSourceFromUrl(sourceUrl, function() {
sourceNode.connect(reverbNode);
});
</script>
Play
Stop
Also, I tried using stop(), and it works, but when I fire start() after clicking on stop, the start() doesn't work. Can you you help me out with a solution??
You can use the suspend() and resume() methods of AudioContext to pause and resume your audio: https://developer.mozilla.org/en-US/docs/Web/API/AudioContext/suspend
One way to implement this with a single button for play/pause/resume, would be to add a function that controls the player state. For example:
let started = false;
function pauseOrResume() {
if (!started) {
sourceNode.start();
started = true;
document.getElementById("pauseButton").innerHTML = 'Pause';
} else if (audioContext.state === 'running') {
audioContext.suspend().then(function () {
document.getElementById("pauseButton").innerHTML = 'Resume';
});
} else if (audioContext.state === 'suspended') {
audioContext.resume().then(function () {
document.getElementById("pauseButton").innerHTML = 'Pause';
});
}
}
And replace your existing "Play" button with:
<a id="pauseButton" href="javascript:pauseOrResume()">Play</a>
This does the following:
If the audio hasn't yet been started, the link will say "Play".
If the user clicks "Play", the audio will start playing and the text of the link will change to "Pause".
If the user clicks "Pause" while the audio is playing, it will be paused, and the text of the link will change to "Resume".

How can I make an audio sound play only once using JQuery?

So I have a div that plays an mp3 sound when it is clicked. Instead of playin once. It continues to play over and over again. The snippet of code is:
$(".g-contain").click(function() {
audioElement.play();
});
This may be irrelevant but I figure I should show you the overall code:
/* set no cache */
$.ajaxSetup({ cache: false });
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', 'https://www.dropbox.com/s/k8xaglyd48vbnq1/pacman_chomp.mp3?dl=1');
audioElement.addEventListener('ended', function() {
this.play();
}, false);
$.getJSON("scripts/data", function(data) {
var html = [];
/* loop through array */
$.each(data, function(index, g) {
$(".container").append(
"<div class='g-details'><div class='name'>" +
g.name + "</div>);
// And finally my click call is here
$(".g-contain").click(function() {
audioElement.play();
});
Not sure why the mp3 file keeps playing when g-contain div is clicked
It's due to this code:
audioElement.addEventListener('ended', function() {
this.play();
}, false);
You attached an event listener to the audio element to re-play when the playing is ended. So once it's played (with click) it will play infinitely.
From the MDN ended event Reference:
ended
The ended event is fired when playback or streaming has stopped
because the end of the media was reached or because no further data is
available.
Just get rid of this code.

Toggle Play/Pause Youtube Video with external button

I have a template I'm building out using fullPage js to create sliding sections. The page supports video, but scroll and gestures are disabled when users scroll with the cursor on top of the video itself. Likewise, this behavior is observed on mobile.
To work around this, I'm using an empty div overlaying the youtube iframe. This solves the scrolling behavior, but I also lack the ability to directly control the youtube player. I've tried using the youtube API and jquery to fake being able to toggle play/pause with the empty div I have on top of the youtube player, but it's not working.
http://codepen.io/lumpeter/pen/XpayeB
The primary code for youtube is:
function onYouTubePlayerReady(playerId) {
ytplayer = document.getElementById("player");
ytplayer.addEventListener("onStateChange", "onPlayerStateChange");
}
function onPlayerReady(event) {
$('#video-button').click(function(event){
ytplayer.playVideo();
});
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING) {
$('#video-button').click(function(event){
ytplayer.pauseVideo();
});
}
else {
$('#video-button').click(function(event){
ytplayer.playVideo();
});
}
}
Can anybody tell why this isn't working? I have event listeners looking for changes and using a boolean to detect the state of the video to toggle play/pause, but for some reason this doesn't work like I anticipated.
===============UPDATE=================
I've also tried the following:
$(document).on('click', '#pauseVideo', function(){
player = new YT.Player('myVideo')
if (event.data == player.PlayerState.PAUSED) {
$('#myVideo').get(0).contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}','*');
}
if (event.data == player.PlayerState.PLAYING) {
$('#myVideo').get(0).contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}','*');
}
});
However, I get the error "Uncaught ReferenceError: YT is not defined."
As fullpage.js already does part of the job by adding ?enablejsapi=1 and loading the JS script of the API for you, then you only have to do this:
var player;
window.onYouTubeIframeAPIReady = function() {
player = new YT.Player('myVideo');
}
$(document).on('click', '#pauseVideo', function(){
$('#myVideo').get(0).contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}','*');
});
Reproduction online
Thanks Alvaro! Yeah I was overthinking the solution a bit with the youtube api. I just needed to use a boolean with a binary true/false statement. Super easy, should have seen it before. Again thanks for your help!
var player;
window.onYouTubeIframeAPIReady = function() {
player = new YT.Player('myVideo',{
events: { 'onStateChange': onPlayerStateChange }
});
}
var isPlaying = true;
$(document).on('click', '#pauseVideo', function(){
if ( isPlaying == true){
$('#myVideo').get(0).contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}','*');
isPlaying = false;
} else {
$('#myVideo').get(0).contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}','*');
isPlaying = true;
}
});

HTML5 Audio on an iPad/iPhone device stops when being touched

In order to get an HTML5 animation playing with sound on an idevice, I've made a div the size of the entire browser named "theScreen", and use the following code:
audioCont.prototype.iCrapLoadPlayThrough = function () {
if (this.supported) {
theScreen = document.getElementById("theScreen");
var self = this;
theScreen.addEventListener('touchstart', function(){self.iCrapClickedLoadPlayThrough();}, false);
return(1);
} else {
return(0); // Not supported
}
};
audioCont.prototype.iCrapClickedLoadPlayThrough = function () { // Check if supported, then load the audio file
var self = this;
theScreen.removeEventListener('touchstart', function(){self.iCrapClickedLoadPlayThrough();}, false);
this.addCanPlayThrough();
this.load();
}
Now this works, and the sound/animation starts when the user taps on the screen. The problem is, if they tap on it again the sound stops, and each repeat tap you hear a few ms of audio. Does anyone know why?
It's not removing the event listener because it's an anonymous function. Remove the anonymous function and just have the function name instead
theScreen.addEventListener('touchstart',self.iCrapClickedLoadPlayThrough,false)
theScreen.removeEventListener('touchstart',self.iCrapClickedLoadPlayThrough,true)
I've found a solution to the problem:
theScreen.addEventListener('touchstart', eventID=function() {self.iCrapClickedLoadPlayThrough();}, false);
then
theScreen.removeEventListener('touchstart', eventID, false);

Categories