From 0ae89aff9fd449da2d6f48b1028c517a74985d16 Mon Sep 17 00:00:00 2001 From: sunxiaojian Date: Tue, 9 Mar 2021 16:54:05 +0800 Subject: [PATCH] fix: can't play audio again when stoped --- .../ViewModel/AudioContainerViewModel.swift | 5 ++--- Mastodon/Service/AudioPlayer.swift | 17 ++++++++++++----- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/Mastodon/Scene/Share/ViewModel/AudioContainerViewModel.swift b/Mastodon/Scene/Share/ViewModel/AudioContainerViewModel.swift index de250a53..303eae2a 100644 --- a/Mastodon/Scene/Share/ViewModel/AudioContainerViewModel.swift +++ b/Mastodon/Scene/Share/ViewModel/AudioContainerViewModel.swift @@ -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 { diff --git a/Mastodon/Service/AudioPlayer.swift b/Mastodon/Service/AudioPlayer.swift index 95be2e78..15168c76 100644 --- a/Mastodon/Service/AudioPlayer.swift +++ b/Mastodon/Service/AudioPlayer.swift @@ -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) {