Question

I have two different button press sound actions. When I press one button it should play one sound, when I press the other, it should stop the first sound and play the other, How can I do this?

Thanks,

-(void) onButtonPressAlbina {
    [soundID2 stop];     
    NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"albina" ofType:@"m4a"];
    SystemSoundID soundID;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath: soundPath], &soundID);
    AudioServicesPlaySystemSound (soundID);
}

-(void) onButtonPressBalena {
    NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"balena" ofType:@"m4a"];
    SystemSoundID soundID;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath: soundPath], &soundID);
    AudioServicesPlaySystemSound (soundID);    
}
Was it helpful?

Solution

You can't stop a sound that's playing via "AudioServicesPlaySystemSound", but what you can do is use "AVAudioPlayer" instead.

Keep a reference to your "AVAudioPlayer" in your object and then you can call "stop" on it when you need to halt it.

Play

#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVAudioPlayer.h>
AVAudioPlayer  *player;

// ...

NSString *path;
NSError *error;
path = [[NSBundle mainBundle] pathForResource:@"albina" ofType:@"m4a"];
if ([[NSFileManager defaultManager] fileExistsAtPath:path]) 
{    
  player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error];
  player.volume = 0.5f;
  [player prepareToPlay];
  [player setNumberOfLoops:0];
  [player play];    
} 

Stop

if (player != nil)
{
  if (player.isPlaying == YES)
    [player stop];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top