2

i'm trying to play audio file from bundle (from project) and its should be silent when user set silent mode of device. my code is here

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

but its show

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

error and not working. pls help.

MAhipal Singh
  • 4,745
  • 1
  • 42
  • 57

1 Answers1

1

Your code has some structural problems. I've cleaned it up a bit for you:

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)
            }
        }
    }

If you're still seeing a "-50" error, make sure your .m4r file is being included in your built application. I was just looking at a related question regarding this a few minutes ago, so the answers there might help you too.

Michael Dautermann
  • 88,797
  • 17
  • 166
  • 215