【问题标题】:Swift Audio from Video: Default to speaker视频中的 Swift 音频:默认为扬声器
【发布时间】:2017-09-10 00:24:27
【问题描述】:

我正在尝试在 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()

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

稍后在同一个应用程序中,我使用上述 AVAudioSession 的相同行播放音频文件,效果很好。之后,如果我重播视频,声音会像我想要的那样从扬声器上发出。但为什么不是第一次发生呢?

【问题讨论】:

  • 您是否设置了音频会话类别并激活了会话?如果有,属于哪个类别?如果您设置了一个类别,您可以将.OptionDefaultToSpeaker 设置为应该也可以工作的选项。这个问答说你的方法是更“瞬态”的版本,符合你所听到的:developer.apple.com/library/content/qa/qa1754/_index.html

标签: ios swift3 avfoundation avplayer


【解决方案1】:

只需使用选项.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)")
}

【讨论】:

  • 我申请了这个类别,声音来自耳机,但只有一侧在播放声音,另一侧不起作用。有什么线索吗?
猜你喜欢
  • 2020-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多