-1

I have the following code, I always get a breakpoint on "try btnSound". Not sure where I'm doing wrong. The Sound file is in main folder.

import UIKit

import AVFoundation

class ViewController: UIViewController {

    @IBOutlet weak var outputLbl: UILabel!

    var btnSound: AVAudioPlayer = AVAudioPlayer()


    override func viewDidLoad() {
        super.viewDidLoad()

        let path = Bundle.main.path(forResource: "btn", ofType: "wav")

        do {

            try btnSound = AVAudioPlayer(contentsOf: URL(fileURLWithPath: path!))

            btnSound.prepareToPlay()

        } catch let err as NSError {
            print(err.debugDescription)
        }

    }
    @IBAction func numberPressed(btn: UIButton!){
        btnSound.play()
    }

}
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
iCodeByte
  • 571
  • 1
  • 7
  • 21
  • Your code claims there is a file _btn.wav_ in your app bundle. There isn’t. The term `path!` means “crash if there is no such path.” Thus, you crash. You crashed because that is what you said to do. – matt Dec 29 '18 at 08:16
  • What do you mean by 'main folder'? – Upholder Of Truth Dec 29 '18 at 08:26
  • try to add another sound file in bundle and play. – Kuldeep Dec 29 '18 at 11:06
  • matt - Thanks for the reply. "btn.wav" file is already present in my bundle, but still it doesn't play the sound. "main folder" means my audio file is present in bundle itself. Below is my files structure: - filename.xcodeproject - filename - btn.wav - AppDelegate.swift - ViewController.swift and so on – iCodeByte Dec 29 '18 at 14:40

1 Answers1

0

OK. Thank you, people. I just used:

var audioPlayer = AVAudioPlayer()

    let source = Bundle.main.path(forResource: "btn", ofType: "wav")

    do {
        audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: source!))
        audioPlayer.prepareToPlay()
    } catch let err as NSError {
        print(err.debugDescription)
    }

I renamed "path" to "sound" and it started working. Not sure what exactly the issue was.

iCodeByte
  • 571
  • 1
  • 7
  • 21