Chand Ninder
Chand Ninder

Reputation: 171

Change play button to pause on click

i am building app with Xcode 11 Swift and i want to add mp3 file in my app and so far i have done this

enter image description here

but i want to show just one button like when user click on play button pause button should display and vice versa, how can i get this ? this is my code to play mp3 file

 @IBAction func Play(_sender: Any) {
           player.play()
 }

 @IBAction func Stop(_sender: Any) {
           player.stop()
 }

let audioPlayer = Bundle.main.path(forResource: "chalisa", ofType: "mp3")
try player = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPlayer!)) as URL

Upvotes: 1

Views: 2686

Answers (2)

Mojtaba Hosseini
Mojtaba Hosseini

Reputation: 120150

You should save the state of the player (or ask from it if you are ok with that). Then update the button based on the state:

enum PlayerState {
    case playing
    case stopped

    mutating func toggle() {
        switch self {
        case .playing: self = .stopped
        case .stopped: self = .playing
        }
    }
}

var state = PlayerState.stopped {
    didSet {
        switch state {
        case .playing: player.play()
        case .stopped: player.stop()
        }
    }
}

@IBAction func buttonDidTouch(_ sender: Any) { state.toggle() }

Upvotes: 1

Vladislav Markov
Vladislav Markov

Reputation: 587

You can do it in one function:

// Note: you should change sender type
@IBAction func buttonPressed(_ sender: UIButton) {
    if player.isPlaying {
        player.stop()
        sender.setImage(yourPlayImage, for: .normal)
    } else {
        player.play()
        sender.setImage(yourPauseImage, for: .normal)
    }
}

Upvotes: 3

Related Questions