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

2025/2/16

GreenfootSound not acknowledging getVolume/setVolume?

Bennylit Bennylit

2025/2/16

#
I have a music track I want to fade out, and I thought I could accomplish this by using this code:
1
2
3
4
5
6
7
8
9
for (int i =0; i<danger.length; i++) {
                System.out.println("Before Volume: "+(danger[i].getVolume()!=0?danger[i].getVolume():"ignore"));
                if (danger[0].getVolume()>2) {
                    danger[0].pause();
                    danger[0].setVolume(danger[0].getVolume()-10);
                    danger[0].play();
                } else danger[0].stop();
                System.out.println("After Volume: "+(danger[i].getVolume()!=0?danger[i].getVolume():"ignore"));
            }
As you can see, it should slowly decrease the volume in intervals of 10. Well guess what? It doesn't. When I check the volume before and after it runs this code, it's the same. What's the problem here?
Super_Hippo Super_Hippo

2025/2/16

#
Iā€™m not sure what the danger array exactly is, but is it on purpose that you use
1
danger[i]
in some cases and
1
danger[0]
in others?
danpost danpost

2025/2/16

#
Bennylit wrote...
I have a music track I want to fade out, and I thought I could accomplish this by using this code: << Code Omitted >> As you can see, it should slowly decrease the volume in intervals of 10. ... When I check the volume before and after it runs this code, it's the same.
There is a coding issue here. You programmed the "fade" in a single for loop without any time constraints. In other words, the loop will complete its task in a single act step. Regardless of what it actually does, it will not take any time in doing it. You need an if statement where the loop starts (instead of a for statement). Also, a condition needs to be true for the action to occur. Maybe add a boolean field (called "fading", maybe) and have it set to true when you want the fading to start. Another thing is there are only 101 values that the volume can be. If you decreased the volume by just one every act step, it would face in less than two seconds. Okay, instead of the boolean, use an int field (called "fadeTimer", maybe). If its value is zero, then no fading takes place. Otherwise, decrease its value, as shown:
1
2
3
4
5
6
7
8
if (fadeTimer == 0 && true /** if time to start fading */) fadeTimer = 200; /
if (fadeTimer > 0 {
    fadeTimer--;
    if (fadeTimer%2 == 0) danger[0].setVolume(danger[0].getVolume()-1);
    if (fadeTimer == 0)
        danger[0].stop();
        ; /** proceed to whatever is next after music completely fades out */
}
You need to login to post a reply.