How can I stop the sound of AudioToolbox?

I have two different beep sounds. When I press one button, it should play one sound, when I press another, it should stop the first sound and play another, how can I do it?

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); } 
+4
source share
1 answer

You cannot stop the sound that is played through " AudioServicesPlaySystemSound ", but you can use " AVAudioPlayer " instead.

Keep a link to your “ AVAudioPlayer ” in your object, and then you can call “ stop ” when you need to stop 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]; } 
+3
source

Source: https://habr.com/ru/post/1468810/


All Articles