热门IT资讯网

IPhone之AVAudioRecorder

发表于:2024-11-25 作者:热门IT资讯网编辑
编辑最后更新 2024年11月25日,#import 需要引入//获取document目录的路径view plain- (NSString*) documentsPath {if (! _documentsPath) {NSArray

#import 需要引入

  1. //获取document目录的路径
  2. view plain
  3. - (NSString*) documentsPath {
  4. if (! _documentsPath) {
  5. NSArray *searchPaths =
  6. NSSearchPathForDirectoriesInDomains
  7. (NSDocumentDirectory, NSUserDomainMask, YES);
  8. _documentsPath = [searchPaths objectAtIndex: 0];
  9. [_documentsPath retain];
  10. }
  11. return _documentsPath;
  12. }
  13. //(document目录的路径)
  14. NSString *destinationString = [[self documentsPath]
  15. stringByAppendingPathComponent:filenameField.text];
  16. NSURL *destinationURL = [NSURL fileURLWithPath: destinationString];
  17. //初始化AVAudioRecorder
  18. NSError *recorderSetupError = nil;
  19. AVAudioRecorder audioRecorder = [[AVAudioRecorder alloc] initWithURL:destinationURL
  20. settings:recordSettings error:&recorderSetupError];
  21. [recordSettings release];


第二个参数 settings是一个容纳键值对的NSDictionary有四种一般的键


1:一般的音频设置


2:线性PCM设置


3:编码器设置


4:采样率转换设置



NSMutableDictionary 需要加入五个设置值(线性PCM)


view plain
  1. NSMutableDictionary *recordSettings =
  2. [[NSMutableDictionary alloc] initWithCapacity:10];
  3. //1 ID号
  4. [recordSettings setObject:
  5. [NSNumber numberWithInt: kAudioFormatLinearPCM] forKey: AVFormatIDKey];
  6. float sampleRate =
  7. [pcmSettingsViewController.sampleRateField.text floatValue];
  8. //2 采样率
  9. [recordSettings setObject:
  10. [NSNumber numberWithFloat:sampleRate] forKey: AVSampleRateKey];
  11. //3 通道的数目
  12. [recordSettings setObject:
  13. [NSNumber numberWithInt:
  14. (pcmSettingsViewController.stereoSwitch.on ? 2 : 1)]
  15. forKey:AVNumberOfChannelsKey];
  16. int bitDepth =
  17. [pcmSettingsViewController.sampleDepthField.text intValue];
  18. //4 采样位数 默认 16
  19. [recordSettings setObject:
  20. [NSNumber numberWithInt:bitDepth] forKey:AVLinearPCMBitDepthKey];
  21. //5
  22. [recordSettings setObject:
  23. [NSNumber numberWithBool:
  24. pcmSettingsViewController.bigEndianSwitch.on]
  25. forKey:AVLinearPCMIsBigEndianKey];
  26. //6 采样信号是整数还是浮点数
  27. [recordSettings setObject:
  28. [NSNumber numberWithBool:
  29. pcmSettingsViewController.floatingSamplesSwitch.on]
  30. forKey:AVLinearPCMIsFloatKey]
  31. ;

AVAudioRecorder成功创建后,使用他非常直接.它的三个基本方法如下


view plain
  1. -(void) startRecording {
  2. [audioRecorder record];
  3. }
  4. -(void) pauseRecording {
  5. [audioRecorder pause];
  6. recordPauseButton.selected = NO;
  7. }
  8. -(void) stopRecording {
  9. [audioRecorder stop];
  10. }
0