項目名: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];
復制代碼