coding with objc & swift

iPhone SDK - 录音同时播放声音

| Comments

想要在iPhone上面在录音的同时也能播放声音,这需要一些技巧。默认情况下,当你在录音的时候,iPhone的输出音量会小到听不见。那么,我们要怎么解决这个问题呢?

首先,设置你的录音设备:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
NSURL *url = [NSURL fileURLWithPath:@"/dev/null"];
NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys:
   [NSNumber numberWithFloat: 44100.0],                 AVSampleRateKey,
   [NSNumber numberWithInt: kAudioFormatAppleLossless], AVFormatIDKey,
   [NSNumber numberWithInt: 1],                         AVNumberOfChannelsKey,
   [NSNumber numberWithInt: AVAudioQualityMax],         AVEncoderAudioQualityKey, nil];
recorder = [[AVAudioRecorder alloc] initWithURL:url settings:settings error:&error];
if (recorder) {
   [recorder prepareToRecord];
   recorder.meteringEnabled = YES;
   [recorder record];
} else {
   NSLog(@"Error: %@", error);
}

然后,告诉设备你想在录音的同时也能播放声音:

1
2
3
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
NSError *err = nil;
[audioSession setCategory :AVAudioSessionCategoryPlayAndRecord error:&err];

再接着,这里就是关键了——允许录音的同时,输出音量仍然可以很大声:

1
2
3
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,
sizeof(audioRouteOverride),&audioRouteOverride);

现在可以一边录音一边播放了。: ]

原文:Tech Thought

Comments