【发布时间】: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