Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Add auto-play next book/podcast and stream error retry

Nathan Poulsonc06a52053f9a
diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dart
index 7d10790b..a6e958e1 100644
--- a/lib/providers/library_provider.dart
+++ b/lib/providers/library_provider.dart
@@ -966,14 +966,40 @@ class LibraryProvider extends ChangeNotifier {
// Done after all sections so the order is correct regardless of which
// section the item appeared in first. Only move NEW items — ones already
// in the list keep their position to avoid shuffling.
+ String? newContinueSeriesKey;
if (_lastFinishedItemId != null && continueSeriesKeys.isNotEmpty) {
for (final key in continueSeriesKeys) {
if (!existingIds.contains(key)) {
_absorbingIdsAdd(key, afterKey: _lastFinishedItemId);
+ newContinueSeriesKey ??= key; // first new item is the next in series
}
}
}
+ // Auto-play the next book in series if the setting is enabled.
+ if (newContinueSeriesKey != null && _api != null) {
+ PlayerSettings.getAutoPlayNextBook().then((autoPlay) {
+ if (!autoPlay) return;
+ final cached = _absorbingItemCache[newContinueSeriesKey];
+ if (cached == null) return;
+ final media = cached['media'] as Map<String, dynamic>? ?? {};
+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};
+ final title = metadata['title'] as String? ?? '';
+ final author = metadata['authorName'] as String? ?? '';
+ final duration = (media['duration'] as num?)?.toDouble() ?? 0;
+ final chapters = media['chapters'] as List<dynamic>? ?? [];
+ AudioPlayerService().playItem(
+ api: _api!,
+ itemId: newContinueSeriesKey!,
+ title: title,
+ author: author,
+ coverUrl: getCoverUrl(newContinueSeriesKey),
+ totalDuration: duration,
+ chapters: chapters,
+ );
+ });
+ }
+
// For podcast libraries, scan _progressMap for additional in-progress
// episodes not already represented in continue-listening sections.
if (isPodcastLibrary) {
@@ -1298,6 +1324,26 @@ class LibraryProvider extends ChangeNotifier {
_absorbingItemCache[nextKey] = syntheticEntry;
await _saveManualAbsorbing();
notifyListeners();
+
+ // Auto-play the next episode if the setting is enabled.
+ if (await PlayerSettings.getAutoPlayNextPodcast() && _api != null) {
+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};
+ final title = metadata['title'] as String? ?? '';
+ final author = metadata['authorName'] as String? ?? '';
+ final duration = (nextEp['duration'] as num?)?.toDouble()
+ ?? (nextEp['audioFile'] as Map<String, dynamic>?)?['duration'] as double? ?? 0;
+ AudioPlayerService().playItem(
+ api: _api!,
+ itemId: showId,
+ title: title,
+ author: author,
+ coverUrl: getCoverUrl(showId),
+ totalDuration: duration,
+ chapters: [],
+ episodeId: nextEpId,
+ episodeTitle: nextEp['title'] as String?,
+ );
+ }
} catch (_) {}
}
diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart
index 9c0ea145..dac11e65 100644
--- a/lib/screens/settings_screen.dart
+++ b/lib/screens/settings_screen.dart
@@ -38,7 +38,8 @@ class _SettingsScreenState extends State<SettingsScreen> {
bool _resetSleepOnPause = false;
bool _sleepFadeOut = true;
int _shakeAddMinutes = 5;
- bool _autoContinueSeries = true;
+ bool _autoPlayNextBook = false;
+ bool _autoPlayNextPodcast = false;
bool _hideEbookOnly = false;
bool _showGoodreadsButton = false;
bool _loggingEnabled = false;
@@ -68,7 +69,8 @@ class _SettingsScreenState extends State<SettingsScreen> {
final resetOnPause = await PlayerSettings.getResetSleepOnPause();
final sleepFade = await PlayerSettings.getSleepFadeOut();
final shakeMins = await PlayerSettings.getShakeAddMinutes();
- final autoSeries = await PlayerSettings.getAutoContinueSeries();
+ final autoPlayBook = await PlayerSettings.getAutoPlayNextBook();
+ final autoPlayPod = await PlayerSettings.getAutoPlayNextPodcast();
final hideEbook = await PlayerSettings.getHideEbookOnly();
final showGoodreads = await PlayerSettings.getShowGoodreadsButton();
final logging = await PlayerSettings.getLoggingEnabled();
@@ -91,7 +93,8 @@ class _SettingsScreenState extends State<SettingsScreen> {
_resetSleepOnPause = resetOnPause;
_sleepFadeOut = sleepFade;
_shakeAddMinutes = shakeMins;
- _autoContinueSeries = autoSeries;
+ _autoPlayNextBook = autoPlayBook;
+ _autoPlayNextPodcast = autoPlayPod;
_hideEbookOnly = hideEbook;
_showGoodreadsButton = showGoodreads;
_loggingEnabled = logging;
@@ -581,14 +584,26 @@ class _SettingsScreenState extends State<SettingsScreen> {
),
const Divider(height: 1, indent: 16, endIndent: 16),
SwitchListTile(
- title: const Text('Auto-absorb next in series'),
+ title: const Text('Auto-play next book in series'),
subtitle: Text(
- _autoContinueSeries ? 'On — next book in series added to Absorbing' : 'Off',
+ _autoPlayNextBook ? 'On — next book plays automatically' : 'Off',
style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
- value: _autoContinueSeries,
+ value: _autoPlayNextBook,
onChanged: _loaded ? (v) {
- setState(() => _autoContinueSeries = v);
- PlayerSettings.setAutoContinueSeries(v);
+ setState(() => _autoPlayNextBook = v);
+ PlayerSettings.setAutoPlayNextBook(v);
+ } : null,
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ SwitchListTile(
+ title: const Text('Auto-play next podcast episode'),
+ subtitle: Text(
+ _autoPlayNextPodcast ? 'On — next episode plays automatically' : 'Off',
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _autoPlayNextPodcast,
+ onChanged: _loaded ? (v) {
+ setState(() => _autoPlayNextPodcast = v);
+ PlayerSettings.setAutoPlayNextPodcast(v);
} : null,
),
const Divider(height: 1, indent: 16, endIndent: 16),
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dart
index be4bf992..80bb7273 100644
--- a/lib/services/audio_player_service.dart
+++ b/lib/services/audio_player_service.dart
@@ -89,8 +89,11 @@ class PlayerSettings {
static Future<bool> getWifiOnlyDownloads() => _get('wifiOnlyDownloads', false);
static Future<void> setWifiOnlyDownloads(bool value) => _set('wifiOnlyDownloads', value);
- static Future<bool> getAutoContinueSeries() => _get('autoContinueSeries', true);
- static Future<void> setAutoContinueSeries(bool value) => _set('autoContinueSeries', value);
+ static Future<bool> getAutoPlayNextBook() => _get('autoPlayNextBook', false);
+ static Future<void> setAutoPlayNextBook(bool value) => _set('autoPlayNextBook', value);
+
+ static Future<bool> getAutoPlayNextPodcast() => _get('autoPlayNextPodcast', false);
+ static Future<void> setAutoPlayNextPodcast(bool value) => _set('autoPlayNextPodcast', value);
// ── Player UI settings (notify listeners on change) ──
@@ -214,7 +217,15 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
void bindService(AudioPlayerService service) => _service = service;
AudioPlayerHandler() {
- _player.playbackEventStream.map(_transformEvent).pipe(playbackState);
+ // Manually subscribe instead of .pipe() so we can handle errors.
+ // Without onError, a stream error (e.g. network timeout during streaming)
+ // would break the audio_service notification pipeline and crash the app.
+ _player.playbackEventStream.map(_transformEvent).listen(
+ playbackState.add,
+ onError: (Object e, StackTrace st) {
+ debugPrint('[Player] playbackEvent error (suppressed): $e');
+ },
+ );
}
@@ -707,6 +718,10 @@ class AudioPlayerService extends ChangeNotifier {
StreamSubscription? _completionSub;
/// Last known position in seconds — used to detect end→0 position jumps.
double _lastKnownPositionSec = 0;
+ // ── Stream error retry tracking ──
+ int _streamRetryCount = 0;
+ static const _maxStreamRetries = 3;
+ bool _retryInProgress = false;
// ── Multi-file track offset tracking ──
// For ConcatenatingAudioSource, _player.position is track-relative.
// We store cumulative start offsets so we can compute absolute book position.
@@ -831,6 +846,8 @@ class AudioPlayerService extends ChangeNotifier {
if (index != null) {
_currentTrackIndex = index.clamp(0, _trackStartOffsets.length - 2);
}
+ }, onError: (Object e, StackTrace st) {
+ debugPrint('[Player] Index stream error: $e');
});
}
@@ -1406,9 +1423,69 @@ class AudioPlayerService extends ChangeNotifier {
_lastKnownPositionSec = 0;
_eqSessionSub?.cancel();
_eqSessionSub = null;
+ _streamRetryCount = 0;
+ _retryInProgress = false;
notifyListeners();
}
+ /// Attempt to recover from a stream error by restarting playback from the
+ /// last known position. Tries up to [_maxStreamRetries] times with
+ /// exponential back-off (1s, 2s, 4s). If the item has been downloaded in
+ /// the meantime, falls back to local files automatically.
+ Future<void> _attemptStreamRetry(Object error) async {
+ if (_retryInProgress) return;
+ if (_currentItemId == null || _api == null) return;
+ if (_streamRetryCount >= _maxStreamRetries) {
+ debugPrint('[Player] Max retries reached ($_maxStreamRetries) — giving up');
+ return;
+ }
+
+ _retryInProgress = true;
+ _streamRetryCount++;
+ final delay = Duration(seconds: 1 << (_streamRetryCount - 1)); // 1s, 2s, 4s
+ debugPrint('[Player] Stream error — retry $_streamRetryCount/$_maxStreamRetries in ${delay.inSeconds}s');
+
+ await Future<void>.delayed(delay);
+
+ // Snapshot state before retry — playItem will overwrite these
+ final itemId = _currentItemId;
+ final title = _currentTitle ?? '';
+ final author = _currentAuthor ?? '';
+ final coverUrl = _currentCoverUrl;
+ final totalDuration = _totalDuration;
+ final chapters = List<dynamic>.from(_chapters);
+ final episodeId = _currentEpisodeId;
+ final episodeTitle = _currentEpisodeTitle;
+ final api = _api!;
+ final retryPos = _lastKnownPositionSec;
+
+ if (itemId == null) {
+ _retryInProgress = false;
+ return;
+ }
+
+ debugPrint('[Player] Retrying playback at ${retryPos.toStringAsFixed(1)}s');
+ final ok = await playItem(
+ api: api,
+ itemId: itemId,
+ title: title,
+ author: author,
+ coverUrl: coverUrl,
+ totalDuration: totalDuration,
+ chapters: chapters,
+ startTime: retryPos,
+ episodeId: episodeId,
+ episodeTitle: episodeTitle,
+ );
+
+ _retryInProgress = false;
+ if (ok) {
+ debugPrint('[Player] Retry succeeded');
+ } else {
+ debugPrint('[Player] Retry failed');
+ }
+ }
+
int _lastSyncSecond = -1;
StreamSubscription? _eqSessionSub;
@@ -1464,9 +1541,14 @@ class AudioPlayerService extends ChangeNotifier {
debugPrint('[Player] processingState → completed');
_onPlaybackComplete();
}
+ }, onError: (Object e, StackTrace st) {
+ debugPrint('[Player] processingState stream error: $e');
+ _attemptStreamRetry(e);
});
_syncSub = _player?.positionStream.listen((trackRelativePos) async {
+ // Reset retry counter on successful position updates
+ _streamRetryCount = 0;
// Convert track-relative position to absolute book position
final absolutePos = position; // uses the getter which adds track offset
final sec = absolutePos.inSeconds;
@@ -1556,6 +1638,9 @@ class AudioPlayerService extends ChangeNotifier {
}
}
}
+ }, onError: (Object e, StackTrace st) {
+ debugPrint('[Player] Position stream error: $e');
+ _attemptStreamRetry(e);
});
}