//建立音频会话和声音文件的URL
//注: 在.h引用里面加入AVAudioSessionDelegate以及AVAudioRecorderDelegate
- (void) viewDidLoad {
[super viewDidLoad];
NSString *soundFilePath = [@"/Users/Shared/" stringByAppendingString: @"sound.caf"];
NSURL *newURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
self.soundFileURL = newURL; //soundFileURL 在.h里面定义
[newURL release];
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
audioSession.delegate = self;
[audioSession setActive: YES error: nil];
recording = NO;
playing = NO;
}
//一个基于AVAudioRecorder类的录制/停止方法
-(IBAction) recordOrStop: (id) sender {
if (recording) {
[soundRecorder stop];
recording = NO;
self.soundRecorder = nil; //soundRecorder 在.h里面定义
//recordOrStopButton 声明定义
[recordOrStopButton setTitle: @"Record" forState: UIControlStateNormal];
[recordOrStopButton setTitle: @"Record" forState: UIControlStateHighlighted];
[[AVAudioSession sharedInstance] setActive: NO error: nil];
} else {
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryRecord error: nil];
NSDictionary *recordSettings =
[[NSDictionary alloc] initWithObjectsAndKeys:
[NSNumber numberWithFloat: 44100.0], AVSampleRateKey,
[NSNumber numberWithInt: kAudioFormatAppleLossless], AVFormatIDKey,
[NSNumber numberWithInt: 1], AVNumberOfChannelsKey,
[NSNumber numberWithInt: AVAudioQualityMax], AVEncoderAudioQualityKey,
nil];
AVAudioRecorder *newRecorder = [[AVAudioRecorder alloc] initWithURL: soundFileURL
settings: recordSettings
error: nil];
[recordSettings release];
self.soundRecorder = newRecorder;
[newRecorder release];
soundRecorder.delegate = self;
[soundRecorder prepareToRecord]; //创建音频文件 sound.caf
[soundRecorder record];
[recordOrStopButton setTitle: @"Stop" forState: UIControlStateNormal];
[recordOrStopButton setTitle: @"Stop" forState: UIControlStateHighlighted];
recording = YES;
}
}