ios - 在 Swift 中使用 AV Audio Player 有条件地播放音频

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

最佳答案

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/

相关文章:

html - 解析 HTML NSRegularExpression

ios - 将 Quartz 用于小型图形项目

ios - 编码和解码函数如何使用 NSCoding 在 Swift 3 中工作?

ios - Rx swift : UISwitch toggle back to initial State

ios - 当我们关闭两个 View Controller 时如何不显示中间屏幕并调用 viewWillAppear

ios - 选择器越界异常

swift - 设计 Swift API 时的可选项

audio - 如何访问扬声器播放的波形?

iphone - 添加音频文件iPhone应用程序

audio - 在哪里可以获得 G722 免费源代码?