Obj-C ios AudioToolkit没有播放声音

时间:2012-03-19 00:13:09

标签: objective-c ios audiotoolbox

当我将声音名称硬编码到那里时,它可以工作,但是当我使用随机生成器创建字符串时,它不会。顺便说一句:这是在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);

1 个答案:

答案 0 :(得分:0)

当我在我的机器上运行-[NSBundle mainBundle]时,它不包含尾部斜杠。

更改此行:

NSString *path = [NSString stringWithFormat:@"%@%@", 
  [[NSBundle mainBundle] resourcePath], fp];

对此:

NSString *path = [[[NSBundle mainBundle] resourcePath] 
  stringByAppendingPathComponent:fp];

这样做是正确的,NSBundle是否添加了斜杠。