Change AVAudioPlayer output to speaker in Swift?

In Swift 3 or 4:

let audioSession = AVAudioSession.sharedInstance()

do {
    try audioSession.overrideOutputAudioPort(AVAudioSessionPortOverride.speaker)
} catch let error as NSError {
    print("audioSession error: \(error.localizedDescription)")
}

To avoid the OSStatus error -50 (mentioned by user462990 in the comments), overrideOutputAudioPort has to be called after setting the session category (code below).

do {
    try session.setCategory(AVAudioSessionCategoryPlayAndRecord)
} catch let error as NSError {
    print("setCategory error: \(error.localizedDescription)")
}

I can understand how this is confusing as I just figured out the answer. So AudioSessionSetProperty was deprecated in iOS 7.

Add this:

session.overrideOutputAudioPort(AVAudioSessionPortOverride.Speaker, error: nil)

Make sure to call AVAudioSession.sharedInstance() first.


try these function.they are work charming.

func SetSessionPlayerOn()
{
    do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord)
    } catch _ {
    }
    do {
        try AVAudioSession.sharedInstance().setActive(true)
    } catch _ {
    }
    do {
        try AVAudioSession.sharedInstance().overrideOutputAudioPort(AVAudioSessionPortOverride.speaker)
    } catch _ {
    }
}
func SetSessionPlayerOff()
{
    do {
        try AVAudioSession.sharedInstance().setActive(false)
    } catch _ {
    }
}

  func SetEarSepeakerOn()
    {
        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord)
        } catch _ {
        }
        do {
            try AVAudioSession.sharedInstance().setActive(true)
        } catch _ {
        }
        do {
            try AVAudioSession.sharedInstance().overrideOutputAudioPort(AVAudioSessionPortOverride.none)
        } catch _ {
        }
    }