feat(lyrics): let synced lyrics run later or earlier than playback

Audio over Bluetooth reaches the listener late, so synced lyrics ran
ahead of what was heard (#753). Lyrics settings gain Lyrics timing: a
slider from 2 s earlier to 2 s later in 0.1 s steps, saved on release,
with a reset.

The offset moves every line and word of the player's lyrics and the
desktop mini player's, so line focus, word sweeps and countdowns follow
it together. Tapping a line still seeks to where it is sung, and a
long-pressed line opens sharing with its own time.
This commit is contained in:
zarzet committed 2026-10-29 23:58:23 +07:00
1 parent 22e3536dd5
commit 152bb36d2e
12 files changed
+353 -5

No files matched your search

+29
View File
@@ -8633,6 +8633,35 @@
"@lyricsBlurOff": {
"description": "Value of the lyrics blur slider at zero"
},
"lyricsOffset": "Lyrics timing",
"@lyricsOffset": {
"description": "Setting: move synced lyrics earlier or later than playback"
},
"lyricsOffsetSubtitle": "Show synced lyrics later or earlier, for example when Bluetooth audio arrives late",
"lyricsOffsetNone": "In sync",
"@lyricsOffsetNone": {
"description": "Value of the lyrics timing slider at zero"
},
"lyricsOffsetLater": "{seconds} s later",
"@lyricsOffsetLater": {
"description": "Value of the lyrics timing slider when lyrics follow playback late",
"placeholders": {
"seconds": {
"type": "String",
"example": "0.3"
}
}
},
"lyricsOffsetEarlier": "{seconds} s earlier",
"@lyricsOffsetEarlier": {
"description": "Value of the lyrics timing slider when lyrics run ahead of playback",
"placeholders": {
"seconds": {
"type": "String",
"example": "0.3"
}
}
},
"appCrashTitle": "The app previously crashed",
"appAnrTitle": "The app previously stopped responding",
"@appAnrTitle": {
+5
View File
@@ -7956,6 +7956,11 @@
"lyricsBlur": "Blur lirik",
"lyricsBlurSubtitle": "Seberapa samar baris di sekitar baris yang sedang diputar",
"lyricsBlurOff": "Mati",
"lyricsOffset": "Waktu lirik",
"lyricsOffsetSubtitle": "Tampilkan lirik tersinkron lebih lambat atau lebih cepat, misalnya saat audio Bluetooth tertunda",
"lyricsOffsetNone": "Sinkron",
"lyricsOffsetLater": "{seconds} dtk lebih lambat",
"lyricsOffsetEarlier": "{seconds} dtk lebih cepat",
"appCrashTitle": "Aplikasi sebelumnya mengalami crash",
"appAnrTitle": "Aplikasi sebelumnya berhenti merespons",
"@appAnrTitle": {
+19
View File
@@ -21,6 +21,15 @@ const String kLyricsBlurKey = 'lyrics_blur';
/// it off, 1 is the default.
double normalizeLyricsBlur(num? value) =>
value != null && value.isFinite ? value.toDouble().clamp(0.0, 1.5) : 1.0;
const String kLyricsOffsetKey = 'lyrics_offset_ms';
const int kMaxLyricsOffsetMs = 2000;
/// How much later synced lyrics follow playback, in milliseconds, so they
/// match audio that reaches the ears late (such as over Bluetooth). Negative
/// values show them earlier.
int normalizeLyricsOffsetMs(num? value) => value != null && value.isFinite
? value.round().clamp(-kMaxLyricsOffsetMs, kMaxLyricsOffsetMs)
: 0;
const String kMornyeGlassClarityKey = 'mornye_glass_clarity';
const String kMornyeGlassOutlinesKey = 'mornye_glass_outlines';
const double kDefaultMornyeGlassClarity = 0.75;
@@ -65,6 +74,7 @@ class ThemeSettings {
final String customFontName;
final double lyricsTextScale;
final double lyricsBlur;
final int lyricsOffsetMs;
final double mornyeGlassClarity;
final bool mornyeGlassOutlines;
@@ -80,6 +90,7 @@ class ThemeSettings {
this.customFontName = '',
this.lyricsTextScale = 1,
this.lyricsBlur = 1,
this.lyricsOffsetMs = 0,
this.mornyeGlassClarity = kDefaultMornyeGlassClarity,
this.mornyeGlassOutlines = true,
});
@@ -98,6 +109,7 @@ class ThemeSettings {
String? customFontName,
double? lyricsTextScale,
double? lyricsBlur,
int? lyricsOffsetMs,
double? mornyeGlassClarity,
bool? mornyeGlassOutlines,
}) {
@@ -115,6 +127,9 @@ class ThemeSettings {
lyricsTextScale ?? this.lyricsTextScale,
),
lyricsBlur: normalizeLyricsBlur(lyricsBlur ?? this.lyricsBlur),
lyricsOffsetMs: normalizeLyricsOffsetMs(
lyricsOffsetMs ?? this.lyricsOffsetMs,
),
mornyeGlassClarity: normalizeMornyeGlassClarity(
mornyeGlassClarity ?? this.mornyeGlassClarity,
),
@@ -134,6 +149,7 @@ class ThemeSettings {
kCustomFontNameKey: customFontName,
kLyricsTextScaleKey: lyricsTextScale,
kLyricsBlurKey: lyricsBlur,
kLyricsOffsetKey: lyricsOffsetMs,
kMornyeGlassClarityKey: mornyeGlassClarity,
kMornyeGlassOutlinesKey: mornyeGlassOutlines,
};
@@ -153,6 +169,7 @@ class ThemeSettings {
json[kLyricsTextScaleKey] as num?,
),
lyricsBlur: normalizeLyricsBlur(json[kLyricsBlurKey] as num?),
lyricsOffsetMs: normalizeLyricsOffsetMs(json[kLyricsOffsetKey] as num?),
mornyeGlassClarity: normalizeMornyeGlassClarity(
json[kMornyeGlassClarityKey] as num?,
),
@@ -175,6 +192,7 @@ class ThemeSettings {
other.customFontName == customFontName &&
other.lyricsTextScale == lyricsTextScale &&
other.lyricsBlur == lyricsBlur &&
other.lyricsOffsetMs == lyricsOffsetMs &&
other.mornyeGlassClarity == mornyeGlassClarity &&
other.mornyeGlassOutlines == mornyeGlassOutlines;
}
@@ -192,6 +210,7 @@ class ThemeSettings {
customFontName.hashCode ^
lyricsTextScale.hashCode ^
lyricsBlur.hashCode ^
lyricsOffsetMs.hashCode ^
mornyeGlassClarity.hashCode ^
mornyeGlassOutlines.hashCode;
}
+7
View File
@@ -22,6 +22,7 @@ ThemeSettings loadBootstrapThemeSettings(SharedPreferences prefs) {
prefs.getDouble(kLyricsTextScaleKey),
),
lyricsBlur: normalizeLyricsBlur(prefs.getDouble(kLyricsBlurKey)),
lyricsOffsetMs: normalizeLyricsOffsetMs(prefs.getInt(kLyricsOffsetKey)),
mornyeGlassClarity: normalizeMornyeGlassClarity(
prefs.getDouble(kMornyeGlassClarityKey),
),
@@ -87,6 +88,7 @@ class ThemeNotifier extends Notifier<ThemeSettings> {
await prefs.setString(kCustomFontNameKey, snapshot.customFontName);
await prefs.setDouble(kLyricsTextScaleKey, snapshot.lyricsTextScale);
await prefs.setDouble(kLyricsBlurKey, snapshot.lyricsBlur);
await prefs.setInt(kLyricsOffsetKey, snapshot.lyricsOffsetMs);
await prefs.setDouble(
kMornyeGlassClarityKey,
snapshot.mornyeGlassClarity,
@@ -152,6 +154,11 @@ class ThemeNotifier extends Notifier<ThemeSettings> {
if (persist) await _saveToStorage();
}
Future<void> setLyricsOffsetMs(int value, {bool persist = true}) async {
_editState((current) => current.copyWith(lyricsOffsetMs: value));
if (persist) await _saveToStorage();
}
Future<void> setMornyeGlassClarity(
double value, {
bool persist = true,
@@ -51,6 +51,7 @@ class LyricsSettingsPage extends ConsumerWidget {
// Lyrics blur only where the player draws it.
if (context.isMornye && ref.watch(mornyeLiquidGlassProvider))
const LyricsBlurSetting(),
const LyricsOffsetSetting(),
SettingsSwitchItem(
icon: Icons.light_mode_outlined,
title: context.l10n.lyricsKeepScreenOn,
+35
View File
@@ -273,3 +273,38 @@ Duration _estimatedFinalWordEnd(
if (next - start <= nearGap) return next;
return estimate;
}
/// Moves every line and word [offset] later (earlier when negative), for the
/// listener's lyrics timing setting. Times stop at the start of the track.
List<LyricLine> lyricsShiftedBy(List<LyricLine> lines, Duration offset) {
if (offset == Duration.zero) return lines;
Duration shift(Duration time) {
final shifted = time + offset;
return shifted < Duration.zero ? Duration.zero : shifted;
}
List<LyricWord> shiftWords(List<LyricWord> words) => [
for (final word in words)
LyricWord(
time: shift(word.time),
end: word.end == null ? null : shift(word.end!),
text: word.text,
),
];
return List.unmodifiable([
for (final line in lines)
LyricLine(
time: shift(line.time),
end: line.end == null ? null : shift(line.end!),
text: line.text,
words: shiftWords(line.words),
romanization: line.romanization,
romanizationWords: shiftWords(line.romanizationWords),
translation: line.translation,
voice: line.voice,
isBackground: line.isBackground,
vocalGroup: line.vocalGroup,
),
]);
}
+19 -1
View File
@@ -291,6 +291,21 @@ class _MiniPlayerLyricsState extends ConsumerState<_MiniPlayerLyrics>
PlayerMetadataController get metadata => widget.metadata;
List<LyricLine>? _shiftedSource;
int _shiftedOffsetMs = 0;
List<LyricLine> _shifted = const [];
/// [lines] with the lyrics timing setting applied, kept while neither
/// changes so word-timed lines keep their sweep across rebuilds.
List<LyricLine> _withOffset(List<LyricLine> lines, int offsetMs) {
if (!identical(lines, _shiftedSource) || offsetMs != _shiftedOffsetMs) {
_shiftedSource = lines;
_shiftedOffsetMs = offsetMs;
_shifted = lyricsShiftedBy(lines, Duration(milliseconds: offsetMs));
}
return _shifted;
}
@override
void initState() {
super.initState();
@@ -381,7 +396,10 @@ class _MiniPlayerLyricsState extends ConsumerState<_MiniPlayerLyrics>
}
return Consumer(
builder: (context, ref, _) {
final lines = lyrics.lines;
final lines = _withOffset(
lyrics.lines,
ref.watch(themeProvider.select((theme) => theme.lyricsOffsetMs)),
);
final current = _followPlayback(ref, lines);
final next = _leadLineAfter(lines, current);
return Padding(
@@ -8,10 +8,12 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:mornye/controllers/player_metadata_controller.dart';
import 'package:mornye/l10n/l10n.dart';
import 'package:mornye/providers/music_player_provider.dart';
import 'package:mornye/providers/theme_provider.dart';
import 'package:mornye/theme/app_tokens.dart';
import 'package:mornye/theme/mornye_theme.dart';
import 'package:mornye/theme/player_artwork_theme.dart';
import 'package:mornye/utils/lyrics_parser.dart';
import 'package:mornye/utils/lyrics_timeline.dart';
import 'package:mornye/utils/string_utils.dart';
import 'package:mornye/widgets/app_icon.dart';
import 'package:mornye/widgets/app_icon_button.dart';
+75
View File
@@ -3,6 +3,7 @@ import 'dart:ui' show ImageFilter;
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:mornye/l10n/l10n.dart';
import 'package:mornye/models/theme_settings.dart';
import 'package:mornye/providers/theme_provider.dart';
import 'package:mornye/theme/mornye_theme.dart';
import 'package:mornye/widgets/app_icon_button.dart';
@@ -73,6 +74,80 @@ class LyricsSizeSetting extends ConsumerWidget {
}
}
/// How much later (or earlier) synced lyrics follow playback, for audio that
/// reaches the listener late, such as over Bluetooth.
class LyricsOffsetSetting extends ConsumerWidget {
const LyricsOffsetSetting({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final offsetMs = ref.watch(
themeProvider.select((theme) => theme.lyricsOffsetMs),
);
final notifier = ref.read(themeProvider.notifier);
String format(double value) {
final ms = value.round();
if (ms == 0) return context.l10n.lyricsOffsetNone;
final seconds = (ms.abs() / 1000).toStringAsFixed(1);
return ms > 0
? context.l10n.lyricsOffsetLater(seconds)
: context.l10n.lyricsOffsetEarlier(seconds);
}
final value = format(offsetMs.toDouble());
final reset = AppIconButton(
tooltip: context.l10n.libraryFilterReset,
onPressed: offsetMs == 0 ? null : () => notifier.setLyricsOffsetMs(0),
icon: const Icon(Icons.restart_alt),
);
return Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (context.isMornye)
Row(
children: [
Expanded(
child: Text(
context.l10n.lyricsOffset,
style: Theme.of(context).textTheme.titleMedium,
),
),
Text(value),
reset,
],
)
else
SliderValueHeader(
title: context.l10n.lyricsOffset,
value: value,
trailing: reset,
),
Text(
context.l10n.lyricsOffsetSubtitle,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
AppSlider(
value: offsetMs.toDouble(),
min: -kMaxLyricsOffsetMs.toDouble(),
max: kMaxLyricsOffsetMs.toDouble(),
divisions: kMaxLyricsOffsetMs * 2 ~/ 100,
label: value,
semanticLabel: context.l10n.lyricsOffset,
semanticFormatterCallback: format,
onChanged: (value) =>
notifier.setLyricsOffsetMs(value.round(), persist: false),
onChangeEnd: (value) => notifier.setLyricsOffsetMs(value.round()),
),
],
),
);
}
}
/// How strongly Mornye blurs the lyric lines around the current one. The
/// preview's second line blurs as much as the line next to the current one.
class LyricsBlurSetting extends ConsumerWidget {
+35 -4
View File
@@ -101,6 +101,10 @@ class _SyncedLyricsViewState extends ConsumerState<SyncedLyricsView>
ProviderSubscription<Duration>? _positionSubscription;
ProviderSubscription<bool>? _playingSubscription;
ProviderSubscription<bool>? _loadingSubscription;
ProviderSubscription<int>? _offsetSubscription;
/// The listener's lyrics timing setting, already applied to [_lines].
Duration _offset = Duration.zero;
Timer? _lineBoundaryTimer;
Timer? _userScrollIdleTimer;
late List<LyricLine> _lines;
@@ -223,6 +227,17 @@ class _SyncedLyricsViewState extends ConsumerState<SyncedLyricsView>
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
_offsetSubscription = ref.listenManual<int>(
themeProvider.select((theme) => theme.lyricsOffsetMs),
(previous, next) {
setState(() {
_offset = Duration(milliseconds: next);
_resetLineKeys();
});
_syncPositionSubscription(resetUserScroll: false);
},
);
_offset = Duration(milliseconds: _offsetSubscription!.read());
_resetLineKeys();
widget.seekPreview.addListener(_previewChanged);
}
@@ -286,7 +301,9 @@ class _SyncedLyricsViewState extends ConsumerState<SyncedLyricsView>
_hasStarted = false;
_lineExtents = null;
_lineLayoutKey = null;
_lines = lyricsWithDisplayEnds(lyricsTimelineWithGaps(widget.lyrics.lines));
_lines = lyricsWithDisplayEnds(
lyricsTimelineWithGaps(lyricsShiftedBy(widget.lyrics.lines, _offset)),
);
_timeline = LyricTimelineIndex(_lines);
_rowReveal.stop();
_revealFrom = _revealTo = [
@@ -378,6 +395,13 @@ class _SyncedLyricsViewState extends ConsumerState<SyncedLyricsView>
setState(() => _awaitingFirstScroll = false);
}
/// Where a line shown at [shown] is sung in the track, before the lyrics
/// timing setting moved it, for seeking to it and sharing it.
Duration _sungTime(Duration shown) {
final time = shown - _offset;
return time < Duration.zero ? Duration.zero : time;
}
Duration get _displayPosition =>
widget.seekPreview.value ??
ref.read(playbackStateProvider).value?.position ??
@@ -528,6 +552,7 @@ class _SyncedLyricsViewState extends ConsumerState<SyncedLyricsView>
_positionSubscription?.close();
_playingSubscription?.close();
_loadingSubscription?.close();
_offsetSubscription?.close();
_lineBoundaryTimer?.cancel();
_userScrollIdleTimer?.cancel();
_measurementTimer?.cancel();
@@ -1189,13 +1214,19 @@ class _SyncedLyricsViewState extends ConsumerState<SyncedLyricsView>
Padding(
padding: _linePadding(index),
child: TvTapTarget(
onTap: () =>
ref.read(musicPlayerControllerProvider).seek(line.time),
onTap: () => ref
.read(musicPlayerControllerProvider)
.seek(_sungTime(line.time)),
onLongPress: widget.onLongPressLine == null
? null
: () {
HapticFeedback.mediumImpact();
widget.onLongPressLine!(line);
widget.onLongPressLine!(
LyricLine(
time: _sungTime(line.time),
text: line.text,
),
);
},
child: AnimatedScale(
// Focus changes paint scale, never font metrics or
+96
View File
@@ -98,6 +98,102 @@ void main() {
expect(loadBootstrapThemeSettings(prefs).lyricsBlur, 1);
});
test('lyrics timing validates stored bounds', () {
expect(normalizeLyricsOffsetMs(null), 0);
expect(normalizeLyricsOffsetMs(double.nan), 0);
expect(normalizeLyricsOffsetMs(250.4), 250);
expect(normalizeLyricsOffsetMs(9000), kMaxLyricsOffsetMs);
expect(normalizeLyricsOffsetMs(-9000), -kMaxLyricsOffsetMs);
final settings = const ThemeSettings().copyWith(lyricsOffsetMs: -300);
expect(ThemeSettings.fromJson(settings.toJson()), settings);
});
testWidgets('timing slider previews, persists on release and resets', (
tester,
) async {
final container = ProviderContainer();
addTearDown(container.dispose);
await tester.pumpWidget(
UncontrolledProviderScope(
container: container,
child: MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: const Scaffold(body: LyricsOffsetSetting()),
),
),
);
await tester.pumpAndSettle();
expect(find.text('In sync'), findsOneWidget);
final slider = tester.widget<AppSlider>(find.byType(AppSlider));
slider.onChanged!(300);
await tester.pump();
expect(find.text('0.3 s later'), findsOneWidget);
final prefs = await SharedPreferences.getInstance();
expect(prefs.getInt(kLyricsOffsetKey), isNull);
slider.onChangeEnd!(-500);
await tester.pumpAndSettle();
expect(find.text('0.5 s earlier'), findsOneWidget);
expect(loadBootstrapThemeSettings(prefs).lyricsOffsetMs, -500);
await tester.tap(find.byTooltip('Reset'));
await tester.pumpAndSettle();
expect(loadBootstrapThemeSettings(prefs).lyricsOffsetMs, 0);
});
testWidgets('lyrics timing decides which line is current', (tester) async {
final preview = ValueNotifier<Duration?>(const Duration(seconds: 3));
addTearDown(preview.dispose);
final container = ProviderContainer();
addTearDown(container.dispose);
final theme = MornyeTheme.build(Brightness.dark);
await tester.pumpWidget(
UncontrolledProviderScope(
container: container,
child: MaterialApp(
theme: theme,
home: Scaffold(
body: SyncedLyricsView(
lyrics: const ParsedLyrics(
synced: true,
wordSynced: false,
plainText: '',
lines: [
LyricLine(time: Duration.zero, text: 'First line'),
LyricLine(time: Duration(seconds: 2), text: 'Second line'),
],
),
seekPreview: preview,
colorScheme: theme.colorScheme,
isActive: true,
showPronunciation: false,
showTranslation: false,
),
),
),
),
);
await tester.pumpAndSettle();
double scaleOf(String text) => tester
.widget<AnimatedScale>(
find
.ancestor(
of: find.text(text),
matching: find.byType(AnimatedScale),
)
.first,
)
.scale;
expect(scaleOf('Second line'), 1.0);
// Two seconds later: at 3 s the second line, now at 4 s, has not begun.
await container.read(themeProvider.notifier).setLyricsOffsetMs(2000);
await tester.pumpAndSettle();
expect(scaleOf('First line'), 1.0);
expect(scaleOf('Second line'), 0.96);
expect(tester.takeException(), isNull);
await tester.pumpWidget(const SizedBox());
});
for (final strength in [0.0, 0.5, 1.5]) {
testWidgets('Mornye lyrics blur nearby lines at strength $strength', (
tester,
+30
View File
@@ -376,4 +376,34 @@ void main() {
isEmpty,
);
});
test('lyrics timing moves lines and words, stopping at the start', () {
const lines = [
LyricLine(
time: Duration(milliseconds: 200),
end: Duration(seconds: 2),
text: 'First',
words: [
LyricWord(
time: Duration(milliseconds: 200),
end: Duration(seconds: 1),
text: 'First',
),
],
),
LyricLine(time: Duration(seconds: 3), text: 'Second'),
];
expect(identical(lyricsShiftedBy(lines, Duration.zero), lines), isTrue);
final later = lyricsShiftedBy(lines, const Duration(milliseconds: 300));
expect(later.map((line) => line.time.inMilliseconds), [500, 3300]);
expect(later.first.end, const Duration(milliseconds: 2300));
expect(later.first.words.single.time, const Duration(milliseconds: 500));
expect(later.first.words.single.end, const Duration(milliseconds: 1300));
final earlier = lyricsShiftedBy(lines, const Duration(milliseconds: -500));
expect(earlier.map((line) => line.time.inMilliseconds), [0, 2500]);
expect(earlier.first.words.single.time, Duration.zero);
expect(earlier.map((line) => line.text), ['First', 'Second']);
});
}