Your implementation for playing audio samples does not allow for this. Because you are using AudioServicesPlaySystemSound from the AudioToolbox framework, there is no way to stop playback once the audio sample is triggered. You can only get a callback once it has finished playing.
This way of playing sounds has other limitations also (taken from the docs)
In addition, when you use the AudioServicesPlaySystemSound function:
Sounds play at the current system audio volume, with no programmatic
volume control available
Sounds play immediately
Looping and stereo positioning are unavailable
Simultaneous playback is unavailable: You can play only one sound at a
time
The sound is played locally on the device speakers; it does not use
audio routing.
To have control over stopping the sound once triggered, you'll need to use another API. For a high level API try AVAudioPlayer class from AVFoundation framework. You will then be able to hook up events from a button such as touch down
to start playing the sound, and also events such as touch up inside
and touch drag outside
to stop the sound playing.
You may or may not encounter performance issues depending on what else you're doing. For better performance (and a lot more writing of code) AudioUnits would be the preferred choice.
A short example using AVAudioPlayer class would be something like this-
The following code assumes a property of type AVAudioPlayer named
loopPlayer that is initialised with a file called some_audio_loop_file.wav in a UIViewController sub-class.
yourViewController.h
@property (nonatomic, strong) AVAudioPlayer *loopPlayer;
yourViewController.m
// set up loopPlayer property in for example viewDidLoad
NSURL* audioFileURL = [[NSBundle mainBundle] URLForResource:@"some_audio_loop_file" withExtension:@"wav"];
self.loopPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioFileURL error:nil];
// called from a UIButton touch down event
-(IBAction)startAudioSample:(id)sender {
[self.loopPlayer play];
}
// called from a UIButton touch up inside and touch drag outside events
-(IBAction)stopAudioSample:(id)sender {
if (self.loopPlayer.isPlaying) {
[self.loopPlayer stop];
self.loopPlayer.currentTime = 0;
self.loopPlayer.numberOfLoops = -1;
[self.loopPlayer prepareToPlay];
}