项目名:SpeakHere
功能:录制并播放用户录制的音频

框架:AVFoundation.framework

实现步骤
以下例子用到了AVAudioRecorder和AVAudioPlay来录制和播放音频,并且预先设置了一系列音频参数及保存路径。AVAudioRecorder和AVAudioPlay提供了相比openAL更为便捷的录音和播放方式,便于实现一些简单的录音和播放功能。
1. 设置音频参数及保存路径

 1    NSNumber *sampleRate, *formatId, *numberOfChannels, *audioQuality;
2
3 // recording file path
4 filePath = [NSHomeDirectory() stringByAppendingPathComponent: @"Documents/recording.caf"];
5
6 // set up record settings
7 sampleRate = [NSNumber numberWithFloat: 44100.0];
8 formatId = [NSNumber numberWithInt: kAudioFormatAppleLossless];
9 numberOfChannels = [NSNumber numberWithInt: 1];
10 audioQuality = [NSNumber numberWithInt: AVAudioQualityMax];
11 // save settings in NSDictionary
12 NSDictionary *recordSettings = [[NSDictionary alloc] initWithObjectsAndKeys: sampleRate, AVSampleRateKey, formatId, AVFor matIDKey, numberOfChannels, AVNumberOfChannelsKey, audioQuality, AVEncoderAudioQualityKey, nil];

 



复制代码

2. 开始和停止录音

// init recorder
recorder = [[AVAudioRecorder alloc] initWithURL: [NSURL fileURLWithPath:filePath] settings: recordSettings error: nil];
[recorder record];
[recorder stop];



复制代码

3. 开始和停止播放

1 player = [[AVAudioPlayer alloc] initWithContentsOfURL: [NSURL fileURLWithPath:filePath] error: nil];
2 [player play];
3 [player stop];



复制代码