我希望最多可以按两次按钮来播放音频。按下按钮两次后,即使按下也不会再播放音频。我目前有这段代码,但它不起作用,我不确定我哪里出错了:
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()
}
}
最佳答案
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()
当音频成功排队等待播放时返回一个 bool 值(见 documentation ),在这种情况下我们递增 audioCounter
.
我还简化了 audioPlayer
的初始化通过使用 try?
返回 nil
的 try 版本当被调用者抛出时。
关于ios - 在 Swift 中使用 AV Audio Player 有条件地播放音频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34354120/