IPhone之AVAudioRecorder

来源:互联网 发布:php接口安全 编辑:程序博客网 时间:2024/06/09 14:47

#import <AVFoundation/AVFoundation.h>  需要引入

//获取document目录的路径

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

第二个参数  settings是一个容纳键值对的NSDictionary有四种一般的键
1:一般的音频设置
2:线性PCM设置
3:编码器设置
4:采样率转换设置

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

[java] view plaincopy
  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]

;

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

[java] view plaincopy
  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. }