Reputation: 31
I created this method to easily play sounds in an XCode iPhone application.
void playSound(NSString* myString) {
CFBundleRef mainBundle = CFBundleGetMainBundle();
NSString *string = myString;
CFURLRef soundFileURLRef;
soundFileURLRef = CFBundleCopyResourceURL(mainBundle, (__bridge CFStringRef) string, CFSTR ("wav"), NULL);
UInt32 soundID;
AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID);
AudioServicesPlaySystemSound(soundID);
}
The problem with this is, I don't know how to later stop the sound or to make the sound play on a loop forever until it is stopped. How would I go about doing this? Could I possibly make the method return the sound, and then put that in a variable to later be modified?
Upvotes: 0
Views: 1480
Reputation: 603
In case if you want to decide to play a sound based on a bool variable,
private func playSound() {
if isStarted {
AudioServicesPlaySystemSoundWithCompletion(kSystemSoundID_Vibrate, {
if self.isStarted {
self.playSound()
}
})
}
}
Upvotes: 0
Reputation: 253
System Sound Services usually is used to play short sounds/alerts/etc and pausing/stopping probably should be avoided. If this is really needed you could try AudioServicesDisposeSystemSoundID(systemSoundID)
to stop the sound.
As for looping you could create recursive function to loop the sound using AudioServicesPlaySystemSoundWithCompletion
.
Example (swift 3):
func playSystemSound(systemSoundID: SystemSoundID, count: Int){
AudioServicesPlaySystemSoundWithCompletion(systemSoundID) {
if count > 0 {
self.playSystemSound(systemSoundID: systemSoundID, count: count - 1)
}
}
}
So in your example you would just replace AudioServicesPlaySystemSound(soundID);
with playSystemSound(systemSoundID: soundID, count: numOfPlays)
Upvotes: 1
Reputation: 12260
From documentation: "The interface does not provide level, positioning, looping, or timing control, and does not support simultaneous playback...".
So for sound playback it is better use AVFoundation classes.
Upvotes: 1
Reputation: 115
I'm afraid i dont know how to stop it, but try this for looping:
soundFile = [NSURL fileURLWithPath: [[NSBundle mainBundle] pathForResource:@"AudioName" ofType:@"wav"]];
sound = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFile error:nil];
sound.numberOfLoops = -1; //infinite
[sound play];
Upvotes: 1