【问题标题】:Play Audio when an Image is clicked in a UICollectionView在 UICollectionView 中单击图像时播放音频
【发布时间】:2020-07-24 12:27:10
【问题描述】:

我已经在单元格中设置了 UICollectionView 和 UIImage 和 UILabel。当用户点击单元格时,它应该播放与图像相关的特定音频。在指定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、胡萝卜播放 sound2、茄子播放 3 等等。 当我用下面的代码替换它时,它什么也没有。

let filename = vegSoundArray[indexPath.item]

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

我应该如何解决这个错误?

【问题讨论】:

  • 确保从数组中获取正确的声音值。尝试添加调试器并检查。

标签: swift xcode uicollectionview avfoundation


【解决方案1】:

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

【讨论】:

  • 是的,我已经看到了,问题是当我在 forResource 中将“sound1”替换为“filename”时,它没有播放任何内容。此外,当我尝试在 playSound() 中传递文件名变量时,它给了我一个错误“使用未解析的标识符”。我能做些什么来解决这个问题?
  • 确保你没有在它周围加上引号,否则它会寻找一个字面上名为“filename.mp3”的文件。像这样:if let fileURL = Bundle.main.url(forResource: filename, withExtension: "mp3")
  • 非常感谢您的回复!那是我犯的错误,只是删除引号就解决了这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-17
  • 2019-03-25
  • 1970-01-01
  • 2017-08-08
  • 1970-01-01
  • 2012-04-22
相关资源
最近更新 更多