gpt4 book ai didi

ios - 快速播放多种声音

转载 作者:可可西里 更新时间:2023-11-01 02:16:52 26 4
gpt4 key购买 nike

我正在尝试添加多个按钮来播放专用声音,即;按钮 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 的新手,在 objective-c 中,我为每个按钮写出了每个 IBAction。然后我修改了代码,将所有按钮绑定(bind)到一个 Action ,并使用标签来确定按下了哪个按钮。我能用 swift 进行这种类型的整合吗?任何帮助将不胜感激。

最佳答案

替换你的,

  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 那么每个条件都会变为真!!

希望这会有所帮助:)

关于ios - 快速播放多种声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37317335/

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