如果声音名称为 sound0 ... soundN,您可以只介绍 ivars — 一个跟踪当前索引,一个定义声音的数量。
@implementation MyClass {
NSUInteger soundIdx;
NSUInteger soundCount;
}
-(instancetype) init //or any other entry point method like viewDidLoad,....
{
self = [super init];
if (self) {
soundCount = 10;
}
return self;
}
-(IBAction)sound
{
CFBundleRef mainBundle = CFBundleGetMainBundle();
CFURLRef soundFileURLRef;
soundFileURLRef = CFBundleCopyResourceURL(mainBundle, (CFStringRef) [NSString stringWithFormat:@"sound%lu", soundIdx], CFSTR("wav"), NULL);
UInt32 soundID;
AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID);
AudioServicesPlaySystemSound(soundID);
soundIdx = (++soundIdx) % soundCount;
}
@end
如果声音名称不遵循任何特定的命名约定,您可以将它们放在一个数组中
@implementation MyClass {
NSUInteger soundIdx;
NSArray *soundNames;
}
-(instancetype) init //or any other entry point method like viewDidLoad,....
{
self = [super init];
if (self) {
soundNames = @[@"sound1",@"hello", @"ping"];
}
return self;
}
-(IBAction)sound
{
CFBundleRef mainBundle = CFBundleGetMainBundle();
CFURLRef soundFileURLRef;
soundFileURLRef = CFBundleCopyResourceURL(mainBundle, (CFStringRef) soundNames[soundIdx], CFSTR("wav"), NULL);
UInt32 soundID;
AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID);
AudioServicesPlaySystemSound(soundID);
soundIdx = (++soundIdx) % [soundNames count];
}
@end