0

Please explain me the code below. `@IBAction func notePressed(_ sender: UIButton) {

    guard let url = Bundle.main.url(forResource: "note\(sender.tag)", withExtension: "wav") else {
        print("url not found")
        return
    }

    do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        try AVAudioSession.sharedInstance().setActive(true)

        player = try AVAudioPlayer(contentsOf: url)
        //player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.wav.rawValue)
        player?.play()
    } catch let error {
        print(error.localizedDescription)
    }`

Here are some questions: 1. Should I really use init(contentOf:fileTypeHint:) method or I can use init(contentOf:) only? What is the difference? 2. AVAudioSession.. When I just comment 2 line of code starting with "try", my app still work fine. Why do I need AVAudioSession? Thanks to everyone who is willing to help.

djaflienda
  • 31
  • 6
  • `AVAudioSession.sharedInstance().setActive(true)` activates your app's audio session, which might fail when a higher priority audio session (like a phone call) is active, in that case it'll throw an `isBusy` error. – justintime Oct 16 '18 at 09:44
  • Does it mean that if I won't use "setActive()" method and start playing sound, after receiving a phone call my sound won't be stopped? It seems I faced with that kind of bug earlier. – djaflienda Oct 16 '18 at 10:05
  • That behaviour depends on the category you set for your audioSession. Check this answer : https://stackoverflow.com/a/29027722/3074641. – justintime Oct 16 '18 at 11:24

0 Answers0