fix: can't play audio again when stoped

This commit is contained in:
sunxiaojian 2021-03-09 16:54:05 +08:00
parent 5a17b8a6ee
commit 0ae89aff9f
2 changed files with 14 additions and 8 deletions

View File

@ -20,8 +20,7 @@ class AudioContainerViewModel {
audioView.playButton.publisher(for: .touchUpInside)
.sink { _ in
let isPlaying = AudioPlayer.shared.playbackState.value == .readyToPlay || AudioPlayer.shared.playbackState.value == .playing
if isPlaying {
if AudioPlayer.shared.isPlaying() {
AudioPlayer.shared.pause()
} else {
if audioAttachment === AudioPlayer.shared.attachment {
@ -70,7 +69,7 @@ class AudioContainerViewModel {
.receive(on: DispatchQueue.main)
.sink(receiveValue: { playbackState in
if audioAttachment === AudioPlayer.shared.attachment {
let isPlaying = playbackState == .playing || playbackState == .readyToPlay
let isPlaying = AudioPlayer.shared.isPlaying()
audioView.playButton.isSelected = isPlaying
audioView.slider.isEnabled = isPlaying
if playbackState == .stopped {

View File

@ -44,7 +44,11 @@ extension AudioPlayer {
}
if audioAttachment == attachment {
if self.playbackState.value == .stopped {
self.seekToTime(time: 0)
}
player.play()
self.playbackState.value = .playing
return
}
@ -52,7 +56,7 @@ extension AudioPlayer {
player.replaceCurrentItem(with: playerItem)
attachment = audioAttachment
player.play()
playbackState.send(PlaybackState.playing)
playbackState.value = .playing
}
func addObserver() {
@ -99,20 +103,23 @@ extension AudioPlayer {
.store(in: &disposeBag)
NotificationCenter.default.publisher(for: .AVPlayerItemDidPlayToEndTime, object: nil)
.sink { _ in
self.playbackState.send(PlaybackState.stopped)
self.playbackState.value = .stopped
self.currentTimeSubject.value = 0
}
.store(in: &disposeBag)
}
func isPlaying() -> Bool {
return self.playbackState.value == .readyToPlay || self.playbackState.value == .playing
}
func resume() {
player.play()
playbackState.send(PlaybackState.playing)
playbackState.value = .playing
}
func pause() {
player.pause()
playbackState.send(PlaybackState.paused)
playbackState.value = .paused
}
func seekToTime(time: TimeInterval) {