Created
July 1, 2012 19:32
-
-
Save basecode/3029331 to your computer and use it in GitHub Desktop.
An AVAudioPlayer Category for playing an Audio (mainly Audio-Sprite) File at a certain time for a certain duration. This Code is already in use in several iOS 5 Apps (that make use of ARC) published by MadameLeRenoir.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// AVAudioPlayer+SpriteCategory.h | |
// Copyright (C) 2012 Tobias Reiss (MIT License) | |
#import <AVFoundation/AVFoundation.h> | |
@interface AVAudioPlayer (SpriteCategory) | |
- (void) playAt:(NSTimeInterval)aStartTime duration:(NSTimeInterval)aDuration; | |
- (void) playAt:(NSTimeInterval)aStartTime duration:(NSTimeInterval)aDuration completion:(void (^)(void))completionBlock; | |
- (void) completionCleanup:(NSTimer*)aTimer; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// AVAudioPlayer+SpriteCategory.m | |
// Copyright (C) 2012 Tobias Reiss (MIT License) | |
// more infos about "Associated Objects": | |
// http://stackoverflow.com/questions/2846218/how-do-i-use-objc-setassociatedobject-objc-getassociatedobject-inside-an-object | |
// http://www.techpaa.com/2012/04/adding-properties-to-categories-and.html | |
#import "AVAudioPlayer+SpriteCategory.h" | |
#import <objc/runtime.h> | |
static void * const kMlrAssociatedStorageKey = (void*)&kMlrAssociatedStorageKey; | |
@implementation AVAudioPlayer (SpriteCategory) | |
-(void) playAt:(NSTimeInterval)aStartTime duration:(NSTimeInterval)aDuration { | |
[self playAt:aStartTime duration:aDuration completion:nil]; | |
} | |
-(void) playAt:(NSTimeInterval)aStartTime duration:(NSTimeInterval)aDuration completion:(void (^)(void))completionBlock | |
{ | |
[self completionCleanup:nil]; | |
[self setCurrentTime:aStartTime]; | |
[self play]; | |
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:aDuration | |
target:self | |
selector:@selector(completionCleanup:) | |
userInfo:completionBlock | |
repeats:NO]; | |
objc_setAssociatedObject(self, &kMlrAssociatedStorageKey, timer, OBJC_ASSOCIATION_RETAIN_NONATOMIC); | |
} | |
- (void)completionCleanup:(NSTimer*)aTimer { | |
[self pause]; | |
if (aTimer == nil || ![aTimer userInfo]) { | |
return; | |
} | |
void (^block)() = (void (^)())[aTimer userInfo]; | |
block(); | |
// invalidate NSTimer | |
[(NSTimer*)objc_getAssociatedObject(self, &kMlrAssociatedStorageKey) invalidate]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment