我希望能够在最多按两次按钮时播放音频。按两次按钮后,即使按下也不再播放音频。我目前有这个代码,但它不起作用,我不确定我哪里出错:
var soundFileURLRef: NSURL!
var audioPlayer = AVAudioPlayer?()
var audioCounter = 0
override func viewDidLoad() {
super.viewDidLoad()
// setup for audio
let playObjects = NSBundle.mainBundle().URLForResource("mathsinfo", withExtension: "mp3")
self.soundFileURLRef = playObjects
do {
audioPlayer = try AVAudioPlayer(contentsOfURL: soundFileURLRef)
} catch _ {
audioPlayer = nil
}
audioPlayer?.delegate = self
audioPlayer?.prepareToPlay()
}
//function for counting times audio is played
func countAudio() {
if ((audioPlayer?.play()) != nil) {
++audioCounter
}
}
//MARK: Actions
//action for button playing the audio
@IBAction func playMathsQuestion(sender: AnyObject) {
countAudio()
if audioCounter < 2 {
audioPlayer?.play()
}
}
答案 0 :(得分:0)
您的代码中的countAudio
函数会因为您调用audioPlayer?.play()
而异步播放声音。仅当audioCounter
为零时,audioPlayer
变量才会递增。试试这个版本
var soundFileURLRef: NSURL!
var audioPlayer: AVAudioPlayer?
var audioCounter = 0
override func viewDidLoad() {
super.viewDidLoad()
// setup for audio
let playObjects = NSBundle.mainBundle().URLForResource("mathsinfo", withExtension: "mp3")
self.soundFileURLRef = playObjects
audioPlayer = try? AVAudioPlayer(contentsOfURL: soundFileURLRef)
audioPlayer?.delegate = self
audioPlayer?.prepareToPlay()
}
//MARK: Actions
//action for button playing the audio
@IBAction func playMathsQuestion(sender: AnyObject) {
if (audioPlayer != nil) {
if (audioCounter < 2 && audioPlayer!.play()) {
++audioCounter
}
}
}
您可以在此处看到我们首先检查以确保audioPlayer
不是零。在此之后,我们只在audioPlayer!.play()
时进行audioCounter < 2
调用。对play()
的调用返回一个布尔值,当音频成功排队等待播放时,该布尔值为真(参见documentation),在这种情况下,我们增加audioCounter
。
我还使用audioPlayer
版本的try简化了try?
的初始化,当被调用者抛出时,返回nil
。