Search code examples
xcodeswiftavaudioplayerexc-bad-instruction

AVAudioPath not working - Swift


I am trying to play a song based on the instrument the user selects. Here is my code:

@IBAction func play(sender: AnyObject) {

    if isPlaying == false {
        player.play()
        isPlaying = true
    }

}
@IBAction func stop(sender: AnyObject) {

    if isPlaying == true {
        player.stop()
        isPlaying = false
    }

}
@IBAction func pause(sender: AnyObject) {

    if isPlaying == true {
        isPlaying = false
        player.pause()
    }

}



var player = AVAudioPlayer()
var audioPath = NSBundle.mainBundle().pathForResource("Iditarod Bass", ofType: "m4a")

var isPlaying = Bool()

@IBOutlet var instrumentSelect: UISegmentedControl!


@IBAction func didChangeInstrument(sender: AnyObject) {

    if isPlaying == false {

        if instrumentSelect.selectedSegmentIndex == 0 {

            audioPath = NSBundle.mainBundle().pathForResource("Iditarod Bass", ofType: "m4a")

            do {
                try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath!))
            } catch {


            }

        } else if instrumentSelect.selectedSegmentIndex == 1 {

            audioPath = NSBundle.mainBundle().pathForResource("Iditarod Cello", ofType: "m4a")

                do {
                    try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath!))
                } catch {


                }


        } else if instrumentSelect.selectedSegmentIndex == 2 {

            audioPath = NSBundle.mainBundle().pathForResource("Iditarod Viola", ofType: "m4a")
            do {
                try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath!))
            } catch {


            }

        } else if instrumentSelect.selectedSegmentIndex == 3 {

            audioPath = NSBundle.mainBundle().pathForResource("Iditarod Violin 1", ofType: "m4a")

            do {
                try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath!))
            } catch {


            }

        } else if instrumentSelect.selectedSegmentIndex == 4 {

            audioPath = NSBundle.mainBundle().pathForResource("Iditarod Violin 2", ofType: "m4a")

            do {
                try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath!))

            } catch {


            }


        }
    }

}

All of them work fine except for the instrumentSelect.selectedSegmentIndex == 1. I don't know why. I get an EXC_BAD_INSTRUCTION that says fatal error: unexpectedly found nil while unwrapping an Optional value. The file is working fine, and I have cleaned the project numerous times. I have typed everything correctly. Why is that one not working? I am very confused about this, and I appreciate your help.


Solution

  • The file was not being added to the app target. It was added to the project only. Thanks @matt for helping me.