Swift AVPlayer 到耳机扬声器

Swift AVPlayer to ear speaker

我有一个简单的音频播放器,效果很好。我正在播放遥控 URL MP3。我的代码:

@IBAction func playAudio(sender: AnyObject) {
        let url = self.productAudio
        let playerItem = AVPlayerItem( URL:NSURL( string:url ) )
        player = AVPlayer(playerItem:playerItem)
        player.
        player.rate = 1.0;
        player.play()
}

但是声音是通过扬声器输出的。如何通过耳机播放音频?

终于找到答案了...

我不得不修改我的音频会话,并覆盖端口。这是播放器代码之前的代码:

    let session = AVAudioSession.sharedInstance()
    var error: NSError?

    session.setCategory(AVAudioSessionCategoryPlayAndRecord, error: &error)
    session.overrideOutputAudioPort(AVAudioSessionPortOverride.None, error: &error)
    session.setActive(true, error: &error)

Swift 5.0

let session = AVAudioSession.sharedInstance()

        do{
            try session.setCategory(.playAndRecord)
            try session.overrideOutputAudioPort(AVAudioSession.PortOverride.none)
            try session.setActive(true)
        } catch {
            print ("\(#file) - \(#function) error: \(error.localizedDescription)")
        }