1

我正在尝试根据用户选择的乐器播放歌曲。这是我的代码:

@IBAction func 播放(发件人: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 {


            }


        }
    }

}

除了instrumentSelect.selectedSegmentIndex == 1. 我不知道为什么。我得到一个EXC_BAD_INSTRUCTIONfatal error: unexpectedly found nil while unwrapping an Optional value。该文件工作正常,我已经多次清理该项目。我已经正确输入了所有内容。为什么那个不工作?我对此感到非常困惑,感谢您的帮助。

4

1 回答 1

0

该文件未添加到应用程序目标。它仅添加到项目中。感谢@matt 帮助我。

于 2015-11-22T18:24:09.470 回答