当我将声音名称硬编码到那里时,它可以工作,但是当我使用随机生成器创建字符串时,它不会。顺便说一句:这是在 Xcode 4.3 和 iPhone 5.1 模拟器中。
int rand = round(arc4random_uniform(3));
char buf[100];
sprintf(buf,"Sound%d.aifc",rand);
//get the filename of the sound file
NSString *fp=[NSString stringWithUTF8String:buf];
NSString *path = [NSString stringWithFormat:@"%@%@", [[NSBundle mainBundle] resourcePath], fp];
//declare a system sound
SystemSoundID soundID;
//get a path for the sound file
NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
//create the sound id
AudioServicesCreateSystemSoundID((CFURLRef)filePath, &soundID);
//play the sound
AudioServicesPlaySystemSound(soundID);