2017-10-28 126 views
1

我看到這個意外的行爲,帶有AVAudioPlayer的暫停()函數。當我點擊'暫停'按鈕時,音頻實際上應該在當前時間暫停,並在調用play()時從其中恢復。但在這裏,當我點擊暫停()時音頻暫停,當我點擊play()時,音頻從頭開始播放。暫停()的行爲就像stop()。AVAudioPlayer暫停()不像預期的那樣運行

var player: AVAudioPlayer = AVAudioPlayer() 

@IBAction func PlayPauseAudioButton(_ sender: UIButton) { 
    if sender.currentImage == #imageLiteral(resourceName: "play-btn") { 
     sender.setImage(#imageLiteral(resourceName: "pause-btn"), for: .normal) 

     do { 
      let audioPath = Bundle.main.path(forResource: "aug-ps-raj", ofType: "mp3") 
      try player = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL) 
     } catch { 
      // Catch the error 
     } 
     player.play() 

    } else { 
     sender.setImage(#imageLiteral(resourceName: "play-btn"), for: .normal) 
     player.pause() 

    } 
} 

回答

2

問題是,您每次單擊播放按鈕時都會創建一個新播放器實例。相反,您可以提前創建該實例並僅在按鈕點擊處理程序中調用play()和pause()。

相關問題