使用Swift中的AV Audio Player播放条件音频

时间:2015-12-18 11:01:46

标签: ios swift audio avaudioplayer

我希望能够在最多按两次按钮时播放音频。按两次按钮后,即使按下也不再播放音频。我目前有这个代码,但它不起作用,我不确定我哪里出错:

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()
    }
}

1 个答案:

答案 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