我的声音全部设置并且播放正常,但我想根据NSString
的值更改声音。这是我的代码:
- (void) playSound {
CFBundleRef mainBundle = CFBundleGetMainBundle();
CFURLRef soundFileURLRef;
soundFileURLRef =CFBundleCopyResourceURL(mainBundle, (CFStringRef) @"glass", CFSTR ("wav"), NULL);
UInt32 soundID;
AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID);
AudioServicesPlaySystemSound(soundID);
}
我希望@"glass"
是来自其他地方的字符串的值,其定义如下NSString *sound = @"newSound";
。
答案 0 :(得分:0)
怎么样:
- (void) playSound:(NSString *)soundFile {
CFBundleRef mainBundle = CFBundleGetMainBundle();
CFURLRef soundFileURLRef;
soundFileURLRef =CFBundleCopyResourceURL(mainBundle, (CFStringRef) soundFile, CFSTR ("wav"), NULL);
UInt32 soundID;
AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID);
AudioServicesPlaySystemSound(soundID);
}
有很多不同的方法可以做到这一点。您甚至可以将“.wav”作为传入的soundFile字符串的一部分,以防您想要控制是否打开.wav或.mp3等。
答案 1 :(得分:0)
你不能像这样定义方法吗?
- (void) playSound:(NSString *)soundName {
CFBundleRef mainBundle = CFBundleGetMainBundle();
CFURLRef soundFileURLRef;
soundFileURLRef =CFBundleCopyResourceURL(mainBundle, (CFStringRef) soundName, CFSTR ("wav"), NULL);
UInt32 soundID;
AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID);
AudioServicesPlaySystemSound(soundID);
}
然后调用它来播放不同的声音,如: -
[soundPlayer playSound:@“glass”];
[soundPlayer playSound:@“newSound”];
答案 2 :(得分:0)
我会这样做:
将此添加到您的标题文件中:
typedef enum {
GlassSound,
NewSound,
} SoundEffect;
将其添加到实施块
中- (void)playSound:(SoundEffect)soundEffect {
NSString *sound = nil;
switch (soundEffect) {
case Glass:
sound = @"glass.wav";
break;
case newSound:
sound = @"newSound.wav";
break;
default:
break;
}
if (sound != nil) {
CFBundleRef mainBundle = CFBundleGetMainBundle();
CFURLRef soundFileURLRef;
soundFileURLRef =CFBundleCopyResourceURL(mainBundle, (CFStringRef) sound, NULL);
UInt32 soundID;
AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID);
AudioServicesPlaySystemSound(soundID);
}
}