2

I just converted to Swift 3 and I need help with this error. I got this error when I converted to swift 3 yesterday and this full code was working great. I put a try? in it but the it did not fix the error at all it stayed the same.

import Foundation
import AVFoundation

class AudioHelper: NSObject, AVAudioPlayerDelegate {
    var player : AVAudioPlayer?


    class var defaultHelper : AudioHelper {
        struct Static {
            static let instance : AudioHelper = AudioHelper()
        }

        return Static.instance
    }

    override init() {
        super.init()
    }

    func initializeAudio() {
        let url = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("", ofType: "")!)
        self.player = try! AVAudioPlayer(contentsOfURL: url, fileTypeHint: nil)
        self.player?.numberOfLoops = -1
        self.player?.play()        
    }

    func stopAudio() {
        self.player?.stop()
        self.player?.prepareToPlay()
    }

    func startAudio() {
          AVAudioSession.sharedInstance().setActive(true, error: nil)
          self.player?.play()
    }


    func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) {
        AVAudioSession.sharedInstance().setActive(false, error: nil)
    }
}
M_G
  • 1,208
  • 1
  • 11
  • 16
Bran
  • 151
  • 2
  • 11
  • http://i.stack.imgur.com/irdef.png image of error – Bran Sep 13 '16 at 21:24
  • 2
    Take a look at [the documentation](https://developer.apple.com/reference/avfoundation/avaudiosession/1616597-setactive) for the method `setActive(_:)` – it throws instead of taking an error parameter. Therefore just delete the error parameter and prefix the call with a `try?` if you don't care about an error being thrown. – Hamish Sep 13 '16 at 21:29
  • Also probably better dupe target [Swift 2 AVAudioSession setCategory extra argument 'error'](http://stackoverflow.com/questions/32878965/swift-2-avaudiosession-setcategory-extra-argument-error) – Hamish Sep 13 '16 at 21:35
  • This is not helping me with my answer, its different. – Bran Sep 13 '16 at 22:42
  • @Hamish is saying change your two instances of ```AVAudioSessiom.sharedInstance().setActive(false, error: nil)``` to ```try? AVAudioSession.sharedInstance().setActive(false)``` since the signature changed in Swift 3 – Robert Masen Sep 14 '16 at 01:30
  • Should be `AVAudioPlayer(contentsOf: url` – Leo Dabus Sep 14 '16 at 02:43
  • You should use `Bundle.main.url(forResource:` method to get yiur url – Leo Dabus Sep 14 '16 at 02:46
  • http://stackoverflow.com/questions/30280519/how-to-play-audio-in-background-swift/30280699#30280699 – Leo Dabus Sep 14 '16 at 02:47

1 Answers1

2

You can handle the exception in these ways:

do {
        try AVAudioSession.sharedInstance().setActive(true)
} catch {

}

Without catching:

try? AVAudioSession.sharedInstance().setActive(true)
M_G
  • 1,208
  • 1
  • 11
  • 16