Whirlwind
Whirlwind

Reputation: 13665

Repeating short sounds after certain time delay

So I am having situation where I want to loop a sound and gradually decrease the delay between sounds. Means, sound beep should be played most often as time passing.

Right now, I am using an AVAudioPlayer with a sound which has duration of 1 sec, but the actual sound lasts only 0.5 sec. The other 0.5 sec of the sound is silenced. So when I use numberOfLoops property and set it to -1 (endless repeating) in combination with rate property on AVAudioPlayer and change it to some higher value than 1, I get desired result... Still, this is not that ideal, because sound may end up distorted (because of pitch).

I am looking for something like SKAction in SpriteKit for example, where I can run a block of code in after certain delay... What would be an optimal way for doing this in UIKit ?

Upvotes: 1

Views: 548

Answers (1)

GCBenson
GCBenson

Reputation: 536

To get a block of code to run after a certain delay in UIKit, one way is to use GCD, namely dispatch_after.

- (void)myMethod {
        __weak __typeof__(self) weakSelf = self;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(self.dispatchInterval * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if (weakSelf.isRunning){
                [weakSelf myMethod];
            }
        });

        // Code to play audio here
    }

Here, dispatchInterval is a float representing the number of seconds before the loop repeats. So just update dispatchInterval to reduce the loop length each time it fires. To start the loop just set isRunning to YES and call myMethod, to stop the loop just set isRunning to NO. This approach avoids having to use NSTimer, which can cause issues with retaining strong references to self.

Upvotes: 0

Related Questions