Search code examples
objective-cimageaudiococos2d-iphoneccsprite

CCSprite with image file and sound file


I see how to add a image file to a CCSprite but how can I also add a audio file?

Is the an attribute I can store a map or dictionary?

FYI I'm on a mobile device posting this so code is not an option right now, will try to update my question

UPDATE:

What I'm trying to do is associate an audio file with each CCSprite and on touch drag play the audio file. Each CCSprite will play a different audio file. I'm trying to figure out the easiest way to either attach or associate the audio file with the CCSprite


Solution

  • OK, here is the approach I'd prefer, depending on whether you are playing a "background music" sound or an "effect" sound:

    If you are playing an MP3 sound, ie background music:

    1) Add a parameter to the sprite constructor to assign a sound file:

    [MySpriteClass spriteWithSound:@"mySound.mp3"];
    

    2) Simply use:

    // on touchDragged:
    [[SimpleAudioEngine sharedEngine] playBackgroundMusic:self.sound];
    
    // on touchEnded: touchCancelled:
    [[SimpleAudioEngine sharedEngine] stopBackgroundMusic];
    

    NOTE: This approach is simple because you can only play one BGM at any given time.


    If you are playing an uncompressed sound, ie effect:

    1) Add a parameter to the sprite constructor to assign a sound file:

    [MySpriteClass spriteWithSound:@"mySound.caf"];
    

    2) Play the effect on touchDragged: while storing the return value:

    // on touchDragged:
    soundID = [[SimpleAudioEngine sharedEngine] playEffect:self.sound];
    

    3) Stop the effect on touchEnded: using the soundID:

    // on touchEnded: cancelled:
    [[SimpleAudioEngine sharedEngine] stopEffect:soundID];
    

    NOTE: This approach is better as it allows you to play more sounds at a time.


    Final Remarks:

    If you have subclasses of each different sprite (ie, FishSprite, DogSprite, ... etc), such that ALL instance of any given class have the same sound, it would be better to add static method to return the sound name for that class:

    // somewhere in DogSprite.m
    + (NSString *)soundName {
        return @"bark.caf";
    }
    

    And for the sake of completeness, add a superclass that implements the touchDragged:, touchEnded:, so you don't have redundant code:

    // on touchDragged:
    soundID = [[SimpleAudioEngine sharedEngine] playBackgroundMusic:[[self class] soundName]];
    
    // on touchEnded: cancelled:
    [[SimpleAudioEngine sharedEngine] stopEffect:soundID];