0

我已经设置好声音并且播放正常,但我想根据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";

4

3 回答 3

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);
    }
}
于 2012-04-27T19:26:43.377 回答
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 等。

于 2012-04-27T19:13:32.930 回答
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"];

于 2012-04-27T19:15:58.247 回答