Audio.play() doesn't work ONLY in if statement - javascript

So I am making a small game to practice javascript. I wanted to add the getting point sound when the car is not crashing with the obstacle. If the car is not crashing with obstacles, I am adding points and making the obstacle disappear and appearing once again at the top of the road so everything is working fine. Under those lines, I added the audio.play(); function and it is not working. I added the alert to check if it should work and the alert is appearing so what is going on?
else if(document.getElementById("B7").innerHTML == '<div id="obstacle">X</div>' || document.getElementById("A7").innerHTML == '<div id="obstacle">X</div>')
{
document.getElementById("A7").innerHTML = "";
document.getElementById("B7").innerHTML = "";
points = points + addPoints;
audio.play();
alert("sound here");
nextObstacle();
}
Link for GitHub repository for this project:
https://github.com/AdamMaichrzik/Spliterio/blob/master/car.html
Lines 270 - 280.

Ok, so I googled more about this problem and it turns out that some of web browsers are blocking playing sound without previously clicking any button or something like that to play the sound. You HAVE TO first CLICK some button to play the sound and then it can be played in loops etc. So I just added play sound while selecting difficulty and it is working when the car is not crashing.

Related

Audio playing on image click using js/jquery, but not working in some web browsers?

I used some code from this thread to create a website where a randomly selected sound plays on image click: Play random sounds without repeat. It was important to me that the sounds do not repeat until the entire series has been cycled through, which is why I went with this solution: http://jsfiddle.net/cbuckley/FdLge/
It works like a charm in Google Chrome, but for some reason it doesn't seem to play the audio in other web browsers like Safari. I knew it would not work on mobile, but I was not expecting this. Any ideas what I can do to resolve it?
This is my site, for reference: http://comfortinajar.com/
the html is as follows:
<div id="element"></div>
<img src="Images/Screen.jpg" id=test>
and the script is:
<script>
var sounds = [];
// Return the full list of URLs in random order
function getSounds() {
return [
'Audio/Comfort1.mp3',
'Audio/Comfort2.mp3',
'Audio/Comfort3.mp3',
'Audio/Comfort4.mp3',
'Audio/Comfort5.mp3',
'Audio/Comfort6.mp3',
'Audio/Comfort7.mp3',
'Audio/Comfort8.mp3',
'Audio/Comfort9.mp3',
'Audio/Comfort10.mp3',
'Audio/Comfort11.mp3',
'Audio/Comfort12.mp3',
'Audio/Comfort13.mp3',
'Audio/Comfort14.mp3',
'Audio/Comfort15.mp3',
"Audio/Comfort16.mp3",
"Audio/Comfort17.mp3",
"Audio/Comfort18.mp3"].sort(function () {
// http://stackoverflow.com/a/18650169/283078
return (.5 - Math.random());
});
}
// Play the next sound
function playSound() {
if (!sounds.length) {
// Get the list of sounds (random order)
sounds = getSounds();
}
// Pops a URL every time, ensuring all are played exactly once
$("#element").html(
'<embed src="' + sounds.pop() +
'" hidden="true" autostart="true" />'
);
// Once all the URLs have been popped, the array is repopulated
}
$('#test').click(playSound);
</script>
The code also currently causes a page jump where the div tag is (at the very bottom of the page) the first time that it is loaded, and a block of white remains there after that, and the first sound loaded fades in for some reason (reducing audibility), but I am less concerned with those problems. All I really care about is making the sound work in all browsers. Let me know if you can help!

Animate CC gotoAndStop for HTML5 Canvas

I'm trying to create a simple plant collecting game. When you click all the plants, game ends and sends you to third frame.
1st frame, start button (just wrote start, didn't try to add navigation yet)
2st frame, game area.
3st frame, game over text.
When I start the animation, it passes through 1st frame and comes to second. I've written "stop()" at top of this frame so we can play now.
var kalanMeyve = 7;
// this fruit instance, click event, bind same function but remove yourself (this.instance)
this.ananas.addEventListener("click", fl_MouseClickHandler.bind(this.ananas));
this.armut.addEventListener("click", fl_MouseClickHandler.bind(this.armut));
this.cilek.addEventListener("click", fl_MouseClickHandler.bind(this.cilek));
this.domates.addEventListener("click", fl_MouseClickHandler.bind(this.domates));
this.kirmizibiber.addEventListener("click", fl_MouseClickHandler.bind(this.kirmizibiber));
this.muz.addEventListener("click", fl_MouseClickHandler.bind(this.muz));
this.sogan.addEventListener("click", fl_MouseClickHandler.bind(this.sogan));
function fl_MouseClickHandler() {
this.parent.removeChild(this);
kalanMeyve--;
if(kalanMeyve == 0)
{
//alert here works when game over
}
}
All instances, variables etc. are correct. In fact, when I try to check if my if statement working, it works. I can put an alert when the game is over. But can't navigate to another frame.

SoundJS music clips should toggle each other on/off

I have a bunch of sounds on a page, similar to the sound grid example. Some of these tracks are music tracks and I'd like to treat them differently. Most of the sounds can play over each other and that is the intent, however, no music track should be able to play over another music track. Think radio buttons.
I've got some very woolly code that detects if the other track is playing when clicked and stops the track, and switches that track's css (play icons and such). But now, adding a 3rd or 4th track to the mix becomes unruly.
sounds are loaded and stored in a hash of reusable sound instances that look like:
mySounds["sound1"]= createjs.Sound.createInstance("sound1");
...
when the button in the html is clicked on (I'm not currently using the data-type attribute, that was from an earlier attempt but I thought it might be useful):
<button type="button" class="btn btn-vol btn-sm" data-type="music" data-track="music1" onclick="play(this)">
<span class="glyphicon glyphicon-play bplay"></span></button>
I currently do:
function play(target) {
//define some stuff from html
musicTrack = $(target).attr('data-track');
music1 = $('button[data-track="music1"]');
music2 = $('button[data-track="music2"]');
myInstance = mySounds[id] //id is defined elsewhere
toggle = $(target).find('span.bplay'); //this is where I have the play/pause icons
//For all cases, not just music I find the play icon and swap it.
if(toggle.hasClass('glyphicon-play')){ //the sound is ready to play. if it had a stop icon it would mean it was already playing
toggle.removeClass('glyphicon-play');
toggle.addClass('glyphicon-stop')
//special case for music Tracks
if(musicTrack == "music1") { //If I clicked on music track 1
if(mySounds[musicTrack2].position !=0){ //if it isn't 0, it's playing!
music2.find('span.bplay).removeClass('glyphicon-stop');
music2.find('span.bplay').addClass('glyphicon-play');
mySounds[musicTrack2].stop();
}
else {
//do nothing because track 2 isn't playing
}
} else if (musicTrack=="music2"){ //If I clicked on music track 2
if(mySounds[musicTrack2].position !=0){
music1.find('span.bplay').removeClass('glyphicon-stop');
music1.find('span.bplay').addClass('glyphicon-play');
mySounds[musicTrack1].stop();
}
else {
//do nothing because track 1 isn't playing
}
myInstance.play(); // play the clicked on instance
}
else {
//if the glyphicon does not say play (says stop) then we stop the sound etc..
toggle.removeClass('glyphicon-stop');
toggle.addClass('glyphicon-play');
myInstance.stop();
}
}
I haven't checked the above for syntax as I copied it by hand from my code, keeping only the relevant bits, but all this works. I click on music1, if music 2 isn't playing - it plays. If music 2 is playing, it stops music 2, switches it's stop icon to play and plays music 1. My actual code does some tweening of the sounds before it stops so they crossfade nicely.
I'm not a programmer but I'd love to be able to do this in a more efficient/elegant manner. Surely there is a way!
A better way to do this would be give the music buttons a different click handling function, and using a app / global variable to track the currently playing music. Then use the icon to determine behavior. You'd need to add a way to get the currently playing music, possible another variable. Something like this:
var currentMusic;
function playMusic(target) {
//define some stuff from html
musicTrack = $(target).attr('data-track');
myInstance = mySounds[id]; //id is defined elsewhere
toggle = $(target).find('span.bplay'); //this is where I have the play/pause icons
//For all cases, not just music I find the play icon and swap it.
if(toggle.hasClass('glyphicon-stop')){
toggle.removeClass('glyphicon-stop');
toggle.addClass('glyphicon-play');
currentMusic = null;
myInstance.stop();
}
else {
if(currentMusic) {
// get current instance and call stop
currentMusic.addClass('glyphicon-play');
currentMusic.removeClass('glyphicon-stop');
}
toggle.removeClass('glyphicon-play');
toggle.addClass('glyphicon-stop');
currentMusic = toggle;
myInstance.play();
}
}

Flash CC Canvas HTML5 Element adding interactivity in Timeline

I've been trying to solve this for several time, but I'm now pointless with this situation. I'm creating a HTML5 canvas project in Flash CC, I'm kinda new in JS (not difficult BTW), the point is, I have around 10 keyframes inside my main timeline, and some classic buttons, all I need to do is to navigate inside every frame when a button is pressed (pretty easy uh!) the trouble is, the first frame works perfectly, but from 2 to the others, I can't be able to use buttons, interactivity is being programmed as follows:
var self = this;
this.stop();
this.btn4.addEventListener("click", clickUno);
function clickUno() {
self.gotoAndPlay(1);
}
Any help will be really appreciated, I just don't know why 1st frame works great, but others doesn't!
I had similar issues with canvas with flash.
I needed to created completed new buttons on every instance you need a button to get code to work. (ODD I know.)
Button code.
this.getinsideIt.addEventListener("click", fl_ClickToGoToAndPlayFromFrame_9.bind(this));
function fl_ClickToGoToAndPlayFromFrame_9()
{
this.Mygreatmovie.gotoAndPlay(350);
}
As I understand, you need a button, clicking on which proceeds your animation 1 frame at a time. Correct?
You should make use of the currentFrame and totalFrames properties of the main stage for this. Query the current frame and move on to next!
var self = this;
this.stop();
if(!this.btn4.hasEventListener("click", clickUno))
this.btn4.addEventListener("click", clickUno);
function clickUno(e) {
var curr = self.currentFrame;
var total = self.totalFrames;
self.gotoAndStop((curr + 1)%total);
}

JWPlayer 4 javascript events are ignored

First of all, I can't upgrade to a newer version of the player, because I need the displayclick=fullscreen option to work, and it doesn't with version 5.
So, what I need to do is this: have the player auto-start with no volume and no controls on the page (this works just fine), and when the user clicks the screen the player must go full-screen and the volume must turn on.
The problem is all Javascript interaction seems to be completely ignored by the player, and I really can't see where the problem is.
When the page is loaded, I embed the player:
var so = new SWFObject('path_to_player.swf','div_id','200','120','10');
so.addParam('allowfullscreen','true');
so.addParam('allowscriptaccess','sameDomain');
so.addParam('bgcolor','#000000');
so.addParam('flashvars','file=path_to_playlist.xml&autostart=true&displayclick=fullscreen&controlbar=none&volume=0&icons=false&image=path_to_thumb.jpg');
so.write('div_id');
This seems to work just fine, the player is loading.
Then I add the event listeners:
var player = null;
function playerReady(p) {
player = document.getElementById(p.id);
addListeners();
}
function addListeners() {
if (player) {
console.log('add the listener');
console.log(player.getConfig().volume);
player.addControllerListener("RESIZE", "checkResize");
} else {
setTimeout("addListeners()", 100);
}
}
function checkResize(obj) {
console.log('resized');
if (obj.fullscreen) {
player.sendEvent("VOLUME", "60");
} else {
player.sendEvent("VOLUME", 0);
}
}
The "add the listener" message gets displayed in the console, but the second one, with the player's volume doesn't, and neither does the "resized" one when the player enters or exits fullscreen (and, obviously, the volume doesn't turn on).
I've tried other listeners, for both model and controller, and they don't seem to work. Sending events doesn't work either.
I've tried running just the code for the player separately, to make sure there are no other things interfering with the code, but I still have the same problem.
Well, it seems I've found the answer myself. Upgrading to a newer version of swfobject and using swfobject.embedSWF() seems to work just fine.

Categories

Resources