我正在尝试添加多个按钮来播放专用声音,即按钮1播放声音1,按钮2播放声音2,按钮3播放声音3,依此类推。我尝试过使用以下代码:
import UIKit
import AVFoundation
class ViewController: UIViewController {
var PlaySound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("tea-pot-whistle", ofType: "wav")!)
var Sound1audioPlayer = AVAudioPlayer()
var pianoSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("wind_1234", ofType: "wav")!)
var Sound2audioPlayer = AVAudioPlayer()
var pianoSound2 = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Evil_Laugh", ofType: "wav")!)
var Sound3audioPlayer = AVAudioPlayer()
@IBOutlet weak var Btn1 : UIButton!
@IBOutlet weak var Btn2 : UIButton!
@IBOutlet weak var Btn3 : UIButton!
@IBAction func likedThis(sender: UIButton) {
if (Btn1.tag == 1){
Sound1audioPlayer.play()
}
if(Btn2.tag == 2){
Sound2audioPlayer.play()
}
if (Btn3.tag == 3){
Sound3audioPlayer.play()
}
/*
CFBundleRef mainBundle = CFBundleGetMainBundle();
CFURLRef soundFileURLRef;
soundFileURLRef = CFBundleCopyResourceURL(mainBundle, (CFStringRef) @"givewater", CFSTR ("wav"), NULL);
UInt32 SoundID;
AudioServicesCreateSystemSoundID(soundFileURLRef, &SoundID);
AudioServicesPlaySystemSound(SoundID);*/
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
Btn1.tag = 1;
Btn2.tag = 2;
Btn3.tag = 3;
Sound1audioPlayer = try! AVAudioPlayer(contentsOfURL: pianoSound)
Sound2audioPlayer = try! AVAudioPlayer(contentsOfURL: PlaySound)
Sound3audioPlayer = try! AVAudioPlayer(contentsOfURL: pianoSound2)
Sound1audioPlayer.prepareToPlay()
Sound2audioPlayer.prepareToPlay()
Sound3audioPlayer.prepareToPlay()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
此代码播放声音,但根据按下的按钮,它会播放所有三个声音。我是swift的新手,在目标c中我为每个按钮写了每个IBAction。然后我修改了代码以将所有按钮绑定到单个动作,并使用标签来确定按下了哪个按钮。我能用swift进行这种类型的整合吗?任何帮助都会非常感激。
答案 0 :(得分:1)
替换你的,
if (Btn1.tag == 1){
Sound1audioPlayer.play()
}
if(Btn2.tag == 2){
Sound2audioPlayer.play()
}
if (Btn3.tag == 3){
Sound3audioPlayer.play()
}
与
if (sender.tag == 1){
Sound1audioPlayer.play()
}
if(sender.tag == 2){
Sound2audioPlayer.play()
}
if (sender.tag == 3){
Sound3audioPlayer.play()
}
你应该使用sender.tag !!如果你检查btn.tag,那么每个条件都将成为现实!!
希望这会有所帮助:)