Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Sleep timer chime and adjustable fade, fix cover overflow on zoomed screens

Nathan Poulson1a7b3c94158a
diff --git a/assets/audio/bell.mp3 b/assets/audio/bell.mp3
new file mode 100644
index 00000000..c14bd84f
Binary files /dev/null and b/assets/audio/bell.mp3 differ
diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart
index 83116ebc..c7731c57 100644
--- a/lib/screens/settings_screen.dart
+++ b/lib/screens/settings_screen.dart
@@ -53,6 +53,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
String _shakeMode = 'addTime';
bool _resetSleepOnPause = false;
bool _sleepFadeOut = true;
+ int _sleepFadeDuration = 30;
+ bool _sleepChime = false;
+ double _sleepChimeVolume = 0.7;
int _shakeAddMinutes = 5;
String _bookQueueMode = 'off';
String _podcastQueueMode = 'off';
@@ -188,6 +191,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
PlayerSettings.getSkipChapterBarrier(), // 42
PlayerSettings.getShowExplicitBadge(), // 43
PlayerSettings.getIncludePreReleases(), // 44
+ PlayerSettings.getSleepFadeDuration(), // 45
+ PlayerSettings.getSleepChime(), // 46
+ PlayerSettings.getSleepChimeVolume(), // 47
]);
final s = results[0] as AutoRewindSettings;
final speed = results[1] as double;
@@ -231,6 +237,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
final skipBarrier = results[39] as bool;
final showExplicit = results[40] as bool;
final preReleases = results[41] as bool;
+ final fadeDur = results[42] as int;
+ final chime = results[43] as bool;
+ final chimeVol = results[44] as double;
if (mounted) setState(() {
_rewindSettings = s;
_defaultSpeed = speed;
@@ -278,6 +287,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
_trustAllCerts = trustCerts;
_showExplicitBadge = showExplicit;
_includePreReleases = preReleases;
+ _sleepFadeDuration = fadeDur;
+ _sleepChime = chime;
+ _sleepChimeVolume = chimeVol;
_canPickDownloadLocation = !_isPlayStoreBuild;
_loaded = true;
@@ -1134,7 +1146,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
title: const Text('Fade volume before sleep'),
subtitle: Text(
_sleepFadeOut
- ? 'Gradually lowers volume during the last 30 seconds'
+ ? 'Gradually lowers volume over the last ${_sleepFadeDuration}s'
: 'Playback stops immediately when timer ends',
style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
value: _sleepFadeOut,
@@ -1144,6 +1156,62 @@ class _SettingsScreenState extends State<SettingsScreen> {
} : null,
),
const Divider(height: 1, indent: 16, endIndent: 16),
+ SwitchListTile(
+ title: const Text('Chime before sleep'),
+ subtitle: Text(
+ _sleepChime
+ ? 'Plays a gentle bell when the timer is about to end'
+ : 'No sound warning before sleep',
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _sleepChime,
+ onChanged: _loaded ? (v) {
+ setState(() => _sleepChime = v);
+ PlayerSettings.setSleepChime(v);
+ } : null,
+ ),
+ if (_sleepChime) ...[
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ child: Row(children: [
+ Icon(Icons.volume_down_rounded, size: 18, color: cs.onSurfaceVariant),
+ Expanded(child: Slider(
+ value: _sleepChimeVolume,
+ min: 0.5, max: 3.0, divisions: 10,
+ label: '${(_sleepChimeVolume * 100 / 3).round()}%',
+ onChanged: _loaded ? (v) {
+ setState(() => _sleepChimeVolume = v);
+ PlayerSettings.setSleepChimeVolume(v);
+ } : null,
+ )),
+ Icon(Icons.volume_up_rounded, size: 18, color: cs.onSurfaceVariant),
+ ]),
+ ),
+ ],
+ if (_sleepFadeOut || _sleepChime) ...[
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ ListTile(
+ title: const Text('Wind-down duration'),
+ subtitle: Text(
+ 'Fade and chime start ${_sleepFadeDuration}s before sleep',
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ ),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ child: Row(children: [
+ Text('${_sleepFadeDuration}s', style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ Expanded(child: Slider(
+ value: _sleepFadeDuration.toDouble(),
+ min: 10, max: 60, divisions: 10,
+ label: '${_sleepFadeDuration}s',
+ onChanged: _loaded ? (v) {
+ setState(() => _sleepFadeDuration = v.round());
+ PlayerSettings.setSleepFadeDuration(v.round());
+ } : null,
+ )),
+ ]),
+ ),
+ ],
+ const Divider(height: 1, indent: 16, endIndent: 16),
// ── Auto Sleep Timer ──
SwitchListTile(
title: const Text('Auto sleep timer'),
diff --git a/lib/services/backup_service.dart b/lib/services/backup_service.dart
index 46d8f42b..5293ed66 100644
--- a/lib/services/backup_service.dart
+++ b/lib/services/backup_service.dart
@@ -31,6 +31,9 @@ class BackupService {
'shakeAddMinutes': await PlayerSettings.getShakeAddMinutes(),
'resetSleepOnPause': await PlayerSettings.getResetSleepOnPause(),
'sleepFadeOut': await PlayerSettings.getSleepFadeOut(),
+ 'sleepFadeDuration': await PlayerSettings.getSleepFadeDuration(),
+ 'sleepChime': await PlayerSettings.getSleepChime(),
+ 'sleepChimeVolume': await PlayerSettings.getSleepChimeVolume(),
'hideEbookOnly': await PlayerSettings.getHideEbookOnly(),
'collapseSeries': await PlayerSettings.getCollapseSeries(),
'librarySort': await PlayerSettings.getLibrarySort(),
@@ -231,6 +234,9 @@ class BackupService {
if (s['shakeAddMinutes'] != null) PlayerSettings.setShakeAddMinutes(s['shakeAddMinutes'] as int);
if (s['resetSleepOnPause'] != null) PlayerSettings.setResetSleepOnPause(s['resetSleepOnPause'] as bool);
if (s['sleepFadeOut'] != null) PlayerSettings.setSleepFadeOut(s['sleepFadeOut'] as bool);
+ if (s['sleepFadeDuration'] != null) PlayerSettings.setSleepFadeDuration(s['sleepFadeDuration'] as int);
+ if (s['sleepChime'] != null) PlayerSettings.setSleepChime(s['sleepChime'] as bool);
+ if (s['sleepChimeVolume'] != null) PlayerSettings.setSleepChimeVolume((s['sleepChimeVolume'] as num).toDouble());
if (s['hideEbookOnly'] != null) PlayerSettings.setHideEbookOnly(s['hideEbookOnly'] as bool);
if (s['collapseSeries'] != null) PlayerSettings.setCollapseSeries(s['collapseSeries'] as bool);
if (s['librarySort'] != null) PlayerSettings.setLibrarySort(s['librarySort'] as String);
diff --git a/lib/services/player_settings.dart b/lib/services/player_settings.dart
index 56181788..3c309c27 100644
--- a/lib/services/player_settings.dart
+++ b/lib/services/player_settings.dart
@@ -206,6 +206,12 @@ class PlayerSettings {
static Future<bool> getSleepFadeOut() => _get('sleepFadeOut', true);
static Future<void> setSleepFadeOut(bool value) => _set('sleepFadeOut', value);
+ static Future<int> getSleepFadeDuration() => _get('sleepFadeDuration', 30);
+ static Future<void> setSleepFadeDuration(int seconds) => _set('sleepFadeDuration', seconds);
+ static Future<bool> getSleepChime() => _get('sleepChime', false);
+ static Future<void> setSleepChime(bool value) => _set('sleepChime', value);
+ static Future<double> getSleepChimeVolume() => _get('sleepChimeVolume', 2.0);
+ static Future<void> setSleepChimeVolume(double value) => _set('sleepChimeVolume', value);
static Future<int> getSleepRewindSeconds() => _get('sleepRewindSeconds', 0);
static Future<void> setSleepRewindSeconds(int seconds) => _set('sleepRewindSeconds', seconds);
diff --git a/lib/services/sleep_timer_service.dart b/lib/services/sleep_timer_service.dart
index 22d075db..ffda3aa2 100644
--- a/lib/services/sleep_timer_service.dart
+++ b/lib/services/sleep_timer_service.dart
@@ -1,6 +1,8 @@
import 'dart:async';
import 'dart:math';
import 'package:flutter/foundation.dart';
+import 'package:flutter/services.dart';
+import 'package:just_audio/just_audio.dart' as ja;
import 'package:sensors_plus/sensors_plus.dart';
import 'package:vibration/vibration.dart';
import 'scoped_prefs.dart';
@@ -123,7 +125,7 @@ class SleepTimerService extends ChangeNotifier {
// Wind-down warning & fade
bool _warningSent = false;
- static const _warningThreshold = Duration(seconds: 30);
+ Duration _fadeThreshold = const Duration(seconds: 30);
double _fadeStartVolume = 1.0; // volume when fade begins
// Reset on pause/play
@@ -153,16 +155,18 @@ class SleepTimerService extends ChangeNotifier {
// ── Time-based sleep ──
- void setTimeSleep(Duration duration) {
+ void setTimeSleep(Duration duration) async {
cancel();
_mode = SleepTimerMode.time;
_timeRemaining = duration;
_initialDuration = duration;
_warningSent = false;
+ final fadeSecs = await PlayerSettings.getSleepFadeDuration();
+ _fadeThreshold = Duration(seconds: fadeSecs);
_startTimeCountdown();
_startShakeDetection();
notifyListeners();
- debugPrint('[SleepTimer] Set time sleep: ${duration.inMinutes}m');
+ debugPrint('[SleepTimer] Set time sleep: ${duration.inMinutes}m (fade: ${fadeSecs}s)');
}
int _tickIntervalSeconds = 5;
@@ -175,8 +179,8 @@ class SleepTimerService extends ChangeNotifier {
void _scheduleNextTick() {
_timer?.cancel();
- // Tick every 1s during fade period (last 35s), every 5s otherwise
- final nearFade = _timeRemaining <= _warningThreshold + const Duration(seconds: 5);
+ // Tick every 1s during fade period, every 5s otherwise
+ final nearFade = _timeRemaining <= _fadeThreshold + const Duration(seconds: 5);
_tickIntervalSeconds = nearFade ? 1 : 5;
_timer = Timer.periodic(Duration(seconds: _tickIntervalSeconds), _onTimerTick);
}
@@ -212,29 +216,32 @@ class SleepTimerService extends ChangeNotifier {
}
- // Switch to fast ticks when approaching warning threshold
+ // Switch to fast ticks when approaching fade threshold
if (_tickIntervalSeconds > 1 &&
- _timeRemaining <= _warningThreshold + const Duration(seconds: 5)) {
+ _timeRemaining <= _fadeThreshold + const Duration(seconds: 5)) {
_scheduleNextTick();
}
- // Wind-down warning at 30 seconds: vibration + optional fade
- if (!_warningSent && _timeRemaining <= _warningThreshold && _timeRemaining.inSeconds > 0) {
+ // Wind-down: vibration + optional fade + optional chime
+ if (!_warningSent && _timeRemaining <= _fadeThreshold && _timeRemaining.inSeconds > 0) {
_warningSent = true;
onToast?.call('Sleep timer ending soon...');
final fadeEnabled = await PlayerSettings.getSleepFadeOut();
if (fadeEnabled && !_cast.isCasting) {
_isFadingOut = true;
_fadeStartVolume = _player.volume;
- debugPrint('[SleepTimer] Warning: ${_timeRemaining.inSeconds}s remaining - starting fade');
+ debugPrint('[SleepTimer] Warning: ${_timeRemaining.inSeconds}s remaining - starting fade (${_fadeThreshold.inSeconds}s)');
} else {
debugPrint('[SleepTimer] Warning: ${_timeRemaining.inSeconds}s remaining');
}
+ // Play chime sound if enabled
+ final chimeEnabled = await PlayerSettings.getSleepChime();
+ if (chimeEnabled) _playChime();
}
- // Gradually lower volume during the last 30 seconds
+ // Gradually lower volume during the fade period
if (_isFadingOut && _timeRemaining.inSeconds > 0 && !_cast.isCasting) {
- final fraction = _timeRemaining.inSeconds / _warningThreshold.inSeconds;
+ final fraction = _timeRemaining.inSeconds / _fadeThreshold.inSeconds;
_player.setVolume((_fadeStartVolume * fraction).clamp(0.0, 1.0));
}
@@ -247,7 +254,7 @@ class SleepTimerService extends ChangeNotifier {
if (_mode != SleepTimerMode.time) return;
_timeRemaining += extra;
// Reset warning and restore volume if we're above threshold again
- if (_timeRemaining > _warningThreshold) {
+ if (_timeRemaining > _fadeThreshold) {
_warningSent = false;
if (_isFadingOut) {
_isFadingOut = false;
@@ -392,6 +399,27 @@ class SleepTimerService extends ChangeNotifier {
}
}
+ /// Play a gentle bell chime to warn that sleep timer is ending soon.
+ ja.AudioPlayer? _chimePlayer;
+ void _playChime() async {
+ try {
+ final vol = await PlayerSettings.getSleepChimeVolume();
+ _chimePlayer?.dispose();
+ final chime = ja.AudioPlayer();
+ _chimePlayer = chime;
+ await chime.setVolume(vol);
+ await chime.setAsset('assets/audio/bell.mp3');
+ debugPrint('[SleepTimer] Chime: playing (vol=$vol)');
+ chime.play();
+ chime.playerStateStream.where((s) => s.processingState == ja.ProcessingState.completed).first.then((_) {
+ chime.dispose();
+ if (_chimePlayer == chime) _chimePlayer = null;
+ });
+ } catch (e) {
+ debugPrint('[SleepTimer] Chime error: $e');
+ }
+ }
+
// ── Shake detection ──
diff --git a/lib/widgets/absorbing_card.dart b/lib/widgets/absorbing_card.dart
index c1af0d0d..cf02adc8 100644
--- a/lib/widgets/absorbing_card.dart
+++ b/lib/widgets/absorbing_card.dart
@@ -548,7 +548,8 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli
builder: (context, _) => LayoutBuilder(
builder: (context, constraints) {
final maxW = constraints.maxWidth * 0.75;
- final maxH = constraints.maxHeight.isFinite ? constraints.maxHeight : maxW;
+ final rawH = constraints.maxHeight.isFinite ? constraints.maxHeight : maxW;
+ final maxH = rawH - 24;
double coverW, coverH;
if (_rectangleCovers) {
coverW = maxW;
diff --git a/lib/widgets/card_button_config.dart b/lib/widgets/card_button_config.dart
index 897a1fa6..5eeb2e00 100644
--- a/lib/widgets/card_button_config.dart
+++ b/lib/widgets/card_button_config.dart
@@ -14,7 +14,7 @@ final Set<String> _iosHiddenButtons = Platform.isIOS ? const {'cast', 'equalizer
const _allCardButtons = [
CardButtonDef('chapters', 'Chapters', Icons.list_rounded),
CardButtonDef('speed', 'Speed', Icons.speed_rounded),
- CardButtonDef('sleep', 'Sleep Timer', Icons.bedtime_outlined),
+ CardButtonDef('sleep', 'Timer', Icons.nightlight_round_outlined),
CardButtonDef('bookmarks', 'Bookmarks', Icons.bookmark_outline_rounded),
CardButtonDef('details', 'Book Details', Icons.info_outline_rounded),
CardButtonDef('equalizer', 'Equalizer', Icons.equalizer_rounded),
diff --git a/lib/widgets/card_buttons.dart b/lib/widgets/card_buttons.dart
index ad970f34..75cc82bc 100644
--- a/lib/widgets/card_buttons.dart
+++ b/lib/widgets/card_buttons.dart
@@ -201,7 +201,7 @@ class CardSleepButtonInline extends StatelessWidget {
} else if (active) {
label = '${sleep.chaptersRemaining} ch left';
} else {
- label = compact ? 'Sleep' : 'Sleep Timer';
+ label = 'Timer';
}
final h = compact ? 30.0 : (large ? 48.0 : 36.0);
@@ -233,12 +233,12 @@ class CardSleepButtonInline extends StatelessWidget {
),
),
Center(child: compact && !active
- ? Icon(Icons.bedtime_outlined, size: iconSz,
+ ? Icon(Icons.nightlight_round_outlined, size: iconSz,
color: isActive ? cs.onSurfaceVariant : cs.onSurface.withValues(alpha: 0.24))
: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
- Icon(Icons.bedtime_outlined, size: iconSz,
+ Icon(Icons.nightlight_round_outlined, size: iconSz,
color: active ? accent : (isActive ? cs.onSurfaceVariant : cs.onSurface.withValues(alpha: 0.24))),
SizedBox(width: compact ? 4 : 8),
Flexible(child: Text(label, overflow: TextOverflow.ellipsis, style: TextStyle(
@@ -1094,7 +1094,7 @@ class CardActionDelegate {
);
case 'sleep':
return CardWideButton(
- icon: Icons.bedtime_outlined, label: short ? 'Sleep' : 'Sleep Timer',
+ icon: Icons.nightlight_round_outlined, label: 'Timer',
accent: accent, isActive: true, alwaysEnabled: true, large: large, compact: compact,
child: CardSleepButtonInline(accent: accent, isActive: isPlaybackActive, large: large, compact: compact),
);
@@ -1191,7 +1191,7 @@ class CardActionDelegate {
);
case 'sleep':
return MoreMenuItem(
- icon: Icons.bedtime_outlined, label: 'Sleep Timer', accent: accent,
+ icon: Icons.nightlight_round_outlined, label: 'Timer', accent: accent,
enabled: true,
onTap: () {
Navigator.pop(ctx);
diff --git a/lib/widgets/expanded_card.dart b/lib/widgets/expanded_card.dart
index 1ba41a95..2efd0617 100644
--- a/lib/widgets/expanded_card.dart
+++ b/lib/widgets/expanded_card.dart
@@ -585,7 +585,7 @@ class _ExpandedCardState extends State<ExpandedCard> {
builder: (context, _) => LayoutBuilder(
builder: (context, constraints) {
final maxW = constraints.maxWidth * 0.90;
- final maxH = constraints.maxHeight;
+ final maxH = constraints.maxHeight - 24;
double coverW, coverH;
if (_rectangleCovers) {
coverW = maxW;
diff --git a/pubspec.yaml b/pubspec.yaml
index 566dc569..a1da7336 100644
--- a/pubspec.yaml
+++ b/pubspec.yaml
@@ -100,6 +100,7 @@ flutter:
uses-material-design: true
assets:
- assets/icon/
+ - assets/audio/
flutter_launcher_icons:
android: true