32
技術社區[雲棲]
IPhone之AVAudioRecorder
#import <AVFoundation/AVFoundation.h> 需要引入//獲取document目錄的路徑
- (NSString*) documentsPath { if (! _documentsPath) { NSArray *searchPaths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); _documentsPath = [searchPaths objectAtIndex: 0]; [_documentsPath retain]; } return _documentsPath; } //(document目錄的路徑) NSString *destinationString = [[self documentsPath] stringByAppendingPathComponent:filenameField.text]; NSURL *destinationURL = [NSURL fileURLWithPath: destinationString]; //初始化AVAudioRecorder NSError *recorderSetupError = nil; AVAudioRecorder audioRecorder = [[AVAudioRecorder alloc] initWithURL:destinationURL settings:recordSettings error:&recorderSetupError]; [recordSettings release];
第二個參數 settings是一個容納鍵值對的NSDictionary有四種一般的鍵
1:一般的音頻設置
2:線性PCM設置
3:編碼器設置
4:采樣率轉換設置
NSMutableDictionary 需要加入五個設置值(線性PCM)
NSMutableDictionary *recordSettings = [[NSMutableDictionary alloc] initWithCapacity:10]; //1 ID號 [recordSettings setObject: [NSNumber numberWithInt: kAudioFormatLinearPCM] forKey: AVFormatIDKey]; float sampleRate = [pcmSettingsViewController.sampleRateField.text floatValue]; //2 采樣率 [recordSettings setObject: [NSNumber numberWithFloat:sampleRate] forKey: AVSampleRateKey]; //3 通道的數目 [recordSettings setObject: [NSNumber numberWithInt: (pcmSettingsViewController.stereoSwitch.on ? 2 : 1)] forKey:AVNumberOfChannelsKey]; int bitDepth = [pcmSettingsViewController.sampleDepthField.text intValue]; //4 采樣位數 默認 16 [recordSettings setObject: [NSNumber numberWithInt:bitDepth] forKey:AVLinearPCMBitDepthKey]; //5 [recordSettings setObject: [NSNumber numberWithBool: pcmSettingsViewController.bigEndianSwitch.on] forKey:AVLinearPCMIsBigEndianKey]; //6 采樣信號是整數還是浮點數 [recordSettings setObject: [NSNumber numberWithBool: pcmSettingsViewController.floatingSamplesSwitch.on] forKey:AVLinearPCMIsFloatKey]
;
AVAudioRecorder成功創建後,使用他非常直接.它的三個基本方法如下
-(void) startRecording { [audioRecorder record]; } -(void) pauseRecording { [audioRecorder pause]; recordPauseButton.selected = NO; } -(void) stopRecording { [audioRecorder stop]; }
最後更新:2017-04-02 06:52:04