2017-04-13 48 views
2

我试图在iPhone上播放视频,如果视频中的音频在iPhone扬声器上播放出来,这将是理想选择。视频中的快速音频:默认为扬声器

不过,我得到我的控制台上的错误:

audioSession error: The operation couldn’t be completed. (OSStatus error -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

你有设置一个音频会话类和启动会话?如果是这样,哪一类?如果您设置了一个类别,您可以将'.OptionDefaultToSpeaker'设置为应该也适用的选项。这个问答说,你的方法是更“暂时”的版本,这符合你所听到的:https://developer.apple.com/library/content/qa/qa1754/_index.html –

回答

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)") 
} 
+0

我应用了这个类别,声音来自耳机,但只有一方在播放对方没有工作的声音。任何线索? –

相关问题