Showing posts with label AudioToolbox example. Show all posts
Showing posts with label AudioToolbox example. Show all posts

Tuesday, May 10, 2011

iPhone SDK AudioToolbox example

An AudioToolbox example. It plays a soundclip that is less than 30 seconds long.
In this AudioToolbox example, two methods are used. It's really simple!

1. Create an AudioService ID

AudioServiceCreateSystemSoundID(fileURL, soundID);

2. Play sound.

AudioServicePlaySystemSound(soundID)


// Code Fragment.

#import <UIKit/UIKit.h>
#import <AudioToolbox/AudioServices.h>

@interface Sound : NSObject
{
    SystemSoundID _soundID;
}
+(id)soundWithContentsOfFile:(NSString *)aPath;
-(id)initWithContentsOfFile:(NSString *)aPath;
-(void)play;

@end

Sound.m
#import "Sound.h"

@implementation Sound
+(id)soundWithContentsOfFile:(NSString *)aPath
{
    if(aPath)
    {
        return [[[Sound alloc]initWithContentsOfFile:aPath]autorelease];
    }
    return nil;
}

-(id)initWithContentsOfFile:(NSString *)aPath
{
    self = [super init];
    if(self != nil)
    {
        NSURL *aFileURL = [NSURL fileURLWithPath:aPath isDirectory:NO];
        if(aFileURL != nill)
        {
            SystemSoundID aSoundID;
            OSStatus error = AudioServicesCreateSystemSoundID((CFURLRef)aFileURL, &aSoundID);
            if(error == kAudioServicesNoError)
            {
                _soundID = aSoundID;
            }
            else
            {
                NSLog(@"Error %d loading sound at path : %@", error, aPath);
            }
        }
        else 
        {
            NSLog(@"NSURL is nil for path : %@", aPath);
            [self release], self = nil;
        }
    }
    return self;
}

-(void)play
{
    AudioServicesPlaySystemSound(_soundID);
}