在AVAudioRecorder和AVAudioPlayer之间进行混淆

Joh*_*ohn 1 iphone cocoa-touch objective-c avaudioplayer avaudiorecorder

这是我的问题:

代码(FooController):

   NSString *path = [[NSBundle mainBundle] pathForResource:@"mySound" ofType:@"m4v"]; 
    soundEffect = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path]  error:NULL];
[soundEffect play];
    // MicBlow
    micBlow = [[MicBlowController alloc]init];
Run Code Online (Sandbox Code Playgroud)

而MicBlowController包含:

        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];
Run Code Online (Sandbox Code Playgroud)

[recorder updateMeters];
const double ALPHA = 0.05;
double peakPowerForChannel = pow(10,(0.05*[recorder peakPowerForChannel:0]));
lowPassResults = ALPHA * peakPowerForChannel + (1.0 - ALPHA) * lowPassResults;

NSLog(@"Average input: %f Peak input %f Low pass results: %f",[recorder averagePowerForChannel:0],[recorder peakPowerForChannel:0],lowPassResults);
Run Code Online (Sandbox Code Playgroud)

如果我播放背景音并尝试从麦克风获得峰值,我会得到此日志:平均输入:0.000000峰值输入-120.000000低通结果:0.000001

但是,如果我评论关于AVAudioPlayer的所有部分它是有效的.我认为有渠道问题.

谢谢

Joh*_*ohn 6

好吧,我找到了解决方案,它是AVAudioSession!

通过使用方法setCategory(使用AVAudioSessionCategoryPlayAndRecord作为参数),我可以播放声音并从麦克风录制声音.

audioSession = [[AVAudioSession sharedInstance] retain];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error: nil];
[audioSession setActive:YES error: nil];
Run Code Online (Sandbox Code Playgroud)