我试图从bundle(来自项目)播放音频文件,当用户设置设备的静音模式时,它应该是静音的。我的代码在这里
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错误:无法完成操作。 (OSStatus错误-50。)
错误而无法正常工作。请帮助。
答案 0 :(得分:1)
您的代码存在一些结构性问题。我已经为你清理了一下:
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文件包含在您构建的应用程序中。几分钟前,我只是在看at a related question,所以那里的答案也可能对你有所帮助。