Created
December 30, 2015 05:19
-
-
Save jamesnesfield/d97d6dd258914c5506c7 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// cant remember where i got this from, not my code though | |
- (void)setSoundNamed:(NSString *)name forControlEvent:(UIControlEvents)controlEvent | |
{ | |
// Remove the old UI sound. | |
NSString *oldSoundKey = [NSString stringWithFormat:@"%lu", (unsigned long)controlEvent]; | |
AVAudioPlayer *oldSound = [self sounds][oldSoundKey]; | |
#pragma clang diagnostic push | |
#pragma clang diagnostic ignored "-Wselector" | |
[self removeTarget:oldSound action:@selector(play) forControlEvents:controlEvent]; | |
#pragma clang diagnostic pop | |
// Set appropriate category for UI sounds. | |
// Do not mute other playing audio. | |
[[AVAudioSession sharedInstance] setCategory:@"AVAudioSessionCategoryAmbient" error:nil]; | |
// Find the sound file. | |
NSString *file = [name stringByDeletingPathExtension]; | |
NSString *extension = [name pathExtension]; | |
NSURL *soundFileURL = [[NSBundle mainBundle] URLForResource:file withExtension:extension]; | |
NSError *error = nil; | |
// Create and prepare the sound. | |
AVAudioPlayer *tapSound = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:&error]; | |
[tapSound setVolume:0.8f]; | |
NSString *controlEventKey = [NSString stringWithFormat:@"%lu", (unsigned long)controlEvent]; | |
NSMutableDictionary *sounds = [self sounds]; | |
[sounds setObject:tapSound forKey:controlEventKey]; | |
[tapSound prepareToPlay]; | |
if (!tapSound) { | |
DLog(@"Couldn't add sound - error: %@", error); | |
return; | |
} | |
// Play the sound for the control event. | |
[self addTarget:tapSound action:@selector((play)) forControlEvents:controlEvent]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment