当我将声音名称硬编码到那里时,它可以工作,但是当我使用随机生成器创建字符串时,它不会。顺便说一句:这是在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);
答案 0 :(得分:0)
当我在我的机器上运行-[NSBundle mainBundle]
时,它不包含尾部斜杠。
更改此行:
NSString *path = [NSString stringWithFormat:@"%@%@",
[[NSBundle mainBundle] resourcePath], fp];
对此:
NSString *path = [[[NSBundle mainBundle] resourcePath]
stringByAppendingPathComponent:fp];
这样做是正确的,NSBundle
是否添加了斜杠。