在AVFoundation中使用相同按钮播放/暂停和循环音频

时间:2016-06-21 12:47:43

标签: ios iphone swift avfoundation

我尝试将操作链接到相同的按钮,但这会使按钮完全停止工作。如果我创建一个单独的按钮,我可以使用相同的代码使用它:

@IBAction func Play(sender: AnyObject) {
    SoundPlayer.play()
}

@IBAction func stop(sender: AnyObject) {        
    SoundPlayer.stop()
}

我还需要音频循环。

使用Nirav代码:

class ViewController: UIViewController {

   var SoundPlayer:AVAudioPlayer = AVAudioPlayer()

   @IBOutlet var btnPlay: UIButton!
   @IBOutlet var btnStop: UIButton!

   override func viewDidLoad() {
      super.viewDidLoad()

      let FileLocation = NSBundle.mainBundle().pathForResource("Aspirin", ofType: ".mp3")


      do {
          SoundPlayer = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: FileLocation!))


          try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
          try AVAudioSession.sharedInstance().setActive(true)

      }

      catch {
          print(error)
      }

   }

   override func didReceiveMemoryWarning() {
      super.didReceiveMemoryWarning()
   }

   @IBAction func btnTap(sender: UIButton) {
      if (sender == self.btnPlay) {
      }
      else if (sender == self.btnStop) {
      }
   }
}

1 - 故事板的屏幕截图

1 个答案:

答案 0 :(得分:0)

你可以这样做只需创建这个按钮的IBOutlet

@IBOutlet var btnPlay: UIButton!

现在将此操作绑定到两个按钮

@IBaction func btnTap(sender: UIButton) {
     if (!sender.selected) {
         SoundPlayer.play()
     }
     else {
         SoundPlayer.stop()
     }
     sender.selected = !sender.selected
}

希望这会对你有所帮助