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

2021/8/18

playing sound error

alex_rimbu alex_rimbu

2021/8/18

#
can somebody please tell me what's wrong here? it displays an error saying sound is an "undeclared variable" import greenfoot.*; public class MyWorld extends World { public MyWorld() { super(600, 400, 1); GreenfootImage bg = new GreenfootImage("ocean_background.jpg"); bg.scale(getWidth(), getHeight()); setBackground(bg); for (int i = 0; i < 20; i++) { Fish temp = new Fish("red"); int x = Greenfoot.getRandomNumber(getWidth()); int y = Greenfoot.getRandomNumber(getHeight()); addObject(temp, x, y); sound = new GreenfootSound("aquarium.wav"); sound.playLoop(); } } }
rocket770 rocket770

2021/8/19

#
Looking at the code "sound" Is just the name of a variable, you never actually declare it. Replace the 17th line " sound = new GreenfootSound("aquarium.wav");" to "GreenfootSound sound = new GreenfootSound("aquarium.wav")" It probably wont make too much of a difference, but there's also no need to instantiate a new GreenfootSound object every iteration in the for loop, rather you may move only that line of code outside the for loop.
alex_rimbu alex_rimbu

2021/8/19

#
That worked, thanks!
You need to login to post a reply.