Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Make the iOS lock screen skip buttons use your own skip amounts

Barnabasf520cc14ebe3
diff --git a/ios/Runner/AbsorbPlayerCore.swift b/ios/Runner/AbsorbPlayerCore.swift
index 5644b9c4..81c5d910 100644
--- a/ios/Runner/AbsorbPlayerCore.swift
+++ b/ios/Runner/AbsorbPlayerCore.swift
@@ -35,6 +35,12 @@ final class AbsorbPlayerCore: NSObject, AbsorbPlayerCoreProtocol, @unchecked Sen
private var _commandsConfigured = false
+ // Lock screen skip amounts, mirrored from Dart. They start on the same
+ // defaults as PlayerSettings so the buttons are right before Dart pushes
+ // anything, then follow the user's setting (and per-library override).
+ private var _skipForwardSec = 30
+ private var _skipBackwardSec = 10
+
// Server sync timer (separate from the engine's position observer).
private var _serverSyncTimer: Timer?
private static let serverSyncIntervalSec: TimeInterval = 60.0
@@ -484,6 +490,33 @@ final class AbsorbPlayerCore: NSObject, AbsorbPlayerCoreProtocol, @unchecked Sen
// MARK: - MPRemoteCommandCenter
+ /// Point the lock screen skip buttons at the user's skip amounts. Called
+ /// from Dart at startup and whenever the setting (or the playing item's
+ /// per-library override) changes. Applies immediately even before the
+ /// commands are armed, because `preferredIntervals` lives on the shared
+ /// command center and whoever writes it last wins - audio_service only
+ /// writes it when it re-applies its controls.
+ func setSkipIntervals(forward: Int, backward: Int) {
+ queue.async { [weak self] in
+ guard let self = self else { return }
+ let fwd = max(1, forward)
+ let back = max(1, backward)
+ if fwd != self._skipForwardSec || back != self._skipBackwardSec {
+ self.emit("[NativeCore] skip intervals fwd=\(fwd)s back=\(back)s")
+ }
+ self._skipForwardSec = fwd
+ self._skipBackwardSec = back
+ // Always re-assert, even when unchanged: audio_service writes the same
+ // properties whenever it re-applies its controls (it does after a stop),
+ // so a push that looks redundant here may still be undoing a stale write.
+ DispatchQueue.main.async {
+ let cc = MPRemoteCommandCenter.shared()
+ cc.skipForwardCommand.preferredIntervals = [NSNumber(value: fwd)]
+ cc.skipBackwardCommand.preferredIntervals = [NSNumber(value: back)]
+ }
+ }
+ }
+
/// Register the remote command handlers up front, without loading a player or
/// starting playback. They defer to Flutter while it's alive, so this is a
/// no-op for normal foreground use - but it guarantees a native target stays
@@ -533,9 +566,10 @@ final class AbsorbPlayerCore: NSObject, AbsorbPlayerCoreProtocol, @unchecked Sen
return .success
}
- cc.skipForwardCommand.preferredIntervals = [30]
+ cc.skipForwardCommand.preferredIntervals = [NSNumber(value: _skipForwardSec)]
cc.skipForwardCommand.addTarget { [weak self] event in
- let interval = (event as? MPSkipIntervalCommandEvent)?.interval ?? 30
+ let fallback = self?._skipForwardSec ?? 30
+ let interval = (event as? MPSkipIntervalCommandEvent)?.interval ?? Double(fallback)
if self?.flutterIsAlive() == true {
self?.emit("[NativeCore] remote: skipForward - Flutter is alive, deferring")
return .success
@@ -543,9 +577,10 @@ final class AbsorbPlayerCore: NSObject, AbsorbPlayerCoreProtocol, @unchecked Sen
self?.skipForward(seconds: Int(interval))
return .success
}
- cc.skipBackwardCommand.preferredIntervals = [10]
+ cc.skipBackwardCommand.preferredIntervals = [NSNumber(value: _skipBackwardSec)]
cc.skipBackwardCommand.addTarget { [weak self] event in
- let interval = (event as? MPSkipIntervalCommandEvent)?.interval ?? 10
+ let fallback = self?._skipBackwardSec ?? 10
+ let interval = (event as? MPSkipIntervalCommandEvent)?.interval ?? Double(fallback)
if self?.flutterIsAlive() == true {
self?.emit("[NativeCore] remote: skipBackward - Flutter is alive, deferring")
return .success
diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift
index a7a5c42d..09efea40 100644
--- a/ios/Runner/AppDelegate.swift
+++ b/ios/Runner/AppDelegate.swift
@@ -438,6 +438,23 @@ let flutterEngine = FlutterEngine(name: "SharedEngine", project: nil, allowHeadl
}
}
+ // Lock screen skip amounts. iOS bakes these into the command center's
+ // preferredIntervals rather than reading them per press, so Dart pushes the
+ // effective amounts here whenever they change.
+ let playerCoreChannel = FlutterMethodChannel(name: "com.absorb.player_core",
+ binaryMessenger: messenger)
+ playerCoreChannel.setMethodCallHandler { (call, result) in
+ guard call.method == "setSkipIntervals" else { result(FlutterMethodNotImplemented); return }
+ let args = call.arguments as? [String: Any]
+ guard let forward = args?["forward"] as? Int,
+ let backward = args?["backward"] as? Int else {
+ result(FlutterError(code: "SKIP_ARGS", message: "Missing forward or backward", details: nil))
+ return
+ }
+ AbsorbPlayerCore.shared.setSkipIntervals(forward: forward, backward: backward)
+ result(true)
+ }
+
let widgetChannel = FlutterMethodChannel(name: "com.absorb.widget",
binaryMessenger: messenger)
self.widgetChannel = widgetChannel
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dart
index f6c83366..060bd138 100644
--- a/lib/services/audio_player_service.dart
+++ b/lib/services/audio_player_service.dart
@@ -1501,12 +1501,44 @@ class AudioPlayerService extends ChangeNotifier {
}
}
+ static const _playerCoreChannel = MethodChannel('com.absorb.player_core');
+ static const _audioServiceClientChannel = MethodChannel(
+ 'com.ryanheise.audio_service.client.methods',
+ );
+
+ /// Point the iOS lock screen skip buttons at [forward] / [backward] seconds.
+ /// Unlike Android, iOS doesn't ask how far to skip on each press - it reads
+ /// the amounts off MPRemoteCommandCenter, which audio_service writes once at
+ /// startup and the native core armed with the defaults, so changing the
+ /// setting never reached the lock screen. Tell both, since they write the
+ /// same properties and whoever goes last wins.
+ static Future<void> _pushIosSkipIntervals(int forward, int backward) async {
+ try {
+ await _playerCoreChannel.invokeMethod('setSkipIntervals', {
+ 'forward': forward,
+ 'backward': backward,
+ });
+ } catch (e) {
+ debugPrint('[SkipDebug] native core setSkipIntervals failed: $e');
+ }
+ try {
+ await _audioServiceClientChannel.invokeMethod('updateSkipIntervals', {
+ 'fastForwardInterval': forward * 1000,
+ 'rewindInterval': backward * 1000,
+ });
+ } catch (e) {
+ debugPrint('[SkipDebug] audio_service updateSkipIntervals failed: $e');
+ }
+ }
+
/// Refresh the notification's cached skip labels with the amounts for the
/// current library. Called on settings changes and whenever the loaded
/// item changes.
void _syncNotifSkipCache() {
final libId = _currentLibraryId;
- PlayerSettings.getEffectiveForwardSkip(libraryId: libId).then((v) {
+ final fwdFuture = PlayerSettings.getEffectiveForwardSkip(libraryId: libId);
+ final backFuture = PlayerSettings.getEffectiveBackSkip(libraryId: libId);
+ fwdFuture.then((v) {
debugPrint(
'[SkipDebug] notif cache: lib=$libId fwd=${v}s (was ${_handler?._cachedForwardSkip})',
);
@@ -1515,12 +1547,18 @@ class AudioPlayerService extends ChangeNotifier {
_handler!.refreshPlaybackState();
}
});
- PlayerSettings.getEffectiveBackSkip(libraryId: libId).then((v) {
+ backFuture.then((v) {
if (_handler != null && v != _handler!._cachedBackSkip) {
_handler!._cachedBackSkip = v;
_handler!.refreshPlaybackState();
}
});
+ if (Platform.isIOS) {
+ unawaited(
+ Future.wait([fwdFuture, backFuture])
+ .then((v) => _pushIosSkipIntervals(v[0], v[1])),
+ );
+ }
}
/// Fill in a missing library id for the playing item so per-library skip
@@ -2520,6 +2558,11 @@ class AudioPlayerService extends ChangeNotifier {
// Initialize cached skip amounts so notification icons show the correct values
_handler!._cachedForwardSkip = fwdSkip;
_handler!._cachedBackSkip = backSkip;
+ // Nothing is loaded yet so there's no library override to apply; the
+ // per-library amounts follow from _syncNotifSkipCache once an item does.
+ if (Platform.isIOS) {
+ unawaited(_pushIosSkipIntervals(fwdSkip, backSkip));
+ }
_handler!._cachedNotifSpeedBookmark =
await PlayerSettings.getMediaControlsSpeedBookmark();
_handler!._cachedLockSeekBar = await PlayerSettings.getLockSeekBar();
diff --git a/packages/audio_service/darwin/audio_service/Sources/audio_service/AudioServicePlugin.m b/packages/audio_service/darwin/audio_service/Sources/audio_service/AudioServicePlugin.m
index 2878fe71..ea1c7685 100644
--- a/packages/audio_service/darwin/audio_service/Sources/audio_service/AudioServicePlugin.m
+++ b/packages/audio_service/darwin/audio_service/Sources/audio_service/AudioServicePlugin.m
@@ -142,6 +142,26 @@ static NSMutableDictionary *nowPlayingInfo = nil;
fastForwardInterval = configMap[@"fastForwardInterval"];
rewindInterval = configMap[@"rewindInterval"];
result(@{});
+ } else if ([@"updateSkipIntervals" isEqualToString:call.method]) {
+ // Absorb patch: the skip amounts were only ever read from the config at
+ // init, and updateControl: skips re-applying them once the controls have
+ // settled, so changing the setting left the lock screen on the amounts
+ // from launch. Refresh the statics (used by every later re-apply) and
+ // push them to the command center now.
+ NSDictionary *args = (NSDictionary *)call.arguments;
+ fastForwardInterval = args[@"fastForwardInterval"];
+ rewindInterval = args[@"rewindInterval"];
+ if (commandCenter) {
+ if (fastForwardInterval.integerValue > 0) {
+ int fwdSec = [fastForwardInterval intValue]/1000;
+ commandCenter.skipForwardCommand.preferredIntervals = @[[NSNumber numberWithInt:fwdSec]];
+ }
+ if (rewindInterval.integerValue > 0) {
+ int backSec = [rewindInterval intValue]/1000;
+ commandCenter.skipBackwardCommand.preferredIntervals = @[[NSNumber numberWithInt:backSec]];
+ }
+ }
+ result(@{});
} else if ([@"setState" isEqualToString:call.method]) {
NSDictionary *args = (NSDictionary *)call.arguments;
NSDictionary *stateMap = (NSDictionary *)args[@"state"];