gpt4 book ai didi

swift - 如何根据UIimageview图像一键播放声音

转载 作者:行者123 更新时间:2023-11-30 10:40:28 24 4
gpt4 key购买 nike

我为 children 开发了一个功能齐全的闪存卡应用程序。它有一个 UIImageView,可以通过手势点击循环浏览 26 张卡片 (abcs),还有一个音乐按钮,可以为每个图像播放声音。现在我已经 100% 工作了,但是声音在 IF 语句中播放,该语句添加了额外的 400 行代码。

音乐按钮的示例:

        if (imageView.image?.isEqual(UIImage(named: "card1")))! {
do { audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: aSound))
audioPlayer.play()
} catch {
print("Couldn't load sound file")
}
}
else if (imageView.image?.isEqual(UIImage(named: "card2")))! {
do { audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: bSound))
audioPlayer.play()
} catch {
print("Couldn't load sound file")
}
}
else if (imageView.image?.isEqual(UIImage(named: "card3")))! {
do { audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: cSound))
audioPlayer.play()
} catch {
print("Couldn't load sound file")
}
}

我知道我可以设置一个包含声音文件的声音阵列,但我如何将它绑回卡上?我无法在 Assets 图像上设置标签属性,可以吗?

寻找一种方法来缩短我当前的代码。

最佳答案

这是我会采用的一种方法。还没有测试过,但它应该可以帮助你。!我使用数组,但 Set 或 Dictionary 也可以。

1)创建一个结构体

struct Card {
let soundURL: URL
let image: UIImage
}

2)将所有卡片收集到一个数组中:

let cards: [Card] = {
var collection = [Card]()
let soundPaths: [String] = ["aSound", "bSound", "xSound", "zSound"]
let cardNames: [String] = ["card1", "card2", "card25", "card26"]

// array of all 26 urls
var soundUrls: [URL] {
var urls = [URL]()
for path in soundPaths {
urls.append(URL(fileURLWithPath: path))
}
return urls
}

// array of all 26 images
var cardImages: [UIImage] {
var images = [UIImage]()
for name in cardNames {
guard let image = UIImage(contentsOfFile: name) else { continue }
images.append(image)
}
return images
}

// not the best approach but if you have sound and naming
// in the order then:
for idx in 0..<26 {
let card = Card(soundURL: soundUrls[idx], image: cardImages[idx])
collection.append(card)
}

return collection
}()

3)为UIImage添加扩展来播放声音:

extension UIImage {
func playSound() {
let card = cards.filter { $0.image == self }.first
if card != nil {
do {
let audioPlayer = try AVAudioPlayer(contentsOf: card!.soundURL)
audioPlayer.play()
} catch {
print("Couldn't load the sound file with error: \(error)")
}
}
}
}

然后,当您获得 imageView.image 时,您应该能够执行以下操作:

imageView.image?.playSound()

我再次没有对此进行测试,但我认为逻辑仍然成立。希望对您有所帮助。

关于swift - 如何根据UIimageview图像一键播放声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56914986/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com