【问题标题】:Swift 2: play sound for different images in arraySwift 2:为数组中的不同图像播放声音
【发布时间】:2016-03-20 12:30:42
【问题描述】:

我得到了一组图像

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])
}

播放声音按钮: 我在这种方法中尝试做的是在图像发生变化时播放声音。阵列中的每个图像都有不同的声音。我怎样才能做到这一点?例如“apple”会播放声音1,“orange”会在按下下一张图片时播放声音2

 @IBAction func playButtonTapped(sender: UIButton) {


    myAudioPlayer.play()


}

【问题讨论】:

  • 它是否在您保存声音数组的同一个控制器中?
  • 是的。它在同一个控制器中。

标签: arrays swift audio avfoundation playback


【解决方案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
}

【讨论】:

  • self.setTrack(audioList[imageIndex]) 为此我收到错误消息:“使用未解析的标识符'audioList'
  • audioList 是您歌曲的数组
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-25
  • 1970-01-01
  • 1970-01-01
  • 2012-10-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多