Swift 2:为阵列中的不同图像播放声音

时间:2016-03-20 12:30:42

标签: arrays swift audio avfoundation playback

我有一系列图片

var cardImages = ["bellota", "manzana", "botas"]

我创建了myAudioPlayer来播放声音

let filePath = NSBundle.mainBundle().pathForResource("correct", ofType: "wav")

    if let filePath = filePath
    {

        let filePathURL = NSURL(fileURLWithPath: filePath)

        do {

            try myAudioPlayer = AVAudioPlayer(contentsOfURL: filePathURL)


        } catch {

            print("error")

        }

    }

更改图像的下一步按钮

  @IBAction func nextButtonTapped(sender: UIButton) {

    if imageIndex < 0 {

        imageIndex = maxImages
    }


    cardImageView.image = UIImage(named: cardImages[imageIndex])

    imageIndex++

    if imageIndex > maxImages {

        imageIndex = 0
    }

    cardImageView.image = UIImage(named: cardImages[imageIndex])
}

playSound按钮: 我想用这种方法做的是在图像变化时播放声音。为阵列中的每个图像添加不同的声音。我怎样才能做到这一点?例如,“apple”将播放sound1,“orange”将在按下下一张图像时播放声音

 @IBAction func playButtonTapped(sender: UIButton) {


    myAudioPlayer.play()


}

1 个答案:

答案 0 :(得分:1)

将音频加载隔离到功能中:

func setTrack(audioName: String){


    let filePath = NSBundle.mainBundle().pathForResource(audioName, ofType: "wav")

    if let filePath = filePath
    {

        let filePathURL = NSURL(fileURLWithPath: filePath)

        do {

            try myAudioPlayer = AVAudioPlayer(contentsOfURL: filePathURL)


        } catch {

            print("error")

        }

    }
}

然后,在nextButtonPressed:

@IBAction func nextButtonTapped(sender: UIButton) {

    if imageIndex < 0 {

        imageIndex = maxImages
    }


    cardImageView.image = UIImage(named: cardImages[imageIndex])

    imageIndex++

    if imageIndex > maxImages {

        imageIndex = 0
    }

    cardImageView.image = UIImage(named: cardImages[imageIndex])
    self.setTrack(audioList[imageIndex]) // or any other index you need/you have
}