user1604196
user1604196

Reputation: 31

Playing Sound Loop or Stoping Play with AudioServices

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

Answers (4)

Nish
Nish

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

Filip Raj
Filip Raj

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

pronebird
pronebird

Reputation: 12260

From documentation: "The interface does not provide level, positioning, looping, or timing control, and does not support simultaneous playback...".

http://developer.apple.com/library/ios/#documentation/AudioToolbox/Reference/SystemSoundServicesReference/Reference/reference

So for sound playback it is better use AVFoundation classes.

Upvotes: 1

Brandon Boynton
Brandon Boynton

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

Related Questions