Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Stop iOS books jumping back to the start when a pause or seek swaps onto a fresh server session

Barnabas23069aa706f7
diff --git a/ios/Runner/Audio/AbsorbAudioBridge.swift b/ios/Runner/Audio/AbsorbAudioBridge.swift
index 6449a459..82a06c22 100644
--- a/ios/Runner/Audio/AbsorbAudioBridge.swift
+++ b/ios/Runner/Audio/AbsorbAudioBridge.swift
@@ -55,6 +55,7 @@ final class AbsorbAudioBridge: NSObject {
let volume = (args?["volume"] as? Double).map { Float($0) } ?? 1.0
let eq = (args?["eqEnabled"] as? Bool) ?? false
let itemId = args?["itemId"] as? String
+ let startTrackIndex = args?["startTrackIndex"] as? Int
AbsorbAudioEngine.shared.load(
tracks: trackList,
trackOffsets: offsets,
@@ -63,7 +64,8 @@ final class AbsorbAudioBridge: NSObject {
speed: speed,
volume: volume,
eqEnabled: eq,
- itemId: itemId
+ itemId: itemId,
+ startTrackIndex: startTrackIndex
) { duration in
result(["durationS": duration as Any])
}
diff --git a/ios/Runner/Audio/AbsorbAudioEngine.swift b/ios/Runner/Audio/AbsorbAudioEngine.swift
index 564d421b..30d36681 100644
--- a/ios/Runner/Audio/AbsorbAudioEngine.swift
+++ b/ios/Runner/Audio/AbsorbAudioEngine.swift
@@ -85,6 +85,7 @@ final class AbsorbAudioEngine: NSObject {
volume: Float,
eqEnabled: Bool,
itemId: String? = nil,
+ startTrackIndex: Int? = nil,
completion: @escaping (Double?) -> Void) {
queue.async { [weak self] in
guard let self = self else { completion(nil); return }
@@ -103,9 +104,21 @@ final class AbsorbAudioEngine: NSObject {
self.eqEnabled = eqEnabled
self.player.volume = volume
- let targetIndex = self.trackIndexFor(globalSeconds: startPositionS)
+ // Flutter loads with an explicit track and a track-local start, the
+ // same shape as seek(), because it hands over no offsets: deriving the
+ // track from a "global" start here put every mid-book load on track 0
+ // and clamped the position to that track's end. The widget core still
+ // loads by global position with the offsets it stashed.
+ let targetIndex: Int
+ let localStart: Double
+ if let explicit = startTrackIndex, explicit >= 0, explicit < tracks.count {
+ targetIndex = explicit
+ localStart = max(0, startPositionS)
+ } else {
+ targetIndex = self.trackIndexFor(globalSeconds: startPositionS)
+ localStart = max(0, startPositionS - self.trackOffsets[targetIndex])
+ }
self.trackIndex = targetIndex
- let localStart = max(0, startPositionS - self.trackOffsets[targetIndex])
self.loadTrack(atIndex: targetIndex, localStart: localStart, autoPlay: false, completion: completion)
}
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dart
index ee5fe965..e2dc97dd 100644
--- a/lib/services/audio_player_service.dart
+++ b/lib/services/audio_player_service.dart
@@ -5263,6 +5263,8 @@ class AudioPlayerService extends ChangeNotifier {
);
final source = ConcatenatingAudioSource(children: trackSources);
_resetPreBufferState();
+ // Update index BEFORE loading so positionStream events use the right offset
+ _currentTrackIndex = idx;
await _player!.setAudioSource(
source,
initialIndex: idx,
diff --git a/lib/services/native_ios_audio_player.dart b/lib/services/native_ios_audio_player.dart
index 18a7072d..edb9dd91 100644
--- a/lib/services/native_ios_audio_player.dart
+++ b/lib/services/native_ios_audio_player.dart
@@ -78,6 +78,14 @@ class NativeIosAudioPlayer {
// ─── Source loading ───
+ // Loads still waiting on the engine. The engine's periodic observer keeps
+ // ticking through a load, and the first ticks after the item swap report
+ // the new item at 0 before its start seek lands. Position readers turned
+ // that into "track offset + 0" and saved it as progress (a book mid-way
+ // through track 2 came back at 20s). Like just_audio, report the requested
+ // start until the load has answered.
+ int _loadsInFlight = 0;
+
Future<Duration?> setAudioSource(ja.AudioSource source, {
Duration? initialPosition,
int? initialIndex,
@@ -93,27 +101,42 @@ class NativeIosAudioPlayer {
_duration = null;
_durationController.add(null);
+ // `initialPosition` is local to `initialIndex`, the same shape as seek().
+ // The engine needs the index spelled out: the offsets handed to it below
+ // are empty, so deriving the track from the start position would put
+ // every mid-book load on track 0.
+ final startIndex = initialIndex ?? 0;
final startS = (initialPosition?.inMilliseconds ?? 0) / 1000.0;
- final eqEnabled = await ScopedPrefs.getBool('eq_enabled') ?? false;
- final result = await _methodChannel.invokeMethod<Map<dynamic, dynamic>>('load', {
- 'tracks': tracks.map(_trackToMap).toList(),
- 'trackOffsets': _buildTrackOffsets(tracks),
- 'startPositionS': startS,
- 'totalDurationS': _totalDurationHint,
- 'speed': _speed,
- 'volume': _volume,
- 'eqEnabled': eqEnabled,
- // Lets AbsorbPlayerCore recognise this book on a widget-driven resume so
- // it adopts the live engine instead of starting a duplicate stream.
- if (itemId != null) 'itemId': itemId,
- });
- final durS = (result?['durationS'] as num?)?.toDouble();
- final loadedDuration = durS != null && durS > 0
- ? Duration(milliseconds: (durS * 1000).round())
- : null;
- _duration = loadedDuration;
- _durationController.add(loadedDuration);
- return loadedDuration;
+ _currentIndex = startIndex;
+ _currentIndexController.add(startIndex);
+ _position = initialPosition ?? Duration.zero;
+ _updateTime = DateTime.now();
+ _loadsInFlight++;
+ try {
+ final eqEnabled = await ScopedPrefs.getBool('eq_enabled') ?? false;
+ final result = await _methodChannel.invokeMethod<Map<dynamic, dynamic>>('load', {
+ 'tracks': tracks.map(_trackToMap).toList(),
+ 'trackOffsets': _buildTrackOffsets(tracks),
+ 'startTrackIndex': startIndex,
+ 'startPositionS': startS,
+ 'totalDurationS': _totalDurationHint,
+ 'speed': _speed,
+ 'volume': _volume,
+ 'eqEnabled': eqEnabled,
+ // Lets AbsorbPlayerCore recognise this book on a widget-driven resume so
+ // it adopts the live engine instead of starting a duplicate stream.
+ if (itemId != null) 'itemId': itemId,
+ });
+ final durS = (result?['durationS'] as num?)?.toDouble();
+ final loadedDuration = durS != null && durS > 0
+ ? Duration(milliseconds: (durS * 1000).round())
+ : null;
+ _duration = loadedDuration;
+ _durationController.add(loadedDuration);
+ return loadedDuration;
+ } finally {
+ _loadsInFlight--;
+ }
}
/// New: pre-buffer the next book so the engine can swap to it gaplessly when
@@ -257,6 +280,7 @@ class NativeIosAudioPlayer {
final type = raw['type'] as String?;
switch (type) {
case 'position':
+ if (_loadsInFlight > 0) break;
final s = (raw['positionS'] as num?)?.toDouble() ?? 0;
_position = Duration(milliseconds: (s * 1000).round());
_updateTime = DateTime.now();