2

When I hard-code the sound name into there, it works, but when I use a random generator to create the string, it doesn't. BTW: This is in Xcode 4.3 and iPhone 5.1 simulator.


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);
  • Check your assumptions - when you use the random generator, what's the actual filename being set into "buf"? Can you printf it or something to see what it is? – Colen Mar 19 '12 at 00:23
  • @Colen I used GDB with breakpoints and it had the correct file name when ran multiple times.(Sound(0,1,2,3).aifc) – Sam Mauldin Mar 19 '12 at 00:26
  • So if the only change you make is to replace "rand" with "2" on the sprintf line, it works properly? No other changes at all? – Colen Mar 19 '12 at 00:46
  • That dosen't work. It only works like this: NSString *path = [NSString stringWithFormat:@"%@%@", [[NSBundle mainBundle] resourcePath], @"Sound2.aifc"]; – Sam Mauldin Mar 19 '12 at 01:03
  • In the debugger, look at the value of "path" when you do it both ways. What's the difference? – Colen Mar 19 '12 at 01:29
  • It is correct both ways. – Sam Mauldin Mar 19 '12 at 23:29

1 Answers1

0

When I run -[NSBundle mainBundle] on my machine, it doesn't include a trailing slash.

Change this line:

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

To this:

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

This will do the right thing wether NSBundle is adding trailing slashes or not.

iluvcapra
  • 9,436
  • 2
  • 30
  • 32