2014-01-13 64 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); 

重命名我的問題的情況下,任何人尋找如何做到這一點後