在iOS中录制video时播放音频文件

我想用相机录制时播放音频文件。 我使用AVAudioPlayer播放音频和AVCamCaptureManager进行录制。

但是当音频开始播放时,预览屏幕就会冻结。 我该怎么办?

谢谢你的帮助。 这是代码。 (我正在研究AVCam示例。)

这是预览部分。

if ([self captureManager] == nil) { AVCamCaptureManager *manager = [[AVCamCaptureManager alloc] init]; [self setCaptureManager:manager]; [[self captureManager] setDelegate:self]; if ([[self captureManager] setupSession]) { AVCaptureVideoPreviewLayer *newCaptureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:[[self captureManager] session]]; UIView *view = [self videoPreviewView]; CALayer *viewLayer = [view layer]; [viewLayer setMasksToBounds:YES]; CGRect bounds = CGRectMake(0, 0, 480, 320); [newCaptureVideoPreviewLayer setFrame:bounds]; if ([newCaptureVideoPreviewLayer isOrientationSupported]) { [newCaptureVideoPreviewLayer setOrientation:[DeviceProperties setPreviewOrientation]]; } [newCaptureVideoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill]; [viewLayer insertSublayer:newCaptureVideoPreviewLayer below:[[viewLayer sublayers] objectAtIndex:0]]; [self setCaptureVideoPreviewLayer:newCaptureVideoPreviewLayer]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ [[[self captureManager] session] startRunning]; }); [self updateButtonStates]; } 

这是音频播放的一部分。

 NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@", sound] ofType:@"wav"]]; AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil]; [audioPlayer play]; 

如果我使用AudioServicesPlaySystemSound正常而不冻结,但这次它只适用于viewDidLoad。

 CFBundleRef mainBundle = CFBundleGetMainBundle(); CFURLRef soundFileRef; soundFileRef = CFBundleCopyResourceURL(mainBundle, (CFStringRef) CFBridgingRetain(@"sound"), CFSTR ("wav"), NULL); UInt32 soundID; AudioServicesCreateSystemSoundID(soundFileRef, &soundID); AudioServicesPlaySystemSound(soundID); 

我的问题不是video,而是在通话中播放声音(voip类型应用程序),这个问题的答案对我有用:

同时使用vibrate和AVCaptureSession

希望将AVAudioSession类设置为AVAudioSessionCategoryPlayAndRecord将解决问题。 并将其类别选项设置为AVAudioSessionCategoryOptionDefaultToSpeaker|AVAudioSessionCategoryOptionMixWithOthers 。 请检查以下代码集

 @property (strong, nonatomic) AVAudioPlayer *audioPlayer; NSURL *soundUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"VoicemailSound" ofType:@"mp3"]]; //Download and add a system sound to your project and mention its name and type here self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil]; [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker|AVAudioSessionCategoryOptionMixWithOthers error: nil]; [self.audioPlayer prepareToPlay]; [self.audioPlayer play];