您的要求很有趣。所以你需要同时播放和录音,对吧?
因此,您需要使用类别 AVAudioSessionCategoryPlayAndRecord 初始化音频会话。
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:&error];
因为您使用UIImagePickerController 进行录音,所以您对扬声器和麦克风没有太多控制权。所以测试一下,看看它是否有效。
如果你还是有问题,建议你使用AVCaptureSession录制没有音频的视频。看看这个例子怎么用record-video-with-avcapturesession-2。
更新:在我的 VOIP 应用程序中,我使用AVAudioUnit 在播放时进行录制。所以我认为唯一的方法是分别录制视频和音频,然后使用AVComposition 将其组合成一部电影。使用AVCaptureSession 仅录制视频,使用EZAudio 录制音频。 EZAudio 使用 AVAudioUnit 进行记录,以便它应该工作。您可以通过在播放电影时录制音频来测试它,看看它是否有效。我希望它会有所帮助
更新:我测试过,它只有在您使用耳机或选择麦克风时才有效。
以下是测试代码:
NSString *moviePath = [[NSBundle mainBundle] pathForResource:@"videoviewdemo" ofType:@"mp4"];
NSURL *url = [NSURL fileURLWithPath:moviePath];
// You may find a test stream at <http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8>.
AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:url];
AVPlayer *player = [AVPlayer playerWithPlayerItem:playerItem];
AVPlayerLayer *layer = [[AVPlayerLayer alloc] init];
[layer setPlayer:player];
[layer setFrame:CGRectMake(0, 0, 100, 100)];
[self.view.layer addSublayer:layer];
[player play];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//
// Setup the AVAudioSession. EZMicrophone will not work properly on iOS
// if you don't do this!
//
AVAudioSession *session = [AVAudioSession sharedInstance];
NSError *error;
[session setCategory:AVAudioSessionCategoryPlayAndRecord error:&error];
if (error)
{
NSLog(@"Error setting up audio session category: %@", error.localizedDescription);
}
[session setActive:YES error:&error];
if (error)
{
NSLog(@"Error setting up audio session active: %@", error.localizedDescription);
}
//
// Customizing the audio plot's look
//
// Background color
self.audioPlot.backgroundColor = [UIColor colorWithRed:0.984 green:0.471 blue:0.525 alpha:1.0];
// Waveform color
self.audioPlot.color = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0];
// Plot type
self.audioPlot.plotType = EZPlotTypeBuffer;
//
// Create the microphone
//
self.microphone = [EZMicrophone microphoneWithDelegate:self];
//
// Set up the microphone input UIPickerView items to select
// between different microphone inputs. Here what we're doing behind the hood
// is enumerating the available inputs provided by the AVAudioSession.
//
self.inputs = [EZAudioDevice inputDevices];
self.microphoneInputPickerView.dataSource = self;
self.microphoneInputPickerView.delegate = self;
//
// Start the microphone
//
[self.microphone startFetchingAudio];
self.microphoneTextLabel.text = @"Microphone On";
[[AVAudioSession sharedInstance] overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil];
});