cocoa播放音频 系统声效

1
2
NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"alert" ofType:@"wav"];
_sound = [[NSSound alloc] initWithContentsOfFile:resourcePath byReference:YES];

播放系统声效

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
int soundIndex = 0;
- (void) tryLoopPlaySound{
NSArray *directoryContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:@"/System/Library/Sounds"
error:nil];
NSUInteger arrayCount = [directoryContents count];
if (soundIndex < arrayCount-1) {
soundIndex++;
}
else {
soundIndex = 0;
}
[self playSystemSound:soundIndex];
}

-(void) playSystemSound:(int) index{
NSArray *directoryContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:@"/System/Library/Sounds"
error:nil];
NSUInteger arrayCount = [directoryContents count];
if(index >= arrayCount) {
return;
}
NSString *soundName = [directoryContents objectAtIndex:
index];
soundName = [soundName stringByDeletingPathExtension];
NSSound *systemSound = [NSSound soundNamed:soundName];
NSLog(@"soundName %@ %d",soundName, index);
[systemSound play];
}