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

View File

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