简体   繁体   English

使用iPhone SDK同时播放和录制声音吗?

[英]Play and record sound simultaneously with iPhone SDK?

I'm trying to detect input from the mic and also play sounds, which can be toggled on or off, but are always playing when the mic listener is active. 我正在尝试检测来自麦克风的输入并播放声音,可以将其打开或关闭,但是在麦克风监听器处于活动状态时始终会播放。

I've initialized my AVAudioSession in the viewDidLoad method like so: 我已经在viewDidLoad方法中初始化了AVAudioSession,如下所示:

AVAudioSession *session = [AVAudioSession sharedInstance];
NSError *err = nil;
[session setCategory:AVAudioSessionCategoryPlayAndRecord error:&err];
[session setActive:YES error:&err];

Then setup the sound that's supposed to be played: 然后设置应该播放的声音:

NSURL *activeUrl = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/audio_file.caf", [[NSBundle mainBundle] resourcePath]]];
activePlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:activeUrl error:nil];
activePlayer.numberOfLoops = -1;
activePlayer.currentTime = 0;
activePlayer.volume = -1.5;

And I'm using the SCListener class to do the recording. 我正在使用SCListener类进行记录。 When I run this on the phone, the recorder works just fine, but the sound won't loop even when I call play for it in the viewDidLoad method. 当我在电话上运行此功能时,录音机工作正常,但即使在viewDidLoad方法中调用播放器,声音也不会循环播放。

Any ideas? 有任何想法吗?

Thanks so much for the responses. 非常感谢您的回复。 I did actually figure this out a while back, but never got around to updating this. 我确实在一段时间前就解决了这个问题,但是从来没有去更新它。 Turned out to be very simple. 原来很简单。 You have to set category of AVAudioSession to AVAudioSessionCategoryPlayAndRecord. 您必须将AVAudioSession的类别设置为AVAudioSessionCategoryPlayAndRecord。

Pretty much all the documentation you need is here in the class reference: 您所需的几乎所有文档都在类参考中:

http://developer.apple.com/library/ios/#documentation/AVFoundation/Reference/AVAudioSession_ClassReference/Reference/Reference.html http://developer.apple.com/library/ios/#documentation/AVFoundation/Reference/AVAudioSession_ClassReference/Reference/Reference.html

I had a similar issue to you - the code worked on the simulator, but not on the device. 我遇到了类似的问题-该代码在模拟器上有效,但在设备上无效。 I had this problem using Cocos2D (Denshion) along with AVAudioRecorder & AVAudioPlayer. 使用Cocos2D(Denshion)以及AVAudioRecorder和AVAudioPlayer时遇到了这个问题。

The main issue seems to be that AVAudioRecorder and AVAudioPlayer set the AVAudioSessionCategory on your behalf, but if you manipulate it yourself, they seem to remember that you're "self managing" it and stop managing it for you. 主要问题似乎是AVAudioRecorder和AVAudioPlayer代表您设置了AVAudioSessionCategory ,但是如果您自己操作它,他们似乎会记住您正在“自我管理”它并停止为您管理它。

See this blog post that helped me (although I still haven't solved the issue myself; I'll update this post when I do solve it). 请参阅这篇对我有帮助的博客文章 (尽管我仍然没有自己解决问题;我将在解决该问题后对其进行更新)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM