0
短版:隨機播放音短按下按鈕
int num=1;
NSString *popSound= [NSString stringWithFormat:@"pop%d",num];
我如何通過popSound
到CFBundleCopyResourceURL
如下面的聲音叫什麼名字?
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);