Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop a sound using the same button that plays it

Pretty simple, I'm using one button that generates a random number and then with a switch/case, it animates an image and plays a sound. My problem is that when you press the button again, the sound that was playing before doesn't stop and the sound overlaps.

Here's the code:

- (IBAction) pushme: (id) sender{
int random = (arc4random()%10);
switch (random) {
    case 0:  {
            [ANIMATION NUMBER 0]

            NSString *path = [NSString stringWithFormat:@"%@%@",[[NSBundle mainBundle] resourcePath],@"/sound0.wav"];
            SystemSoundID soundID;
            NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
            AudioServicesCreateSystemSoundID((CFURLRef)filePath, &soundID);
            AudioServicesPlaySystemSound(soundID);
        }
        break;
    case 1:  {
            [ANIMATION NUMBER 1]

            NSString *path = [NSString stringWithFormat:@"%@%@",[[NSBundle mainBundle] resourcePath],@"/sound1.wav"];
            SystemSoundID soundID;
            NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
            AudioServicesCreateSystemSoundID((CFURLRef)filePath, &soundID);
            AudioServicesPlaySystemSound(soundID);
    } break; //Lots more cases after this one

I know that this is not the best way to do it, declaring the same variable over and over. but is there a way to stop it before it plays another one?

like image 325
Nicolas Avatar asked Feb 25 '23 10:02

Nicolas


1 Answers

I just dicovered the answer to my own question.

What I did was

  1. Declare SoundSystemID soundID; in the header.
  2. Add this line before the random number gets generated: AudioServicesDisposeSystemSoundID(soundID);

Remember that if you are going to play the sound again, you will need to load the resource again after disposing of it.

Thank you guys, anyway.

like image 76
2 revs, 2 users 88% Avatar answered Mar 08 '23 16:03

2 revs, 2 users 88%