I have a bug here where a set of headphones is plugged in during the audio capture, the audio capture still happens through the onboard microphone and playback is through the speakers. I am trying to capture this audio via the audio port if a headset is plugged in and is in use. Here is the copy of my code:
@IBAction func recordAudio(_ sender: UIButton) {
isPlayingRecording = false;
if endTime == nil {
self.startTimer()
}
recordingInProgress.text = "Recording"
recordingInProgress.isHidden = false
stopButton.isHidden = false
recordButton.isEnabled = false
setSecondaryView()
let dirPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let recordingName = "\(exercise!.exerciseId).m4a"
let pathArray = [dirPath, recordingName]
filePath = NSURL.fileURL(withPathComponents: pathArray) as NSURL?
//Set up audio session
let session = AVAudioSession.sharedInstance()
do {
try session.setCategory(AVAudioSessionCategoryPlayAndRecord)
} catch _ {
}
do {
// setup how audio is going to be used (ie. audio parameters, categories, speaker)
try session.overrideOutputAudioPort(AVAudioSessionPortOverride.speaker)
} catch _ {
}
//Initialize and prepare the recorder
audioRecorder = nil
do {
let recordSettings: [String : AnyObject] = [AVFormatIDKey:Int(kAudioFormatMPEG4AAC) as AnyObject,
AVSampleRateKey:44100.0 as AnyObject,
AVNumberOfChannelsKey:1 as AnyObject,
AVEncoderAudioQualityKey:AVAudioQuality.medium.rawValue as AnyObject
]
try audioRecorder = AVAudioRecorder(url: filePath! as URL, settings:recordSettings)
} catch _ {
}
if audioRecorder != nil {
audioRecorder.delegate = self //This statement makes "RecordViewController" a delegate of "AVAudioRecorder", so that we can use "audioRecorderDidFinishRecording" function later on
audioRecorder.isMeteringEnabled = true
audioRecorder.prepareToRecord()
audioRecorder.record()
}
//Start count up timer if the exercise doesn't have a attempt time constraint.
if(exercise != nil && exercise?.skill != nil && exercise!.skill.respondtime == nil && exercise!.skill.respondtime!.intValue > 0) {
startTime = Date().timeIntervalSince1970
timerLabel.isHidden = false
timerLabel.text = readableSecondString(0.0) as String
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(RecordSoundsViewController.tick), userInfo: nil, repeats: true)
}
}
How do I get this to capture the audio through the audio port/headphone jack when a set of headphones is plugged in? I'm doing this using Swift.