I\'m recording audio with AVAudioRecorder as seen in How do I record audio on iPhone with AVAudioRecorder?
I then use AVAudioPlayer to play back the recording. Howev
this is the key line to output auido in speaker instead in microphone. Note it should be set while recording
try AVAudioSession.sharedInstance().overrideOutputAudioPort(AVAudioSessionPortOverride.speaker)
Below is complete function to setup recording
private func setupRecorder() {
if isAudioRecordingGranted {
let session = AVAudioSession.sharedInstance()
do {
if #available(iOS 10.0, *) {
try! session.setCategory(.playAndRecord, mode:.spokenAudio)
}
else {
// Workaround until https://forums.swift.org/t/using-methods-marked-unavailable-in-swift-4-2/14949 isn't fixed
session.perform(NSSelectorFromString("setCategory:error:"), with: AVAudioSession.Category.playback)
}
try session.setActive(true)
try session.overrideOutputAudioPort(AVAudioSession.PortOverride.speaker)
let settings = [
AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
AVSampleRateKey: 44100,
AVNumberOfChannelsKey: 2,
AVEncoderAudioQualityKey:AVAudioQuality.high.rawValue
]
audioRecorder = try AVAudioRecorder(url: fileUrl(), settings: settings)
audioRecorder.delegate = self
audioRecorder.isMeteringEnabled = true
audioRecorder.prepareToRecord()
self.recorderState = .Ready
}
catch let error {
recorderState = .error(error)
}
}
else {
recorderState = .Failed("Don't have access to use your microphone.")
}
}