音乐切换按钮objective-c

时间:2013-12-02 00:17:40

标签: ios iphone objective-c cocos2d-iphone

我在位于游戏标题屏幕的cocos2d中创建了一个切换按钮。我想要这个切换来打开或关闭音乐。这是我到目前为止所做的:

我将CCMenus和Sprites添加到.h文件中:

 CCMenu *menu2;
 CCMenu *menutwo;
 CCMenuItemImage *sound;
 CCMenuItemSprite *soundOff;

然后我在init中添加了声音按钮和NSUserDefault:

// Sound Button
sound = [CCMenuItemImage itemWithNormalImage:@"music.png" selectedImage:@"music.png" target:self selector:@selector(soundSettings)];
sound.scale = 1.1;
menu2 = [CCMenu menuWithItems:sound, nil];
menu2.position = ccp(screenCenter.x - 33,screenCenter.y / 5);
[self addChild:menu2];

if([[NSUserDefaults standardUserDefaults] objectForKey:@"musicon"] == nil) {
        [[NSUserDefaults standardUserDefaults] setBool:TRUE forKey:@"musicon"];
}

这是CCSprite上面调用的soundSettings方法:

- (void) soundSettings {
    if([[NSUserDefaults standardUserDefaults] boolForKey:@"musicon"] == TRUE) {
        [self removeChild:soundOff cleanup:YES];
        [self removeChild:menutwo cleanup:YES];
        sound = [CCMenuItemImage itemWithNormalImage:@"music.png" selectedImage:@"music.png" target:self selector:@selector(soundIsOff)];
        sound.scale = 1.1;
        menu2 = [CCMenu menuWithItems:sound, nil];
        menu2.position = ccp(screenCenter.x - 33,screenCenter.y / 5);
        [self addChild:menu2];
    } else if ([[NSUserDefaults standardUserDefaults] boolForKey:@"musicon"] == FALSE) {
        [self removeChild:sound cleanup:YES];
        [self removeChild:menu2 cleanup:YES];
        soundOff = [CCMenuItemImage itemWithNormalImage:@"music-not.png" selectedImage:@"music-not.png" target:self selector:@selector(soundIsOn)];
        soundOff.scale = 1.1;
        menutwo = [CCMenu menuWithItems:soundOff, nil];
        menutwo.position = ccp(screenCenter.x - 33,screenCenter.y / 5);
        [self addChild:menutwo];
    }
}

这些是切换CCSprites调用的两种方法:

-(void) soundIsOn {
    [[NSUserDefaults standardUserDefaults] setBool:TRUE forKey:@"musicon"];
}
-(void) soundIsOff {
    [[NSUserDefaults standardUserDefaults] setBool:FALSE forKey:@"musicon"];
}

由于此代码位于标题屏幕中,因此仅停止标题屏幕的音乐。一旦我转到另一个屏幕,音乐BOOL重置并再次变为TRUE。如果有人能帮我解决这个问题,我真的很感激。谢谢!

注意:这是我将检查音乐是否开启的方式:

if([[NSUserDefaults standardUserDefaults]boolForKey:@"musicon"] == TRUE) {
   [[SimpleAudioEngine sharedEngine] playEffect:@"song.mp3"];
}

1 个答案:

答案 0 :(得分:3)

按照以下方式更改您的方法,您需要在NSUserDefaults中设置任何值后进行同步,以重新获得保存的值。

-(void) soundIsOn {
    [[NSUserDefaults standardUserDefaults] setBool:TRUE forKey:@"musicon"];
    [[NSUserDefaults standardUserDefaults] synchronize];// Add this 
}
-(void) soundIsOff {
    [[NSUserDefaults standardUserDefaults] setBool:FALSE forKey:@"musicon"];
    [[NSUserDefaults standardUserDefaults] synchronize];// Add this 
}