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

时间:2010-07-06 16:46:02

标签: iphone audio avaudioplayer record

我正在尝试检测来自麦克风的输入并播放可以打开或关闭的声音,但是当麦克风监听器处于活动状态时,它总是在播放。

我已经在viewDidLoad方法中初始化了我的AVAudioSession,如下所示:

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

然后设置应该播放的声音:

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;

我正在使用SCListener课程进行录制。当我在手机上运行时,录音机工作正常,但即使我在viewDidLoad方法中为它调用play,声音也不会循环。

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

非常感谢您的回复。我确实在一段时间之前想到了这一点,但从来没有对此进行更新。结果很简单。您必须将AVAudioSession的类别设置为AVAudioSessionCategoryPlayAndRecord。

您需要的所有文档都在类引用中:

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

答案 1 :(得分:0)

我遇到了类似的问题 - 代码在模拟器上工作,但在设备上没有。我使用Cocos2D(Denshion)和AVAudioRecorder& AVAudioPlayer。

主要问题似乎是AVAudioRecorder和AVAudioPlayer代表你设置AVAudioSessionCategory,但如果你自己操纵它,他们似乎记得你是“自我管理”它并停止为你管理它

请参阅帮助我的this blog post(虽然我自己还没有解决这个问题;当我解决这个问题时,我会更新这篇文章。)