来自视频的Swift音频:默认为扬声器

时间:2017-04-13 18:54:12

标签: ios swift3 avfoundation avplayer

我正在尝试在iPhone上播放视频,如果视频中的音频出现在iPhone扬声器上,那将是理想的选择。

但是,我在控制台上收到此错误:

  

audioSession错误:无法完成操作。 (OSStatus错误-50。)

这是我的代码::

    let player = AVPlayer(url: video_url)

    let audioSession = AVAudioSession.sharedInstance()

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

    // get the lenght of the video
    self.video_duration = getMediaDuration(url: video_url) + 0.25

    // notification for when video is over.
    NotificationCenter.default.addObserver(self, selector: #selector(self.playerDidFinish), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player.currentItem)

    // the video controller...
    let controller = AVPlayerViewController()
    controller.view.frame = self.view.frame
    controller.player = player
    controller.showsPlaybackControls = false
    controller.view.tag = 99
    self.video_ctrl = controller

    // add controller as subview
    self.view.addSubview(controller.view)
    controller.player?.play()

我用Google搜索了错误,但没有看到任何结果。 任何帮助表示赞赏。

稍后在同一个应用程序中,我使用上面相同的行播放音频文件 AVAudioSession ,这样就可以了。在那之后,如果我重播视频,声音就会出现在扬声器上,就像我想要的那样。但为什么它不是第一次发生?

1 个答案:

答案 0 :(得分:2)

只需使用选项.defaultToSpeaker

do {
    try AVAudioSession.sharedInstance().setActive(false)
    try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: .defaultToSpeaker)
    try AVAudioSession.sharedInstance().setActive(true)
} catch let error as NSError {
    print("AVAudioSession error: \(error.localizedDescription)")
}