This site requires JavaScript, please enable it in your browser!
Greenfoot back
HTown_Diva
HTown_Diva wrote ...

2015/4/27

Using the arrow keys to play a music file

HTown_Diva HTown_Diva

2015/4/27

#
I need to write a java statement that will play “hello.wav” when the up arrow key is pressed but I'm not sure where to start since I've never used the arrow keys in a program. Please help! I do know I need to write Greenfoot.playSound("hello.wav");
lordhershey lordhershey

2015/4/27

#
if(Greenfoot.isKeyDown("up"))
{
  ...
}
Maybe this, but a problem is that is will just play hello a million times over again (over lapping and the like) this might work:
if(Greenfoot.getKey().compareTo("up") == 0)
{
  ...
}
azazeel azazeel

2015/4/27

#
public void act() { if(Greenfoot.isKeyDown("up") Greenfoot.playSound("hello.wav"); } please first learn the example that available everywhere including in this website even we will try to answer all of questions and discussions
danpost danpost

2015/4/27

#
Yes, lordhershey (and @azazeel as well), the sould will play on top of itself many times with 'if (... isKeyDown...)' -- unless you back it up with another condition (like using a boolean that tracks the current state of the key). @lordhershey, your second attempt will fail because you will be calling 'compareTo' on a 'null' value (until the key is pressed and released -- but, the error will occur immediately upon starting the scenario). Better to use the following:
if ("up".equals(Greenfoot.getKey()))
as the String value, "up", will never be null and you can call 'equals' on it forever without any problems.
lordhershey lordhershey

2015/4/27

#
Hi Dan, I believe CompareTo is used correctly Java SE 7 String Class , returns 0 if the stings are the same, the function can return -1, 0, or 1.
azazeel azazeel

2015/4/27

#
if(("up").compareTo(Greenfoot.getKey()) == 0)
lordhershey lordhershey

2015/4/27

#
Oh I think I misunderstood - Greenfoot.getKey() can be null thus calling compareTo on it would cause an exception.
You need to login to post a reply.