Force audio file playback through iPhone loud speaker using Swift

ぐ巨炮叔叔 提交于 2019-12-04 04:04:49

EDIT July 2017: Refer to Husam's answer for the Swift 2.0 solution.

As of Swift 1.2, you use overrideOutputAudioPort and AVAudioSessionPortOverride. It can be implemented by doing something like this:

if !session.overrideOutputAudioPort(AVAudioSessionPortOverride.Speaker, error:&error) {
   println("could not set output to speaker")
   if let e = error {
      println(e.localizedDescription)
   }
}

I'm working on an app that uses this now, and I have a function called setSessionPlayandRecord, which looks like:

func setSessionPlayAndRecord() {
    let session:AVAudioSession = AVAudioSession.sharedInstance()
    var error: NSError?
    if !session.setCategory(AVAudioSessionCategoryPlayAndRecord, error:&error) {
        println("could not set session category")
        if let e = error {
            println(e.localizedDescription)
        }
    }
    if !session.overrideOutputAudioPort(AVAudioSessionPortOverride.Speaker, error:&error) {
        println("could not set output to speaker")
        if let e = error {
            println(e.localizedDescription)
        }
    }
    if !session.setActive(true, error: &error) {
        println("could not make session active")
        if let e = error {
            println(e.localizedDescription)
        }
    }
}

Swift 2.0 Code

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 _ {
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!