在UICollectionView中单击图像时播放音频

时间:2020-07-24 04:09:41

标签: swift xcode uicollectionview avfoundation

我已经在单元格中设置了带有UIImage和UILabel的UICollectionView。当用户点击该单元格时,它应播放与图像关联的特定音频。指定import AVFoundation

后,我已实现以下代码来播放音频
var vegImageArray = ["broccoli","carrot","eggplant", "garlic", "onion", "spinach", "tomato"]

var vegLabelArray = ["Broccoli", "Carrot", "Eggplant", "Garlic", "Onion", "Spinach", "Tomato"]

var vegSoundArray = ["sound1", "sound2", "sound3", "sound4", "sound5", "sound6", "sound7"]



func playsound() {
    

    do {
        if let fileURL = Bundle.main.url(forResource: "sound1", withExtension: "mp3") {
            audioPlayer = try AVAudioPlayer(contentsOf: fileURL)
        }
        else {
            print("No file exists")
        }
    } catch let error {
        print("Can't play error \(error.localizedDescription)")
    }
    audioPlayer?.play()
}


func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

let filename = vegSoundArray[indexPath.item]

playSound()}

问题是,当我运行此代码时,所有单元格都只播放“ sound1”,而不是brocolli播放sound1,声音为2的胡萝卜,声音为3的茄子等等。 当我用下面的代码替换它时,它什么也没起作用。

let filename = vegSoundArray[indexPath.item]

        do {
                if let fileURL = Bundle.main.url(forResource: "filename", withExtension: "mp3")

我应该如何解决此错误?

1 个答案:

答案 0 :(得分:0)

您的代码每次都在播放sound1,因为您已经在forResource: "sound1"中对其进行了硬编码。您应该将filename变量传递到playsound()中,并将其用作forResource arg