soleil
soleil

Reputation: 13135

How to play button sounds in Cocos2d

If I create a button like this:

CCMenuItemImage *okBtn = [CCMenuItemImage itemWithNormalImage:@"gameOkBtn.png"
                                                               selectedImage:@"gameOkBtnPressed.png"
                                                                       block:^(id sender)
                                         {
                                             //actions
                                         }];

How could I play a sound both on press and on release? In regular iOS dev I can subclass UIButton and add selectors for the UIControl events.

EDIT: Here's the subclass

@implementation CCMenuItemImageSound

- (void)selected{
    [super selected];
    [[SoundManager sharedManager] playSound:kSoundButtonDown volume:0.5];

}

- (void)unselected{
    [super unselected];
    //this method gets called twice when you release the button
    [[SoundManager sharedManager] playSound:kSoundButtonUp volume:0.5];

}

@end

Upvotes: 0

Views: 839

Answers (1)

Abhineet Prasad
Abhineet Prasad

Reputation: 1271

In CCMenuItem.m add,

[[SimpleAudioEngine sharedEngine] playEffect:@"button.mp3"];

in the definition of -(void) selected and -(void) unselected method under #pragma mark CCMenuItemSprite - CCRGBAProtocol protocol. This will play the sound for all CCMenuItemImage items.

Better option: If you wish the effect only for few buttons then you can subclass CCMenuItemImage and override the above mentioned methods.

You need to preload the mp3 somewhere in your code:

 [[SimpleAudioEngine sharedEngine]preloadEffect:@"button.mp3"];

You will also have to add #import "SimpleAudioEngine.h" to your CCMenuItem or the subclass that you create.

Upvotes: 1

Related Questions