I am actually really hoping this is a noob question. Have looked around and tried for about an hour for a solution to this but I'm getting nowhere.
Real simple. I am using Cordova to build Android App. I am going through my code and trying to clean it up and make it more reusable.
I have several views/pages that play audio files. I am using the Cordova media api as HTML5 audio is not well supported.
Anyway, I use JQuery to get the ID of heading tag and then combine it with another string to make a variable. Then I am trying to use that variable to be the source for a "new Media" object. I am definitely missing something here, because it is not working and is returning null. My code is pasted below:
var playing = 0;
var myMedia = null;
var mySound = $("h3").attr("id");
var soundPath = "/android_asset/www/audio/"+mySound+".mp3";
myMedia = new Media('"'+soundPath+'"', stopAudio);
function playAudio() {
switch (playing) {
case 0:
myMedia.play();
document.getElementById('play').src = "../icons/pause-btn-grey#2x.png";
playing = 1;
break;
case 1:
myMedia.pause();
document.getElementById('play').src = "../icons/play-btn-grey#2x.png";
playing = 0;
break;
}
I would really appreciate if someone could point me in the right direction. I am sure it is something I have overlooked but cannot "see the wood from the trees".
Related
I am programming a multi-player game with JavaScript and html. For this objective I need communication between the players. How can I manage this?
My code:
enchant();
window.onload = function() {
var game = new Game(320, 320);
Here my first question: It should be counted how many player is that now, who entered the room last. Then a number should be assigned to this player. I´d like to solve this with a function.
var my_bear = get_player_number();
game.preload('chara1.gif');
game.fps=15;
var bears = [];
game.onload = function() {
var ix;
var bear;
for (ix = 0; ix < 5; ix++) {
bear=new Sprite(32, 32);
bear.image = game.assets['chara1.gif'];
bear.frame = 4;
bear.x=Math.random()*300;
bear.y=Math.random()*300;
game.rootScene.addChild(bear);
bears.push(bear);
}
};
game.start();
var addit=6;
document.addEventListener('keyup',function (evt) {
if(evt.keyCode == 38){bears[my_bear-1].y-=addit;}
if(evt.keyCode == 39){bears[my_bear-1].x+=addit;}
if(evt.keyCode == 40){bears[my_bear-1].y+=addit;}
if(evt.keyCode == 37){bears[my_bear-1].x-=addit;}
});
}
Due to this simplification of my programme you have 5 bears. One of them you can control with the arrow-keys (the bear with the value of the variable “my_bear”).
But it´s still a single-player game yet...
init_other_players(my_bear);
A function would be perfect, which detects and indicates any movement of a player on an other computer.
Webspace an two domains are available for my programme.
I´m very looking forward to your helpful answer, thank you !!!
First, if you want multiplayer, you need something to manage the rooms and such, so you need a server. For games, I'd suggest NodeJS. Node is a server app built in JS, so a language you are familiar with. You don't need to know too much about node for now, simply running it will be enough while you progress on your code, after that I'd say you should look a bit more into it.
After, I'd look into Socket.io which lets you manage your websockets and therefore communication between the users and the server. There are tutorials about a chat in the Get Started section of the website which will you let you know the basics of communication between users.
From there you can create the logic for your rooms and the rest of your game! It may look like a lot to learn but, honstly, it's well explained and quite easy to get a grasp of.
In my app a user can choose to store their input into an array for eg.
"[{"time":1835,"elemId":"bass"},{"time":2553,"elemId":"highhat"}]"
This is well and good apart from when I'm trying to replay their input using the example information above.
I think the trouble is I'm using a plugin called LowLatencyAudio which is installed via phonegap which makes things a bit complicated for me.
So instead of trying to 'mimic' the user's input I'd rather just play the .mp3 files that are attached to each button.
This is the code I'm using at the moment with no avail
document.getElementById('playback').onclick = function () {
console.log(localStorage.getItem("eventlist"));
var playback = JSON.parse(window.localStorage.getItem("eventlist"))
for (i = 0; i < playback.length; i++) {
play = playback[i];
setTimeout((function (play) {
return function () {
lla.play();
}
})(play), play.time)
}
}
Which returns the error
Uncaught TypeError: Cannot call method 'play' of undefined.
I'll put in the button and the function I'm trying to call for good measure but I just can't seem to find a result, any help would be appreciated, thank you.
Button
<div class="drum" id="bass" ontouchstart="play('bass');" ontouchend="touchEnd(event);">Bass</div>
Play function
function play(drum) {
document.getElementById(drum).className = 'drum touched';
lla.play('assets/' + drum + '.mp3');
}
I very new to javascript and I would like to process some images in Fiji. I have been using the macro language for a while, but I am trying to get familiar with the formal ImageJ/Fiji API. I am trying to run the folowing simplistic piece of code, it runs with no errors but it does not show any image in the end. What's going wrong?
importClass(Packages.ij.plugin.filter.GaussianBlur);
var image = IJ.openImage("/home/.../KNIIC_BC_Cam2_AirBubble2_Image1038.bmp");
IJ.run(image, "8-bit", "");
var dpl = image.getProcessor().duplicate();
var gs = new GaussianBlur();
gs.blur(dpl,20);
new ImagePlus(gs).show();
Thanks in advance
The problem is the way how you deal with the ImagePlus: in the last line, you try to create a new ImagePlus, but there is no chance that this contains any information of your loaded image.
GaussianBlur processes an ImageProcessor that you'll get via the ImagePlus#getProcessor() method. If you look at the API documentation, you'll also see that blur(ImageProcessor,double) is deprecated in favor of one of the other methods: you might want to use blurGaussian(ImageProcessor, double, double, double)here.
This code would work:
importClass(Packages.ij.plugin.filter.GaussianBlur);
var imp = IJ.openImage("http://imagej.nih.gov/ij/images/clown.jpg");
IJ.run(imp, "8-bit", "");
var ip = imp.getProcessor();
var gs = new GaussianBlur();
gs.blurGaussian(ip,20,20,0.01);
imp.show();
however it uses the low level way of interfering with the GaussianBlur class. To make your life easy, you can also record the javascript command in the GUI via Plugins > Macros > Record... and then choosing Record: Javascript before performing the Gaussian blur via Process > Filters > Gaussian Blur.... This would make your code much shorter:
var imp = IJ.openImage("http://imagej.nih.gov/ij/images/clown.jpg");
IJ.run(imp, "8-bit", "");
IJ.run(imp, "Gaussian Blur...", "sigma=20");
imp.show();
For general help with Javascript scripting in ImageJ, see these two links to the Fiji wiki.
Edit: Starting from ImageJ 1.47n5, ImageProcessor has a new method blurGaussian(double sigma), shortening the above (low level) code to:
var imp = IJ.openImage("http://imagej.nih.gov/ij/images/clown.jpg");
IJ.run(imp, "8-bit", "");
imp.getProcessor().blurGaussian(20);
imp.show();
No idea what I'm doing or why it isn't working. Clearly not using the right method and probably won't use the right language to explain the problem..
Photogallery... Trying to have a single html page... it has links to images... buttons on the page 'aim to' modify the path to the images by finding the name currently in the path and replacing it with the name of the gallery corresponding to the button the user clicked on...
example:
GALLERY2go : function(e) {
if(GalleryID!="landscapes")
{
var find = ''+ findGalleryID()+'';
var repl = "landscapes";
var page = document.body.innerHTML;
while (page.indexOf(find) >= 0) {
var i = page.indexOf(find);
var j = find.length;
page = page.substr(0,i) + repl + page.substr(i+j);
document.body.innerHTML = page;
var GalleryID = "landscapes";
}
}
},
There's a function higher up the page to get var find to take the value of var GalleryID:
var GalleryID = "portfolio";
function findGalleryID() {
return GalleryID
}
Clearly the first varGalleryID is global (t'was there to set a default value should I have been able to find a way of referring to it onLoad) and the one inside the function is cleared at the end of the function (I've read that much). But I don't know what any of this means.
The code, given its frailties or otherwise ridiculousness, actually does change all of the image links (and absolutely everything else called "portfolio") in the html page - hence "portfolio" becomes "landscapes"... the path to the images changes and they all update... As a JavaScript beginner I was pretty chuffed to see it worked. But you can't click on another gallery button because it's stuck in a loop of some sort. In fact, after you click the button you can't click on anything else and all of the rest of the JavaScript functionality is buggered. Perhaps I've introduced some kind of loop it never exits. If you click on portfolio when you're in portfolio you crash the browser! Anyway I'm well aware that 'my cobbled together solution' is not how it would be done by someone with any experience in writing code. They'd probably use something else with a different name that takes another lifetime to learn. I don't think I can use getElement by and refer to the class/id name and parse the filename [using lots of words I don't at all understand] because of the implications on the other parts of the script. I've tried using a div wrapper and code to launch a child html doc and that come in without disposing of the existing content or talking to the stylesheet. I'm bloody lost and don't even know where to start looking next.
The point is... And here's a plea... If any of you do reply, I fear you will reply without the making the assumption that you're talking to someone who really hasn't got a clue what AJAX and JQuery and PHP are... I have searched forums; I don't understand them. Please bear that in mind.
I'll take a stab at updating your function a bit. I recognize that a critique of the code as it stands probably won't help you solve your problem.
var currentGallery = 'landscape';
function ChangeGallery(name) {
var imgs = document.getElementsByTagName("img") // get all the img tags on the page
for (var i = 0; i < imgs.length; i++) { // loop through them
if (imgs[i].src.indexOf(currentGallery) >= 0) { // if this img tag's src contains the current gallery
imgs[i].src = imgs[i].src.replace(currentGallery, name);
}
}
currentGallery = name;
}
As to why I've done what I've done - you're correct in that the scope of the variables - whether the whole page, or only the given function, knows about it, is mixed in your given code. However, another potential problem is that if you replace everything in the html that says 'landscape' with 'portfolio', it could potentially change non-images. This code only finds images, and then replaces the src only if it contains the given keyword.
Trying to play a sound via javascript and want to change it dynamically using sessionstorage
The following is a simplified version that plays sound/s in android/FF Linux/Win when u click the "sprite me button" - I've included other buttons for the example to set and retrieve session values in HTML5.
http://globability.org/webapp/asprite20111124_8.html
The wiki below has Android phone specs where it works: (Samsung Galaxy SII) in case you're interested
http://globability.org/wiki/doku.php?id=current_working_specs_p-tab / also see http://globability.org/wiki/doku.php?id=mobile_pointing_tablet to get a proper idea about what it is that I am working on.
What I need is to have the "play soundsprite" javascript that you can see below in the following section load from sessionstorage and insert values loaded from sessionstorage inserted into an array.
I am not looking for any changes is how the sound is played back - just need to make a dynamically built array work from within the particular javascript.
The code below is based on the soundsprite idea from www.phpied.com/audio-sprites/ by Stoyan Stefanov - made to reduce the http calls needed for playing sounds... Also stabilizes the sound quality, less choppy sound etc.
Antway here goes: YOU ONLY NEED TO LOOK AT PSEUDOCODE SECTION - The rest is functioning
<script>
var thing = 'the thing';
function shut() {
if (typeof thing.pause !== 'undefined') {
thing.pause();
}
}
function log(what) {
document.getElementById('log').innerHTML += what + "<br>";
}
var spriteme = function(){
var sprites = {
// id: [start, length]
'blank':[0.1, 0.5], //This the first sprite, it has to be the first defined and is
called first, it is a blank piece of sound in the combined sound file and needed as of
now.
'success':[13, 2,5],
/* I would like to be able to set the parameters i.e. sound bite to play dynamically -
here a pseudocode example using session storage in preparation for getting the sound
parameters from a database
'wordgen'[null,null];
//this array should be dynamically built from values read from the two session storage keys not sure you need the new thing in HTML5
sessionStorage.globabilitykey1;
sessionStorage.globabilitykey2;
strkey1=globabilitykey1
strkey2=globabilitykey2
var gkey1=parsefloat(strkey1)
var gkey2=parsefloat(strkey2)
'wordgen':[gkey1,gkey2]
and then the idea is to replace the array success in the script with the "generated"
array 'wordgen' to allow dynamic seting of sound to play back */
//the following are sound bites from the collection of soundsprites the site plays from
'word1': [0.5, 2,36], //one
'word2': [3.1, 3.0], //two
'word3': [7.0, 1.82], //three
'word4': [10.03, 2], //four ?
},
song = ['blank', 'success'],
//here you're setting the playback sequence (this is where I would like to replace 'success' with 'wordgen'
current = 0,
id = song[current],
start = 0,
end = sprites[id][1],
int;
thing = document.getElementById('sprite');
thing.play();
log('file: ' + thing.currentSrc);
log(id + ': start: ' + sprites[id].join(', length: '));
// change
int = setInterval(function() {
if (thing.currentTime > end) {
thing.pause();
if (current === song.length - 1) {
clearInterval(int);
return;
}
current++;
id = song[current];
start = sprites[id][0];
end = start + sprites[id][1]
thing.currentTime = start;
thing.play();
log(id + ': start: ' + sprites[id].join(', length: '));
}
}, 10);
};
</script>
Any ideas on how to dynamically create the 'wordgen' array within the javascript based on the values is sessionstorage ?
The whole code/working example can be seen here: http://globability.org/webapp/asprite20111124_8.html
I know the page is one ugly mess... but this is an alpha prototype :)
Argh... it was sooooo simple, I was this close to solving it myself, however a kind freelancer at freelancer.com who has perviously helped me getting one of my ideas to work did it again this time...
And without further ado:
'wordgen':eval("["+sessionStorage.globabilitykey1+","+sessionStorage.globabilitykey2+"]"),
That was what I needed - I had been trying to do the same but without the " eval " in front and the paranthesis around the arguments....
Oh and don't forget to set the value by clicking the button before you try or there will be no sound coming out of your speakers ;)
Here's a link to the working page if you care to try and if you want to see the code in it's "entirity": http://globability.org/webapp/asprite20111201_2.html - Thanks to those of you voting the question up!!!