- ## Header
- #import <Cocoa/Cocoa.h>
- @interface RecorderClass : NSObject {
- NSMutableArray *pressTimes;
- NSDate *lastPress;
- NSTimer *replayTimer;
- NSInteger *currentSoundNumber;
- // In here, put all the buttons the user might press
- IBOutlet NSButton *sampleButton1;
- IBOutlet NSButton *sampleButton2;
- IBOutlet NSButton *sampleButton3;
- // etc...
- }
- - (IBAction)record:(id)sender;
- - (IBAction)addSound:(id)sender;
- - (IBAction)stopRecording:(id)sender;
- - (IBAction)play:(id)sender;
- - (void)playSound:(NSTimer *)timer;
- @end
- ## Main
- #import "RecorderClass.h"
- @implementation RecorderClass
- - (IBAction)record:(id)sender {
- [sender setTitle:@"Stop Recording"];
- pressTimes = [NSMutableArray array];
- lastPress = [NSDate now];
- }
- - (IBAction)addSound:(id)sender {
- [pressTimes addObject:[NSDictionary dictionaryWithObjectsAndKeys:sender, @"ButtonPressed", [lastPress timeIntervalSinceNow], @"TimeBetweenPresses", nil]];
- lastPress = [NSDate now];
- }
- - (IBAction)stopRecording:(id)sender {
- [sender setTitle:@"Start Recording"];
- lastPress = nil;
- }
- - (IBAction)play:(id)sender {
- currentSoundNumber = 0;
- replayTimer = [[NSTimer scheduledTimerWithTimeInterval:[[pressTimes objectAtIndex:0] objectForKey:@"TimeBetweenPresses"] target:self selector:@selector(playSound:) userInfo:[[pressTimes objectAtIndex:0] objectForKey:@"ButtonPressed"] retain];
- }
- - (void)playSound:(NSTimer *)timer {
- NSButton *buttonPressed = [timer object];
- if([buttonPressed isEqualTo:sampleButton1]) {
- NSSound *soundToBePlayed = [NSSound soundNamed:@"sample sound 1.mp3"];
- [soundToBePlayed play]; // This is asynchronious, so we need to use sound:didFinishPlaying: to release the sound
- [sound setDelegate:self];
- } // etc for other buttons, you get the picture
- }
- - (void)sound:(NSSound *)sound didFinishPlaying:(BOOL)finishedPlaying {
- [sound release];
- [replayTimer invalidate];
- [replayTimer release];
- if(currentSoundNumber < [pressTimes count]) {
- replayTimer = [[NSTimer scheduledTimerWithTimeInterval:[[pressTimes objectAtIndex:currentSoundNumber] objectForKey:@"TimeBetweenPresses"] target:self selector:@selector(playSound:) userInfo:[[pressTimes objectAtIndex:currentSoundNumber] objectForKey:@"ButtonPressed"] retain];
- } else {
- replayTimer = nil;
- }
- }
- @end