In the following example, the storyboard has two buttons, one to
start and stop a recording (record), and the other to play it back
(play).
The sound is recorded to a file, sound.aac.
Examining parts of the view controller file:
//
// auaViewController.m
// Audio One
//
// Created by Nick Duchon on 12/10/13.
// Copyright (c) 2013 Nick Duchon. All rights
reserved.
//
#import "auaViewController.h"
@interface auaViewController () {
AVAudioRecorder * audioRecorder;
NSURL * soundFileURL;
AVAudioPlayer * audioPlayer;
}
@end
@implementation auaViewController
bool recording = FALSE;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after
loading the view, typically from a nib.
[self setupRecorder];
} // end method viewDidLoad
- (void) setupRecorder {
NSString * fileName = @"sound.aac";
soundFileURL = [NSURL
fileURLWithPath:[NSTemporaryDirectory()
stringByAppendingString:fileName]];
NSDictionary * soundSetting =
@{AVSampleRateKey:@44100.0f,
AVFormatIDKey:@(kAudioFormatMPEG4AAC),
AVNumberOfChannelsKey:@2,
AVEncoderAudioQualityKey:@(AVAudioQualityHigh)
}; // end sound settings
audioRecorder = [[AVAudioRecorder
alloc]
initWithURL:soundFileURL
settings:soundSetting
error:Nil];
} // end method setupRecorder
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can
be recreated.
}
- (IBAction)record:(id)sender {
if (recording) {
[audioRecorder
stop];
NSLog(@"Stopped");
[self.recordButton setTitle:@"Start Recording"
forState:UIControlStateNormal];
recording =
FALSE;
} else {
[audioRecorder
record];
NSLog(@"Recording");
[self.recordButton setTitle:@"End Recording"
forState:UIControlStateNormal];
recording =
true;
} // end if, case not recording
} // end method record
- (IBAction)play:(id)sender {
audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:soundFileURL
error:nil];
audioPlayer.delegate = self;
[audioPlayer play];
NSLog(@"Playing");
} // end method play
- (void) audioPlayerDidFinishPlaying:(AVAudioPlayer
*)player successfully:(BOOL)flag {
NSLog(@"Done Playing");
}
@end