Reputation: 171
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
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
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
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