更改播放按钮以在点击时暂停

时间:2019-11-25 15:00:30

标签: ios swift xcode uibutton

我正在使用Xcode 11 Swift构建应用程序,并且我想在我的应用程序中添加mp3文件,到目前为止,我已经做到了

enter image description here

但是我只想显示一个按钮,例如当用户单击播放按钮时,暂停按钮应该显示,反之亦然,我该如何显示呢?这是我播放mp3文件的代码

 @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

2 个答案:

答案 0 :(得分:2)

您可以通过一项功能来做到这一点:

// 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)
    }
}

答案 1 :(得分:1)

您应该保存播放器的状态(或从播放器中询问是否满意)。然后根据状态更新按钮:

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() }