forked from jerrykrinock/ClassesObjC
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSSYAlertSounder.m
113 lines (86 loc) · 2.42 KB
/
SSYAlertSounder.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#import "SSYAlertSounder.h"
#import <AudioToolbox/AudioServices.h>
static SSYAlertSounder* static_sharedSounder = nil ;
@interface SSYAlertSounder ()
@end
@implementation SSYAlertSounder
- (id)init {
self = [super init] ;
if (self) {
m_soundIds = [[NSMutableDictionary alloc] init] ;
}
return self ;
}
- (void)dealloc {
for (NSNumber* soundId in [m_soundIds allValues]) {
AudioServicesDisposeSystemSoundID([soundId longValue]) ;
}
[m_soundIds release] ;
[super dealloc] ;
}
- (NSMutableDictionary*)soundIds {
return m_soundIds ;
}
+ (SSYAlertSounder*)sharedSounder {
@synchronized(self) {
if (!static_sharedSounder) {
static_sharedSounder = [[self alloc] init] ;
}
}
// No autorelease. This sticks around forever.
return static_sharedSounder ;
}
- (SystemSoundID)soundIdForPath:(NSString*)path
rememberAs:(NSString*)name {
SystemSoundID soundId = 0 ;
if (path) {
CFURLRef url = (CFURLRef)[NSURL fileURLWithPath:path] ;
if (url) {
OSStatus err ;
err = AudioServicesCreateSystemSoundID(url, &soundId) ;
if (err) {
// This will happen if file was not found.
soundId = 0 ;
}
else {
[[self soundIds] setObject:[NSNumber numberWithLong:soundId]
forKey:name] ;
}
}
}
return soundId ;
}
- (void)playAlertSoundNamed:(NSString*)name {
// First, see if we've got this sound cached
SystemSoundID soundId = [[[self soundIds] objectForKey:name] longValue] ;
// Used -longValue because SystemSoundID is a UInt32
NSString* path ;
// If not found, look in the current application's bundle
if (!soundId) {
path = [[NSBundle mainBundle] pathForResource:name
ofType:@"aiff"] ;
soundId = [self soundIdForPath:path
rememberAs:name] ;
// If not found, look in current user's library
if (!soundId) {
path = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Sounds"] ;
path = [path stringByAppendingPathComponent:[name stringByAppendingPathExtension:@"aiff"]] ;
soundId = [self soundIdForPath:path
rememberAs:name] ;
// If not found, look in system's library
if (!soundId) {
path = @"/System/Library/Sounds" ;
path = [path stringByAppendingPathComponent:[name stringByAppendingPathExtension:@"aiff"]] ;
soundId = [self soundIdForPath:path
rememberAs:name] ;
}
}
}
if (soundId) {
AudioServicesPlayAlertSound(soundId) ;
}
else {
NSBeep() ;
}
}
@end