How to get AVAudioPlayer output to the speaker

32,385

Solution 1

I realize this question is fairly old but when I was struggling with the same problem I found a simple solution that hopefully will help anyone else looking to use the louder media speakers as opposed to the receiver speakers. The method I used was setting up the audio session with the DefaultToSpeaker option in AVAudioSessionCategoryOptions:

In Swift (assuming your audio session is named session) -

session.setCategory(AVAudioSessionCategoryPlayAndRecord, withOptions:AVAudioSessionCategoryOptions.DefaultToSpeaker, error: nil)

In Obj-C -

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker error: nil];

Solution 2

Swift 3

Before recording the sound I set:

AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord)

and before playback I set:

AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)

Objective C

before recording:

[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryRecord error:nil];

before playback:

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:nil];

Solution 3

This works great for me in Swift2

let session = AVAudioSession.sharedInstance()
try! session.setCategory(AVAudioSessionCategoryPlayAndRecord, withOptions: AVAudioSessionCategoryOptions.DefaultToSpeaker)

Solution 4

Swift2:

try session.setCategory(AVAudioSessionCategoryPlayAndRecord,
    withOptions:AVAudioSessionCategoryOptions.DefaultToSpeaker)

Solution 5

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.

Share:
32,385
dizy
Author by

dizy

a.b.c.d.fishes m.n.o.fishes s.a.r.fishes e.d.b.d.fishes o.i.c.d.fishes

Updated on January 14, 2021

Comments

  • dizy
    dizy over 3 years

    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. However the sound is coming out of the ear speaker, not the loud speaker. How would I go about redirecting the sound to the loud speaker ?

    TIA!