Skip navigation

I learned this from this guy, but this is just a super short, clean simple bare class that loads a single file (called “explode1.caf”). Adapt it to your needs.

// SoundMan.h
@interface SoundMan : NSObject

- (void) loadSound: (NSString*) name ;
- (void) genTestSound ;
- (void) playSound ;

@end

// SoundMan.mm
@implementation SoundMan

  ALCcontext *alC ;
  ALCdevice *alD ;
  NSUInteger sourceId ;
  NSUInteger soundBufferId ;
  
  - (id) init
  {
    if( self = [super init] )
    {
      // initializes openal
      alD = alcOpenDevice(NULL);
      if( alD )
      {
        alC = alcCreateContext( alD, NULL ) ;
        alcMakeContextCurrent( alC ) ;
        
        // Generate a test sound
        [self genTestSound] ;
      }
    }
    
    return self ;
  }
  
  - (void) genTestSound
  {
    alGenSources( 1, &sourceId );
    
    // Load explode1.caf
    NSString *path = [[NSBundle mainBundle] pathForResource:@"explode1" ofType:@"caf" ];

    AudioFileID fileID ;
    NSURL *afUrl = [NSURL fileURLWithPath:path];
    
    // NON zero means err
    if( AudioFileOpenURL((__bridge CFURLRef)afUrl, kAudioFileReadPermission, 0, &fileID) )
      printf( "cannot open file: %s", [path UTF8String] ) ;
      
    UInt32 fileSize = [self audioDataSize:fileID];
    unsigned char *outData = (unsigned char*)malloc(fileSize);
    if( AudioFileReadBytes(fileID, FALSE, 0, &fileSize, outData) )
    {
      printf( "Cannot load sound %s", [path UTF8String] );
      return;
    }
    AudioFileClose(fileID);
    	
    alGenBuffers(1, &soundBufferId);
    alBufferData( soundBufferId, AL_FORMAT_STEREO16, outData, fileSize, 44100 );
    
    free( outData ) ;
  }
  
  - (void) playSound
  {
    // set source
    alSourcei( sourceId, AL_BUFFER, soundBufferId ) ;
    
    alSourcef( sourceId, AL_PITCH, 1 ) ;
    alSourcef( sourceId, AL_GAIN, 1 ) ;
    alSourcei( sourceId, AL_LOOPING, AL_FALSE ) ;
    
    ALenum err = alGetError();
    if( err ) // 0 means no error
      printf( "ERROR SoundManager: %d", err ) ;
    else
      alSourcePlay( sourceId );
  }
  
  - (UInt32) audioDataSize:(AudioFileID)fileId {
    UInt64 dataSize = 0;  // dataSize
    UInt32 ps = sizeof(UInt64); // property size
    if( AudioFileGetProperty(fileId, 
        kAudioFilePropertyAudioDataByteCount, &ps, &dataSize) )
      puts( "error retriving data chunk size" );
    return dataSize ;
  }
  

@end


Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: