IBTAudioServicesManager.m 2.56 KB
//
//  IBTAudioServicesManager.m
//  XFFruit
//
//  Created by Xummer on 4/17/15.
//  Copyright (c) 2015 Xummer. All rights reserved.
//

#import "IBTAudioServicesManager.h"
#import <objc/runtime.h>

#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 60000 // iOS 6.0 or later
#define NEEDS_DISPATCH_RETAIN_RELEASE 0
#else                                         // iOS 5.X or earlier
#define NEEDS_DISPATCH_RETAIN_RELEASE 1
#endif

#define kDefaultDelay       1

@interface IBTAudioServicesManager()
{
    BOOL _active;
    dispatch_queue_t audioQueue;
}
@end

@implementation IBTAudioServicesManager

static IBTAudioServicesManager *_audioServicesManager = nil;

+ (IBTAudioServicesManager *)sharedManager
{
    @synchronized(self)
    {
        if (nil == _audioServicesManager) {
            _audioServicesManager = [[self alloc] init];
        }
    }
    return _audioServicesManager;
}

+ (id)allocWithZone:(NSZone *)zone
{
    @synchronized(self)
    {
        if (nil == _audioServicesManager) {
            _audioServicesManager = [super allocWithZone:zone];
            return _audioServicesManager;
        }
    }
    return nil;
}

- (id)copyWithZone:(NSZone *)zone
{
    return self;
}


- (void)dealloc
{
#if NEEDS_DISPATCH_RETAIN_RELEASE
    if (audioQueue)
        dispatch_release(audioQueue);
#endif
}


- (id)init
{
    self = [super init];
    if (self) {
        
        audioQueue = dispatch_queue_create(class_getName([self class]), NULL);
        self.delay = kDefaultDelay;
    }
    return self;
}


- (void)playSound:(SystemSoundID)soundID {
    
    if (_active) {
        return;
    }
    
    __block SystemSoundID sound = soundID;
    
    dispatch_async(audioQueue, ^{ @autoreleasepool {
        //        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
        _active = YES;
        
        AudioServicesPlayAlertSound(sound);
        
    }});
    
    
    dispatch_time_t waitTime = dispatch_time(DISPATCH_TIME_NOW, _delay * NSEC_PER_SEC);
    dispatch_after(waitTime, dispatch_get_main_queue(), ^(void) {
        _active = NO;
    });
    
}




//

static bool BSTAudioServicesActive;

+ (void)setBSTAudioServicesActive:(NSNumber*)activeNum
{
    BSTAudioServicesActive = [activeNum boolValue];
}


+ (void)playSound:(SystemSoundID)soundID {
    
    if (!BSTAudioServicesActive) {
        //        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
        BSTAudioServicesActive = YES;
        AudioServicesPlayAlertSound(soundID);
        [self performSelector:@selector(setBSTAudioServicesActive:) withObject:[NSNumber numberWithBool:NO] afterDelay:2.0f];
    }
}

@end