我有10个不同的按钮,每个按钮都有一个与之关联的唯一标签。所有按钮都链接到相同的IBAction。我可以根据与单击的特定按钮关联的标签播放不同的声音。
import AVFoundation
var myAudio: AVAudioPlayer!
let path = Bundle.main.path(forResource: "sound1", ofType: "wav")!
let url = URL(fileURLWithPath: path)
do {
let sound = try AVAudioPlayer(contentsOf: url)
myAudio = sound
sound.play()
} catch {
//
}
}
答案 0 :(得分:1)
喜欢
@objc func yourbtnActionName(_ sender : UIButton){
switch sender.tag {
case 1:
commonSoundCode(name: "sound1")
break
case 2:
commonSoundCode(name: "yoursecondSoundname")
break
default:
break
}
}
然后是常用方法
func commonSoundCode(name: String){
let path = Bundle.main.path(forResource: name, ofType: "wav")!
let url = URL(fileURLWithPath: path)
do {
let sound = try AVAudioPlayer(contentsOf: url)
myAudio = sound
sound.play()
} catch {
//
}
}
选项2
如果您的声音文件的顺序相同,例如(sound1.wav,sound2.wav ......,sound10.wav)则调用
@objc func yourbtnActionName(_ sender : UIButton){
let path = Bundle.main.path(forResource: "sound\(sender.tag)", ofType: "wav")!
let url = URL(fileURLWithPath: path)
do {
let sound = try AVAudioPlayer(contentsOf: url)
myAudio = sound
sound.play()
} catch {
//
}
}
答案 1 :(得分:0)
您只需根据UIButton's
tag
播放声音。
@IBAction func playsound(_ sender: UIButton)
{
switch sender.tag
{
case 0:
//Sound for Button with tag=0
case 1:
//Sound for Button with tag=1
default:
//Default Sound
}
}
在上面的代码中,根据您的UIButton
tags
添加更多案例。
请添加更多代码,以便更清楚地了解您的问题。