2014-01-13 66 views
0

短版:随机播放音短按下按钮

int num=1; 
NSString *popSound= [NSString stringWithFormat:@"pop%d",num]; 

我如何通过popSoundCFBundleCopyResourceURL如下面的声音叫什么名字?

soundFileURLRef = CFBundleCopyResourceURL(mainBundle, (CFStringRef) @"pop1", CFSTR ("mp3"), NULL); 

详细代码:

//Need to play one of 5 sounds randomly on button press 
CFBundleRef mainBundle = CFBundleGetMainBundle(); 
CFURLRef soundFileURLRef; 

//get random number 
//5 gets me 0-4 so the +1 is needed to adjust the lower bounds 
int num = arc4random_uniform(5)+1; 
NSString *popSound= [NSString stringWithFormat:@"pop%d",num]; 

//just to be sure Im getting what I expect, log this 
//should and am getting "pop1.mp3 
NSLog([NSString stringWithFormat:@"-------sound picked=: pop%d.mp3",num]); 

//this is my problem 
//i can set the sound directly easy enough with this: 
soundFileURLRef = CFBundleCopyResourceURL(mainBundle, (CFStringRef) @"pop1", CFSTR ("mp3"), NULL); 

//but I need to pass my variable popSound as the file name 
//I tried: 
soundFileURLRef = CFBundleCopyResourceURL(mainBundle, (CFStringRef) popSound, CFSTR ("mp3"), NULL); 
//xcode complains saying that casting NSString to CFStringRef requires a bridge cast 


//so I accepted the suggested fix and got: 
soundFileURLRef = CFBundleCopyResourceURL(mainBundle, (__bridge CFStringRef) popSound, CFSTR ("mp3"), NULL); 
//which quiets xcode but doesnt play the sound 

UInt32 soundID; 
AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID); 
AudioServicesPlaySystemSound(soundID); 

回答

0

我居然发现一些工作。我落得这样做是:

//get random number 
//5 gets me 0-4 so the +1 is needed to adjust the lower bounds  
int num = arc4random_uniform(5)+1; 
NSString *popSound= [NSString stringWithFormat:@"pop%d.mp3",num]; 

//just to be sure Im getting what I expect, log this 
//should and am getting "pop1.mp3 
NSLog([NSString stringWithFormat:@"-------sound picked=: pop%d.mp3",num]); 


NSString *path = [NSString stringWithFormat: @"%@/%@", [[NSBundle mainBundle] resourcePath], popSound]; 
NSURL* filePath = [NSURL fileURLWithPath: path isDirectory: NO]; 
SystemSoundID soundID; 
AudioServicesCreateSystemSoundID((__bridge CFURLRef)filePath, &soundID); 
AudioServicesPlaySystemSound(soundID); 

重命名我的问题的情况下,任何人寻找如何做到这一点后