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

2016/2/22

Playing Sound File Once and Stop

smcgee smcgee

2016/2/22

#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import greenfoot.*;
 
/**
 * This class defines a crab. Crabs live on the beach.
 */
public class Crab extends Actor
{
 
    public void act()
    {
        move(4);
 
        if (isAtEdge())
        {
            turn(-3);
            GreenfootSound sound = new GreenfootSound("applause_y.wav");
            sound.play();
            sound.stop();
 
        }
 
    }
}
Each time I run the posted code the sound file (applause) keeps running. How can I change the code so it only plays once. Thank you for your help.
danpost danpost

2016/2/22

#
First, move line 16 to outside the method. The Crab object will then always keep a reference to the one GreenfootSound object created (instead of creating multiple GreenfootSound object and having them play over the top of each other). Then, remove line 18. The 'play' method will have it play once. If the crab is still at the edge when the sound finishes, it will start again.
smcgee smcgee

2016/2/22

#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import greenfoot.*;
 
/**
 * This class defines a crab. Crabs live on the beach.
 *
 */
public class Crab extends Actor
{
    GreenfootSound sound = new GreenfootSound("applause_y.wav");
 
    public void act()
    {
        move(4);
 
        if (isAtEdge())
        {
            turn(-3);
            sound.play();
        }
 
    }
}
Your short lesson was exactly what I needed to understand why the scenario kept playing the sound file again and again. Thank you so much. It now works exactly as I want it to work.
You need to login to post a reply.