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

2016/4/18

sound keeps playing wont stop

Solidchainss Solidchainss

2016/4/18

#
I'm making a mp3 project for an assignment and it works when i press the play button, it just won't stop when I press it again. here's the code... 15 public void act() 16 { 17 play(); 18 stop(); 19 } 20 21 public void play() 22 { 23 GreenfootSound sound = new GreenfootSound("Fetty Wap - Trap Queen.mp3"); 24 if(Greenfoot.mouseClicked(this) == true) 25 { 26 sound.play(); 27 } 28 29 } 30 31 public void stop() 32 { 33 GreenfootSound sound = new GreenfootSound("Fetty Wap - Trap Queen.mp3"); 34 if(Greenfoot.mousePressed(this)) 35 { 36 sound.stop(); 37 } 38 } 39}
danpost danpost

2016/4/18

#
On line 33, you are creating a new GreenfootSound instance of the same song. This is not the instance that is already playing -- so stopping it will not stop the sound from playing. You need to keep a reference of the one that is playing and stop it:
1
2
3
4
5
6
7
// instance reference field (inside class but outside method)
private GreenfootSound sound;
 
// line 23
sound = new GreenfootSound("Fetty Wap - Trap Queen.mp3");
 
// line 33 - remove
Removing the preceding 'GreenfootSound' from line 23 allows 'sound' to refer to the instance field instead of creating a local variable with the same name as the instance field.
You need to login to post a reply.