Mike C Mike C - 5 months ago 33
Swift Question

Using same button to Play/Pause and loop audio in AVFoundation

I have tried linking the action to the same button but this stops the button from working altogether. I can get it working using the same code if I create a separate button:

@IBAction func Play(sender: AnyObject) {


SoundPlayer.play()
}

@IBAction func stop(sender: AnyObject) {

SoundPlayer.stop()
}


I also need the audio to loop.

Using Nirav code:

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 - Screenshot of storyboard

Answer

You can do that just create IBOutlet of both button like this

@IBOutlet var btnPlay: UIButton!

Now bind this action to both button

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

Hope this will help you