按下按钮播放随机短音

时间:2014-01-13 10:51:45

标签: ios objective-c xcode audio

简短版本:

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);

1 个答案:

答案 0 :(得分: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);

重命名我的问题,以防有人在以后查找如何执行此操作