2015-12-18 144 views
1

我希望能够通过最多按两次按钮来播放音频。按下按钮两次后,即使按下它也不应再播放音频。我有这样的代码当前,但它不工作,我不确定我要去的地方错了:在Swift中使用AV音频播放器进行条件音频播放

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

在你的代码的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不为零。在此之后,我们仅在audioCounter < 2时拨打audioPlayer!.play()。对play()的调用返回一个布尔值,当音频成功排队等待播放时返回true(见documentation),在这种情况下,我们增加audioCounter

我还简化了初始化audioPlayer通过使用try?版本的try,返回nil当callee抛出时。