audioSession error: The operation couldn’t be completed. (OSStatus error -50.)

audioSession error: The operation couldn’t be completed. (OSStatus error -50.)

我正在尝试从捆绑包(来自项目)播放音频文件,当用户设置设备的静音模式时它应该是静音的。我的代码在这里

 let audioSession = AVAudioSession.sharedInstance()
ringURl = Bundle.main.url(forResource: "ring", withExtension: "m4r")
do {
try audioSession.setCategory(AVAudioSessionCategorySoloAmbient)
try audioSession.overrideOutputAudioPort(speakerType)
}
do {
player = try AVAudioPlayer(contentsOf: ringURl)
guard let player = player else { return }
player?.prepareToPlay()
player?.play()
} catch let error as NSError {
print(error.description)
}
} catch let error as NSError {
print("audioSession error: \(error.localizedDescription)")
}

但它的显示

audioSession error: The operation couldn’t be completed. (OSStatus error -50.)

错误且无法正常工作。请帮助。

您的代码存在一些结构问题。我已经为您整理了一下:

class ViewController: UIViewController {

    var audioSession = AVAudioSession.sharedInstance() // we only need to instantiate this once
    var player : AVAudioPlayer? // making this a property means player doesn't get released as soon as playSomething exits

    @IBAction func playSomething(sender: UIButton!)
    {
        if let ringURl = Bundle.main.url(forResource: "ring", withExtension: "m4r")
        {
            do {
                try audioSession.setCategory(AVAudioSessionCategorySoloAmbient)
                try audioSession.overrideOutputAudioPort(.speaker)
            } catch let error as NSError {
                print("audioSession error: \(error.localizedDescription)")
            }

            do {
                let ourPlayer = try AVAudioPlayer(contentsOf: ringURl)
                ourPlayer.prepareToPlay()
                ourPlayer.play()
                self.player = ourPlayer
            } catch let error as NSError {
                print(error.description)
            }
        }
    }

如果您仍然看到“-50”错误,请确保您的 .m4r 文件包含在您构建的应用程序中。几分钟前我刚刚在 看这个问题,所以那里的答案也可能对你有帮助。