Objective c 更改传递给函数的NSString的值

Objective c 更改传递给函数的NSString的值,objective-c,cocoa-touch,variables,Objective C,Cocoa Touch,Variables,我有一个声音,所有设置和播放都很好,但我想根据NSString中的值更改声音。这是我的密码: - (void) playSound { CFBundleRef mainBundle = CFBundleGetMainBundle(); CFURLRef soundFileURLRef; soundFileURLRef =CFBundleCopyResourceURL(mainBundle, (CFStringRef) @"glass", CFSTR ("wav"), NU

我有一个声音,所有设置和播放都很好,但我想根据
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”

如何:

- (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”作为传入的声音文件字符串的一部分,以防您想要控制是否打开.wav或.mp3等等。

您不能这样定义方法吗

- (void) playSound:(NSString *)soundName {
    CFBundleRef mainBundle = CFBundleGetMainBundle();
    CFURLRef soundFileURLRef;
    soundFileURLRef =CFBundleCopyResourceURL(mainBundle, (CFStringRef) soundName, CFSTR ("wav"), NULL);
UInt32 soundID;
    AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID);
    AudioServicesPlaySystemSound(soundID);
}
然后调用它播放不同的声音,如:-

[声音播放器播放声音:@“玻璃”]


[声音播放器播放声音:@“newSound”]

我会这样做:

将其添加到头文件:

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

谢谢,我让这个方法起作用了。只需记住如下设置字符串:NSString*soundFile=@“fileName”;并这样称呼它:[self playSound:(NSString*)soundFile];不,你不必那样设置。您只需传递@“fileName”作为参数,该转换完全没有必要。正如@bbum所说,您可以这样调用它:
[self playSound:@“fileName”]或:
NSString*soundFile=@“filename”;[自动播放声音:声音文件]