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
Swift2:
try session.setCategory(AVAudioSessionCategoryPlayAndRecord,
withOptions:AVAudioSessionCategoryOptions.DefaultToSpeaker)
This is an old question, but the other answer did not help me... However, I found a solution which I am posting for future reference in case someone (or myself from the future!) needs it.
The solution is described in the following blog post: iOS: Force audio output to speakers while headphones are plugged in .
You need to create new Objective-C class AudioRouter in your project. Then import AudioRouter.h
into your header file of the class where you are initiating audio functionality. Next, in the corresponding .m
file add the following lines within viewDidLoad
method:
AudioRouter *foobar = [[AudioRouter alloc] init];
[foobar initAudioSessionRouting];
[foobar forceOutputToBuiltInSpeakers];
Now you have audio (e.g. AVAudioPlayer) output forced to loudspeaker! Note that if you plug in earphones while the app is running, then all audio output is directed to earphones.
Swift 5
// Get the singleton instance.
let recordingSession = AVAudioSession.sharedInstance()
do {
// Set the audio session category, mode, and options.
try recordingSession.setCategory(.playAndRecord, mode: .default, options: [.defaultToSpeaker])
try recordingSession.setActive(true)
} catch {
print("Failed to set audio session category.")
}
Check the Developer Documentation for more information about AVAudioSession.CategoryOptions.
Swift 3
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.overrideOutputAudioPort(AVAudioSessionPortOverride.speaker)
} catch let error as NSError {
print("Audio Session error: \(error.localizedDescription)")
}