A Media class

Textures and sounds are used throughout any game, so they should be collected in one place where they are easy to access. One way to do that is with the “Media” class that is shown below.

Add the class to your game and modify it to your needs (loading the correct texture atlas, etc.). This is how you use it:

// At the start of the game, call:
[Media initTextures];
[Media initAudio];
// Then, wherever you need access to a texture or play a sound:
SPTexture *texture = [Media atlasTexture:@"button"];
[Media playSound:@"click.caf"];
// and at the end, release all data.
[Media releaseTextures];
[Media releaseSound];


@interface Media : NSObject 
+ (void)initTextures;
+ (void)releaseTextures;
+ (SPTexture *)atlasTexture:(NSString *)name;
+ (void)initAudio;
+ (void)releaseAudio;
+ (void)playSound:(NSString *)soundName;
+ (SPSoundChannel *)soundChannel:(NSString *)soundName;
#import "Media.h"
@implementation Media
static SPTextureAtlas *atlas = NULL;
static NSMutableDictionary *sounds = NULL;
#pragma mark Texture Atlas
+ (void)initTextures
    [atlas release];
    atlas = [[SPTextureAtlas alloc] initWithContentsOfFile:@"textures.xml"];
+ (void)releaseTextures
    [atlas release];
    atlas = nil;
+ (SPTexture *)atlasTexture:(NSString *)name
    if (!atlas)
        [NSException raise:NSGenericException format:@"call 'initTextures:' first"];
    return [atlas textureByName:name];
#pragma mark Audio
+ (void)initAudio
    if (sounds) return;
    [SPAudioEngine start];
    sounds = [[NSMutableDictionary alloc] init];
    // enumerate all sounds
    NSString *soundDir = [[NSBundle mainBundle] resourcePath];
    NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager]
    NSString *filename;
    while (filename = [dirEnum nextObject])
        if ([[filename pathExtension] isEqualToString: @"caf"])
            SPSound *sound = [[SPSound alloc] initWithContentsOfFile:filename];
            SPSoundChannel *channel = [sound createChannel];
            [sounds setObject:channel forKey:filename];
            [sound release];
+ (void)releaseAudio
    [sounds release];
    sounds = nil;
    [SPAudioEngine stop];
+ (void)playSound:(NSString *)soundName
    [[sounds objectForKey:soundName] play];
+ (SPSoundChannel *)soundChannel:(NSString *)soundName
    return [sounds objectForKey:soundName];

In this code, I simply load all “.caf” files that are available. Furthermore, there are 2 methods to access sounds: one to play it right away, another method if you need to have an audio channel.

For other ideas and a discussion of this class, see this forum thread.

  tutorials/media_class.txt · Last modified: 2013/03/05 10:19 by
Powered by DokuWiki