improved the code so that we can use the AudioPlayerState directly to check the playback speed and added localization

This commit is contained in:
Mauro Romito
2026-02-19 16:05:58 +01:00
committed by Mauro
parent 285f8b7834
commit 3dfcb6912f
13 changed files with 51 additions and 48 deletions
@@ -20,6 +20,7 @@
"a11y_paused_voice_message" = "Voice message, duration: %1$@, current position: %2$@"; "a11y_paused_voice_message" = "Voice message, duration: %1$@, current position: %2$@";
"a11y_pin_field" = "PIN field"; "a11y_pin_field" = "PIN field";
"a11y_play" = "Play"; "a11y_play" = "Play";
"a11y_playback_speed" = "Playback speed";
"a11y_poll_end" = "Ended poll"; "a11y_poll_end" = "Ended poll";
"a11y_polls_will_remove_selection" = "Will remove previous selection"; "a11y_polls_will_remove_selection" = "Will remove previous selection";
"a11y_polls_winning_answer" = "This is the winning answer"; "a11y_polls_winning_answer" = "This is the winning answer";
@@ -20,6 +20,7 @@
"a11y_paused_voice_message" = "Voice message, duration: %1$@, current position: %2$@"; "a11y_paused_voice_message" = "Voice message, duration: %1$@, current position: %2$@";
"a11y_pin_field" = "PIN field"; "a11y_pin_field" = "PIN field";
"a11y_play" = "Play"; "a11y_play" = "Play";
"a11y_playback_speed" = "Playback speed";
"a11y_poll_end" = "Ended poll"; "a11y_poll_end" = "Ended poll";
"a11y_polls_will_remove_selection" = "Will remove previous selection"; "a11y_polls_will_remove_selection" = "Will remove previous selection";
"a11y_polls_winning_answer" = "This is the winning answer"; "a11y_polls_winning_answer" = "This is the winning answer";
@@ -4,9 +4,6 @@
/* Used for testing */ /* Used for testing */
"untranslated" = "Untranslated"; "untranslated" = "Untranslated";
// MARK: - Voice message playback speed
"a11y_playback_speed" = "Playback speed %1$@";
// MARK: - Soft logout // MARK: - Soft logout
"soft_logout_signin_title" = "Sign in"; "soft_logout_signin_title" = "Sign in";
@@ -458,4 +458,17 @@ enum VoiceMessagePlaybackSpeed: Float, CaseIterable, Codable {
case fast = 1.5 case fast = 1.5
case fastest = 2.0 case fastest = 2.0
case slow = 0.5 case slow = 0.5
var label: String {
switch self {
case .default, .fastest:
rawValue.formatted(.number.precision(.fractionLength(0))) + "×"
case .fast, .slow:
rawValue.formatted(.number.precision(.fractionLength(1))) + "×"
}
}
var placeholder: String {
0.0.formatted(.number.precision(.fractionLength(1))) + "×"
}
} }
@@ -10,10 +10,6 @@ import Foundation
// swiftlint:disable explicit_type_interface function_parameter_count identifier_name line_length // swiftlint:disable explicit_type_interface function_parameter_count identifier_name line_length
// swiftlint:disable nesting type_body_length type_name vertical_whitespace_opening_braces // swiftlint:disable nesting type_body_length type_name vertical_whitespace_opening_braces
internal enum UntranslatedL10n { internal enum UntranslatedL10n {
/// Playback speed %1$@
internal static func a11yPlaybackSpeed(_ p1: Any) -> String {
return UntranslatedL10n.tr("Untranslated", "a11y_playback_speed", String(describing: p1))
}
/// Clear all data currently stored on this device? /// Clear all data currently stored on this device?
/// Sign in again to access your account data and messages. /// Sign in again to access your account data and messages.
internal static var softLogoutClearDataDialogContent: String { return UntranslatedL10n.tr("Untranslated", "soft_logout_clear_data_dialog_content") } internal static var softLogoutClearDataDialogContent: String { return UntranslatedL10n.tr("Untranslated", "soft_logout_clear_data_dialog_content") }
+2
View File
@@ -64,6 +64,8 @@ internal enum L10n {
internal static var a11yPinField: String { return L10n.tr("Localizable", "a11y_pin_field") } internal static var a11yPinField: String { return L10n.tr("Localizable", "a11y_pin_field") }
/// Play /// Play
internal static var a11yPlay: String { return L10n.tr("Localizable", "a11y_play") } internal static var a11yPlay: String { return L10n.tr("Localizable", "a11y_play") }
/// Playback speed
internal static var a11yPlaybackSpeed: String { return L10n.tr("Localizable", "a11y_playback_speed") }
/// Poll /// Poll
internal static var a11yPoll: String { return L10n.tr("Localizable", "a11y_poll") } internal static var a11yPoll: String { return L10n.tr("Localizable", "a11y_poll") }
/// Ended poll /// Ended poll
@@ -8,17 +8,17 @@
import SwiftUI import SwiftUI
struct PlaybackSpeedButton: View { struct PlaybackSpeedButton: View {
let speed: Float let speed: VoiceMessagePlaybackSpeed
let onTap: () -> Void let onTap: () -> Void
var body: some View { var body: some View {
Button(action: onTap) { Button(action: onTap) {
ZStack { ZStack {
Text("0.0x") Text(speed.placeholder)
.font(.compound.bodyXSSemibold) .font(.compound.bodyXSSemibold)
.hidden() .hidden()
Text(speedLabel) Text(speed.label)
.font(.compound.bodyXSSemibold) .font(.compound.bodyXSSemibold)
.foregroundColor(.compound.iconSecondary) .foregroundColor(.compound.iconSecondary)
} }
@@ -27,25 +27,17 @@ struct PlaybackSpeedButton: View {
.background(.compound.bgCanvasDefault, in: RoundedRectangle(cornerRadius: 12)) .background(.compound.bgCanvasDefault, in: RoundedRectangle(cornerRadius: 12))
} }
.buttonStyle(.plain) .buttonStyle(.plain)
.accessibilityLabel(UntranslatedL10n.a11yPlaybackSpeed(speedLabel)) .accessibilityLabel(L10n.a11yPlaybackSpeed)
} .accessibilityValue(speed.label)
private var speedLabel: String {
if speed == Float(Int(speed)) {
"\(Int(speed))x"
} else {
String(format: "%gx", speed)
}
} }
} }
struct PlaybackSpeedButton_Previews: PreviewProvider, TestablePreview { struct PlaybackSpeedButton_Previews: PreviewProvider, TestablePreview {
static var previews: some View { static var previews: some View {
HStack(spacing: 8) { HStack(spacing: 8) {
PlaybackSpeedButton(speed: 0.5) { } ForEach(VoiceMessagePlaybackSpeed.allCases, id: \.self) { speed in
PlaybackSpeedButton(speed: 1.0) { } PlaybackSpeedButton(speed: speed) { }
PlaybackSpeedButton(speed: 1.5) { } }
PlaybackSpeedButton(speed: 2.0) { }
} }
.padding() .padding()
.background(Color.gray) .background(Color.gray)
@@ -422,14 +422,14 @@ class TimelineInteractionHandler {
let availableSpeeds = VoiceMessagePlaybackSpeed.allCases let availableSpeeds = VoiceMessagePlaybackSpeed.allCases
guard let currentIndex = availableSpeeds.firstIndex(of: appSettings.voiceMessagePlaybackSpeed) else { guard let currentIndex = availableSpeeds.firstIndex(of: appSettings.voiceMessagePlaybackSpeed) else {
appSettings.voiceMessagePlaybackSpeed = .default appSettings.voiceMessagePlaybackSpeed = .default
audioPlayerState(for: itemID)?.setPlaybackSpeed(VoiceMessagePlaybackSpeed.default.rawValue) audioPlayerState(for: itemID)?.setPlaybackSpeed(VoiceMessagePlaybackSpeed.default)
return return
} }
let nextIndex = (currentIndex + 1) % availableSpeeds.count let nextIndex = (currentIndex + 1) % availableSpeeds.count
let nextSpeed = availableSpeeds[nextIndex] let nextSpeed = availableSpeeds[nextIndex]
appSettings.voiceMessagePlaybackSpeed = nextSpeed appSettings.voiceMessagePlaybackSpeed = nextSpeed
audioPlayerState(for: itemID)?.setPlaybackSpeed(nextSpeed.rawValue) audioPlayerState(for: itemID)?.setPlaybackSpeed(nextSpeed)
} }
func playPauseAudio(for itemID: TimelineItemIdentifier) async { func playPauseAudio(for itemID: TimelineItemIdentifier) async {
@@ -461,7 +461,6 @@ class TimelineInteractionHandler {
// Ensure this one is attached // Ensure this one is attached
if !audioPlayerState.isAttached { if !audioPlayerState.isAttached {
audioPlayerState.attachAudioPlayer(audioPlayer) audioPlayerState.attachAudioPlayer(audioPlayer)
audioPlayerState.setPlaybackSpeed(appSettings.voiceMessagePlaybackSpeed.rawValue)
} }
// Detach all other states // Detach all other states
@@ -518,7 +517,9 @@ class TimelineInteractionHandler {
let playerState = AudioPlayerState(id: .timelineItemIdentifier(itemID), let playerState = AudioPlayerState(id: .timelineItemIdentifier(itemID),
title: L10n.commonVoiceMessage, title: L10n.commonVoiceMessage,
duration: voiceMessageRoomTimelineItem.content.duration, duration: voiceMessageRoomTimelineItem.content.duration,
waveform: voiceMessageRoomTimelineItem.content.waveform) waveform: voiceMessageRoomTimelineItem.content.waveform,
playbackSpeed: appSettings.voiceMessagePlaybackSpeed,
playbackSpeedPublisher: appSettings.$voiceMessagePlaybackSpeed)
mediaPlayerProvider.register(audioPlayerState: playerState) mediaPlayerProvider.register(audioPlayerState: playerState)
return playerState return playerState
} }
@@ -115,7 +115,6 @@ struct TimelineViewState: BindableState {
var isViewSourceEnabled: Bool var isViewSourceEnabled: Bool
var areThreadsEnabled: Bool var areThreadsEnabled: Bool
var linkPreviewsEnabled: Bool var linkPreviewsEnabled: Bool
var voiceMessagePlaybackSpeed = VoiceMessagePlaybackSpeed.default.rawValue
let hasPredecessor: Bool let hasPredecessor: Bool
@@ -102,7 +102,6 @@ class TimelineViewModel: TimelineViewModelType, TimelineViewModelProtocol {
isViewSourceEnabled: appSettings.viewSourceEnabled, isViewSourceEnabled: appSettings.viewSourceEnabled,
areThreadsEnabled: appSettings.threadsEnabled, areThreadsEnabled: appSettings.threadsEnabled,
linkPreviewsEnabled: appSettings.linkPreviewsEnabled, linkPreviewsEnabled: appSettings.linkPreviewsEnabled,
voiceMessagePlaybackSpeed: appSettings.voiceMessagePlaybackSpeed.rawValue,
hasPredecessor: roomProxy.predecessorRoom != nil, hasPredecessor: roomProxy.predecessorRoom != nil,
pinnedEventIDs: roomProxy.infoPublisher.value.pinnedEventIDs, pinnedEventIDs: roomProxy.infoPublisher.value.pinnedEventIDs,
emojiProvider: emojiProvider, emojiProvider: emojiProvider,
@@ -543,11 +542,6 @@ class TimelineViewModel: TimelineViewModelType, TimelineViewModelProtocol {
appSettings.$threadsEnabled appSettings.$threadsEnabled
.weakAssign(to: \.state.areThreadsEnabled, on: self) .weakAssign(to: \.state.areThreadsEnabled, on: self)
.store(in: &cancellables) .store(in: &cancellables)
appSettings.$voiceMessagePlaybackSpeed
.map(\.rawValue)
.weakAssign(to: \.state.voiceMessagePlaybackSpeed, on: self)
.store(in: &cancellables)
userSession.clientProxy.timelineMediaVisibilityPublisher userSession.clientProxy.timelineMediaVisibilityPublisher
.removeDuplicates() .removeDuplicates()
@@ -6,6 +6,7 @@
// Please see LICENSE files in the repository root for full details. // Please see LICENSE files in the repository root for full details.
// //
import Combine
import Foundation import Foundation
import SwiftUI import SwiftUI
@@ -23,7 +24,7 @@ struct VoiceMessageRoomTimelineView: View {
} }
struct VoiceMessageRoomTimelineContent: View { struct VoiceMessageRoomTimelineContent: View {
@EnvironmentObject private var context: TimelineViewModel.Context @Environment(\.timelineContext) private var context
@State private var resumePlaybackAfterScrubbing = false @State private var resumePlaybackAfterScrubbing = false
let timelineItem: VoiceMessageRoomTimelineItem let timelineItem: VoiceMessageRoomTimelineItem
@@ -34,32 +35,31 @@ struct VoiceMessageRoomTimelineContent: View {
onPlayPause: onPlaybackPlayPause, onPlayPause: onPlaybackPlayPause,
onSeek: { onPlaybackSeek($0) }, onSeek: { onPlaybackSeek($0) },
onScrubbing: { onPlaybackScrubbing($0) }, onScrubbing: { onPlaybackScrubbing($0) },
playbackSpeed: context.viewState.voiceMessagePlaybackSpeed,
onPlaybackSpeedChange: onPlaybackSpeedChange) onPlaybackSpeedChange: onPlaybackSpeedChange)
.fixedSize(horizontal: false, vertical: true) .fixedSize(horizontal: false, vertical: true)
} }
private func onPlaybackPlayPause() { private func onPlaybackPlayPause() {
context.send(viewAction: .handleAudioPlayerAction(.playPause(itemID: timelineItem.id))) context?.send(viewAction: .handleAudioPlayerAction(.playPause(itemID: timelineItem.id)))
} }
private func onPlaybackSpeedChange() { private func onPlaybackSpeedChange() {
context.send(viewAction: .handleAudioPlayerAction(.changePlaybackSpeed(itemID: timelineItem.id))) context?.send(viewAction: .handleAudioPlayerAction(.changePlaybackSpeed(itemID: timelineItem.id)))
} }
private func onPlaybackSeek(_ progress: Double) { private func onPlaybackSeek(_ progress: Double) {
context.send(viewAction: .handleAudioPlayerAction(.seek(itemID: timelineItem.id, progress: progress))) context?.send(viewAction: .handleAudioPlayerAction(.seek(itemID: timelineItem.id, progress: progress)))
} }
private func onPlaybackScrubbing(_ dragging: Bool) { private func onPlaybackScrubbing(_ dragging: Bool) {
if dragging { if dragging {
if playerState.playbackState == .playing { if playerState.playbackState == .playing {
resumePlaybackAfterScrubbing = true resumePlaybackAfterScrubbing = true
context.send(viewAction: .handleAudioPlayerAction(.playPause(itemID: timelineItem.id))) context?.send(viewAction: .handleAudioPlayerAction(.playPause(itemID: timelineItem.id)))
} }
} else { } else {
if resumePlaybackAfterScrubbing { if resumePlaybackAfterScrubbing {
context.send(viewAction: .handleAudioPlayerAction(.playPause(itemID: timelineItem.id))) context?.send(viewAction: .handleAudioPlayerAction(.playPause(itemID: timelineItem.id)))
resumePlaybackAfterScrubbing = false resumePlaybackAfterScrubbing = false
} }
} }
@@ -19,7 +19,6 @@ struct VoiceMessageRoomPlaybackView: View {
let onPlayPause: () -> Void let onPlayPause: () -> Void
let onSeek: (Double) -> Void let onSeek: (Double) -> Void
let onScrubbing: (Bool) -> Void let onScrubbing: (Bool) -> Void
let playbackSpeed: Float
let onPlaybackSpeedChange: () -> Void let onPlaybackSpeedChange: () -> Void
var body: some View { var body: some View {
@@ -28,7 +27,8 @@ struct VoiceMessageRoomPlaybackView: View {
size: .medium, size: .medium,
action: onPlayPause) action: onPlayPause)
VStack(spacing: 2) { VStack(spacing: 2) {
PlaybackSpeedButton(speed: playbackSpeed, onTap: onPlaybackSpeedChange) PlaybackSpeedButton(speed: playerState.playbackSpeed,
onTap: onPlaybackSpeedChange)
Text(timeLabelContent) Text(timeLabelContent)
.lineLimit(1) .lineLimit(1)
.font(.compound.bodyXSSemibold) .font(.compound.bodyXSSemibold)
@@ -135,7 +135,6 @@ struct VoiceMessageRoomPlaybackView_Previews: PreviewProvider, TestablePreview {
onPlayPause: { }, onPlayPause: { },
onSeek: { value in Task { await playerState.updateState(progress: value) } }, onSeek: { value in Task { await playerState.updateState(progress: value) } },
onScrubbing: { _ in }, onScrubbing: { _ in },
playbackSpeed: playerState.playbackSpeed,
onPlaybackSpeedChange: { }) onPlaybackSpeedChange: { })
.fixedSize(horizontal: false, vertical: true) .fixedSize(horizontal: false, vertical: true)
} }
@@ -36,7 +36,7 @@ class AudioPlayerState: ObservableObject, Identifiable {
/// It's similar to `playbackState`, with the a difference: `.loading` /// It's similar to `playbackState`, with the a difference: `.loading`
/// updates are delayed by a fixed amount of time /// updates are delayed by a fixed amount of time
@Published private(set) var playerButtonPlaybackState: AudioPlayerPlaybackState @Published private(set) var playerButtonPlaybackState: AudioPlayerPlaybackState
@Published private(set) var playbackSpeed: Float = 1.0 @Published private(set) var playbackSpeed: VoiceMessagePlaybackSpeed
private weak var audioPlayer: AudioPlayerProtocol? private weak var audioPlayer: AudioPlayerProtocol?
private var audioPlayerSubscription: AnyCancellable? private var audioPlayerSubscription: AnyCancellable?
@@ -59,14 +59,21 @@ class AudioPlayerState: ObservableObject, Identifiable {
displayLink != nil displayLink != nil
} }
init(id: AudioPlayerStateIdentifier, title: String, duration: Double, waveform: EstimatedWaveform? = nil, progress: Double = 0.0) { init(id: AudioPlayerStateIdentifier, title: String,
duration: Double,
waveform: EstimatedWaveform? = nil,
progress: Double = 0.0,
playbackSpeed: VoiceMessagePlaybackSpeed = .default,
playbackSpeedPublisher: AnyPublisher<VoiceMessagePlaybackSpeed, Never>? = nil) {
self.id = id self.id = id
self.title = title self.title = title
self.duration = duration self.duration = duration
self.waveform = waveform ?? EstimatedWaveform(data: []) self.waveform = waveform ?? EstimatedWaveform(data: [])
self.progress = progress self.progress = progress
self.playbackSpeed = playbackSpeed
playbackState = .stopped playbackState = .stopped
playerButtonPlaybackState = .stopped playerButtonPlaybackState = .stopped
playbackSpeedPublisher?.assign(to: &$playbackSpeed)
setupPlaybackStateSubscription() setupPlaybackStateSubscription()
} }
@@ -98,6 +105,7 @@ class AudioPlayerState: ObservableObject, Identifiable {
playbackState = .loading playbackState = .loading
self.audioPlayer = audioPlayer self.audioPlayer = audioPlayer
subscribeToAudioPlayer(audioPlayer: audioPlayer) subscribeToAudioPlayer(audioPlayer: audioPlayer)
setPlaybackSpeed(playbackSpeed)
} }
func detachAudioPlayer() { func detachAudioPlayer() {
@@ -112,9 +120,9 @@ class AudioPlayerState: ObservableObject, Identifiable {
playbackState = .error playbackState = .error
} }
func setPlaybackSpeed(_ speed: Float) { func setPlaybackSpeed(_ speed: VoiceMessagePlaybackSpeed) {
playbackSpeed = speed playbackSpeed = speed
audioPlayer?.setPlaybackSpeed(speed) audioPlayer?.setPlaybackSpeed(speed.rawValue)
} }
// MARK: - Private // MARK: - Private