2

そこにサウンド名をハードコーディングすると機能しますが、ランダムジェネレーターを使用して文字列を作成すると機能しません。ところで: これは 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);
4

1 に答える 1

0

私のマシンで実行する-[NSBundle mainBundle]と、末尾のスラッシュが含まれません。

この行を変更します。

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

これに:

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

NSBundleこれは、末尾のスラッシュを追加するかどうかに関係なく、正しいことを行います。

于 2013-02-27T19:38:31.020 に答える