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

Play Audio when an Image is clicked in a UICollectionView

我已经在单元格中设置了带有 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()}

问题是当我 运行 这段代码时,所有单元格都只播放“声音 1”,而不是 brocolli 播放声音 1、胡萝卜播放声音 2、茄子播放声音 3 等等。 当我用以下代码替换它时,它什么也没播放。

let filename = vegSoundArray[indexPath.item]

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

我该如何解决这个错误?

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