访问麦克风后,整个应用的音量变得更安静

时间:2016-04-14 16:45:03

标签: ios swift volume avaudiorecorder avaudiosession

我在iOS应用中遇到了卷问题。当我拨打setupMic()时,整个应用的音量水平显着降低 这是我正在使用的代码:

func setupMic() {
    //make an AudioSession, set it to PlayAndRecord and make it active
    let audioSession: AVAudioSession = AVAudioSession.sharedInstance()
    do {
        try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
    } catch {
       print("There was an error setting the category")
    }
    do {
       try audioSession.setActive(true)
    } catch {
       print("There was an error setting the audio session to active")
    }


    //set up the URL for the audio file
    let documents: AnyObject = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
    let str = documents.stringByAppendingPathComponent("recordTest.caf")
    let url = NSURL.fileURLWithPath(str as String)

    //make a dictionary to hold the recording setting so we can instantiate our AVAudioRecorder
    let number = NSNumber(unsignedInt: kAudioFormatAppleIMA4)
    let recordSettings: [String: AnyObject] = [AVFormatIDKey: number,
                                                 AVSampleRateKey: 44100.0,
                                                 AVNumberOfChannelsKey: 2,
                                                 AVEncoderBitRateKey: 12800,
                                                 AVLinearPCMBitDepthKey: 16,
                                                 AVEncoderAudioQualityKey: AVAudioQuality.Min.rawValue]

    //Instantiate an AVAudioRecorder
    do {
        recorder = try AVAudioRecorder(URL: url, settings: recordSettings)
    } catch {
      print("There was an error")
    }
}

//This function is called everytime our timer levelTimer fires
func levelTimerCallback() {
    recorder.updateMeters()
    let averagePower = self.recorder.peakPowerForChannel(0)
    if averagePower > -7 {
        stopMonitoring()

        print(recorder.peakPowerForChannel(0))
        didCompleteChallenge(true)
    }
}

func startMonitoring() {
    if self.recorder != nil {
        recorder.prepareToRecord()
        recorder.meteringEnabled = true
        //start recording
        recorder.record()
        //instantiate a timer to be called with whatever frequency we want to grab metering values
        self.levelTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(levelTimerCallback), userInfo: nil, repeats: true)
    }
}

func stopMonitoring() {
    self.recorder.stop()
    self.recorder.deleteRecording()
    self.levelTimer.invalidate()
}

我在setupMic()方法中调用了startMonitoring()updateWith()。当使用stopMonitoring()再次更新视图时,我也会调用updateWith() 一旦访问麦克风,音量就会减小。有什么建议?任何修复?

1 个答案:

答案 0 :(得分:3)

修正了问题。音量实际上并没有变得更安静,音频实际上正在传输到耳机。我只需要将音频会话类别选项设置为.DefaultToSpeaker。 AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord, withOptions: [.DefaultToSpeaker])。非常感谢互联网。