从字符串数组播放声音 Swift

Play Sound From String Arrays Swift

我正在尝试为集合视图中的每个图像播放一个声音文件,因此如果用户点击一个图像,用户将听到该图像的名称。例如,如果用户点击猫的图像,用户将听到声音文件 "cat"。我创建了图像的集合视图,并将 UITapGestureRecognizer 添加到单元格中。声音文件在代码最底部的 imageTapped 函数中播放,但我不知道如何编写代码。我不知道之后要编码什么:if tap.state == .recognized, let imageView = tap.view as? UIImageView { 该函数中的当前代码已构建,但我在点击每个图像时听不到声音。我真的很感激任何帮助。

class FlashcardsViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource  {

var animals = ["alligator", "bat", "bear", "beaver", "bird", "butterfly", "camel", "cat", "cheetah", "chicken"]

var bodyparts = ["arm", "ear", "eyes", "foot", "hair", "hand", "head", "leg", "mouth", "nose"]

var classroom = ["backpack", "blackboard", "book", "bookshelf", "calculator", "chair", "chalk", "chalkboard", "clock", "colored pencil"]

var clothes = ["belt", "boots", "coat", "dress", "hat", "jeans", "mittens", "pajamas", "pants", "scarf"]

var family = ["baby", "brother", "dad", "family", "grandma", "grandpa", "grandparents", "mom", "parents", "sister"]

var feelings = ["angry", "cold", "confused", "happy", "hot", "hurt", "sad", "scared", "sick", "tired"]

var food = ["apple", "bacon", "banana", "bean", "blackberry", "blueberry", "broccoli", "butter", "carrot", "cereal"]

var house = ["bathtub", "bed", "bowl", "couch", "cup", "dresser", "fridge", "lamp", "mirror", "plant"]

var transportation = ["ambulance", "bike", "boat", "bus", "car", "firetruck", "helicopter", "motorcycle", "police car", "plane"]

var verbs = ["brush your teeth", "carry", "clap", "color", "cook", "crawl", "cut", "dance", "draw", "drink"]

@IBOutlet weak var collectionView: UICollectionView!

@IBOutlet weak var segmentedControl: UISegmentedControl!

var audioPlayer = AVAudioPlayer()

override func viewDidLoad() {
    super.viewDidLoad()

    let tap = UITapGestureRecognizer(target: self, action: #selector(self.imageTapped(tap:)))
    view.addGestureRecognizer(tap)

}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    let arrays = [animals, bodyparts, classroom, clothes, family, feelings, food, house, transportation, verbs]
    let sectionArray = arrays[segmentedControl.selectedSegmentIndex]
    return sectionArray.count

}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionViewCell

    let arrays = [animals, bodyparts, classroom, clothes, family, feelings, food, house, transportation, verbs]

    cell.imageView?.image = UIImage(named: arrays[segmentedControl.selectedSegmentIndex][indexPath.row])

    cell.isUserInteractionEnabled = true

    return cell

}

@IBAction func segmentedControlAction(_ sender: Any) {

    collectionView.reloadData()

}

func playSound(file: String?) {

    if let file = file {
        let musicFile = URL(fileURLWithPath: file)

        do{

            try audioPlayer = AVAudioPlayer(contentsOf: musicFile)

            audioPlayer.play()

        }catch{

        }
    }
}
@objc func imageTapped(tap: UITapGestureRecognizer) {

    _ = tap.view as? UIImageView

    print("imageTapped")

    let arrays = [animals, bodyparts, classroom, clothes, family, feelings, food, house, transportation, verbs]
     let sectionArray = arrays[segmentedControl.selectedSegmentIndex]

    if tap.state == .recognized, let imageView = tap.view as? UIImageView {
        for (image) in sectionArray {
            imageView.image = UIImage (named: image)
            if let sound = Bundle.main.path(forResource: image, ofType: "wav") {
                playSound(file: sound)
            }
        }
    }
}

}

尝试在 collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)

中调用 playSound(file: String?)

从所选单元格中查找图像

我认为你把事情搞得比你需要的更复杂了。

首先你要多次创建你的arrays,没有必要这样做。你可以这样做

var arrays =  [[String]]()

override func viewDidLoad() {
  super.viewDidLoad()

  // populate the array when your view loads
  arrays = [animals, bodyparts, classroom, clothes, family, feelings, food, house, transportation, verbs]

}

这意味着在您的 cellForItemAt 中您不需要在那里构造它,但您可以访问刚刚创建的 arrays 变量。对于 UICollectionView,您应该使用 indexPath.item 而不是 indexPath.rowindexPath.row 用于 UITableView。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

  let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as CollectionViewCell

  let array = arrays[segmentedControl.selectedSegmentIndex]

  cell.imageView?.image = UIImage(named: array[indexPath.item])

  cell.isUserInteractionEnabled = true

  return cell

}

您也不需要使用手势识别器。 UICollectionViews 带有一个名为 didSelectItemAt 的函数,当您点击单元格时会调用该函数。所以你可以做这样的事情。您可能想在播放下一个文件之前检查文件是否已经在播放。

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  let array = arrays[segmentedControl.selectedSegmentIndex]
  let filename = array[indexPath.item]
  if let filepath = Bundle.main.path(forResource: filename, ofType: "wav") {
    playSound(file: filepath)
  }
}

此外,您最初使用文件名创建的所有那些数组,您应该将它们声明为 let,除非您计划更改它们的内容。使用 letvar 的性能更高。 var 只应在您计划更改存储的值时使用。

所以改变

var animals = ["alligator", "bat", "bear", "beaver", "bird", "butterfly", "camel", "cat", "cheetah", "chicken"]

let animals = ["alligator", "bat", "bear", "beaver", "bird", "butterfly", "camel", "cat", "cheetah", "chicken"]

查看 Apple 文档以获取有关 UICollectionView 的更多信息https://developer.apple.com/documentation/uikit/uicollectionview