Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Let you choose what the media controls show on each line, with book percentage, time left, narrator and series as options

Barnabas18e8efe6f1cb
diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift
index a931b2e0..c26af534 100644
--- a/ios/Runner/AppDelegate.swift
+++ b/ios/Runner/AppDelegate.swift
@@ -653,19 +653,24 @@ let flutterEngine = FlutterEngine(name: "SharedEngine", project: nil, allowHeadl
case "primeNowPlaying":
let title = args?["title"] as? String ?? ""
let artist = args?["artist"] as? String ?? ""
+ let album = args?["album"] as? String ?? ""
let duration = args?["duration"] as? Double ?? 0
let elapsed = args?["elapsed"] as? Double ?? 0
// Merge into what is on the tile for the same book rather than
// replacing it: a full replace dropped the artwork audio_service had
// set, and audio_service only rewrites when its own copy changes, so
// the cover stayed missing on a locked phone until the next chapter.
- // The subtitle is "Author · Book", so a match means the same book and
- // its artwork is still right; anything else starts clean.
+ // The album is the book title whatever the two lines are set to show,
+ // so a match means the same book and its artwork is still right;
+ // anything else starts clean.
let existing = MPNowPlayingInfoCenter.default().nowPlayingInfo ?? [:]
- let sameBook = (existing[MPMediaItemPropertyArtist] as? String) == artist
+ let sameBook = !album.isEmpty && (existing[MPMediaItemPropertyAlbumTitle] as? String) == album
var info: [String: Any] = sameBook ? existing : [:]
info[MPMediaItemPropertyTitle] = title
info[MPMediaItemPropertyArtist] = artist
+ if !album.isEmpty {
+ info[MPMediaItemPropertyAlbumTitle] = album
+ }
info[MPNowPlayingInfoPropertyPlaybackRate] = 1.0
info[MPNowPlayingInfoPropertyElapsedPlaybackTime] = elapsed
if duration > 0 {
diff --git a/ios/Runner/IOSQueueAdvancer.swift b/ios/Runner/IOSQueueAdvancer.swift
index f1c0bae9..21d6f842 100644
--- a/ios/Runner/IOSQueueAdvancer.swift
+++ b/ios/Runner/IOSQueueAdvancer.swift
@@ -23,6 +23,7 @@ final class IOSQueueAdvancer: NSObject {
private var _preparedItem: AVPlayerItem?
private var _preparedTitle: String = ""
private var _preparedArtist: String = ""
+ private var _preparedAlbum: String = ""
private var _preparedDurationS: Double = 0
private var _preparedCoverPath: String?
private var _preparedStartS: Double = 0
@@ -78,6 +79,7 @@ final class IOSQueueAdvancer: NSObject {
let headers = (args?["headers"] as? [String: String]) ?? [:]
let title = (args?["title"] as? String) ?? ""
let artist = (args?["artist"] as? String) ?? ""
+ let album = (args?["album"] as? String) ?? ""
let duration = (args?["durationS"] as? Double) ?? 0
let coverPath = args?["coverPath"] as? String
let startS = (args?["startS"] as? Double) ?? 0
@@ -87,6 +89,7 @@ final class IOSQueueAdvancer: NSObject {
headers: headers,
title: title,
artist: artist,
+ album: album,
durationS: duration,
coverPath: coverPath,
startS: startS,
@@ -124,6 +127,7 @@ final class IOSQueueAdvancer: NSObject {
headers: [String: String],
title: String,
artist: String,
+ album: String,
durationS: Double,
coverPath: String?,
startS: Double,
@@ -169,6 +173,7 @@ final class IOSQueueAdvancer: NSObject {
self._preparedItem = item
self._preparedTitle = title
self._preparedArtist = artist
+ self._preparedAlbum = album
self._preparedDurationS = durationS
self._preparedCoverPath = coverPath
self._preparedStartS = startS
@@ -227,6 +232,7 @@ final class IOSQueueAdvancer: NSObject {
_preparedItem = nil
_preparedTitle = ""
_preparedArtist = ""
+ _preparedAlbum = ""
_preparedDurationS = 0
_preparedCoverPath = nil
_preparedStartS = 0
@@ -247,6 +253,7 @@ final class IOSQueueAdvancer: NSObject {
private func publishNowPlaying(rate: Double) {
let title = _preparedTitle
let artist = _preparedArtist
+ let album = _preparedAlbum
let duration = _preparedDurationS
let coverPath = _preparedCoverPath
let elapsed = _preparedStartS
@@ -261,6 +268,9 @@ final class IOSQueueAdvancer: NSObject {
if duration > 0 {
info[MPMediaItemPropertyPlaybackDuration] = duration
}
+ if !album.isEmpty {
+ info[MPMediaItemPropertyAlbumTitle] = album
+ }
if let coverPath = coverPath, let img = UIImage(contentsOfFile: coverPath) {
let artwork = MPMediaItemArtwork(boundsSize: img.size) { _ in img }
info[MPMediaItemPropertyArtwork] = artwork
diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb
index 9b752e93..2ee740d7 100644
--- a/lib/l10n/app_en.arb
+++ b/lib/l10n/app_en.arb
@@ -842,6 +842,38 @@
"chapterProgressOffSubtitle": "Off - they show full book progress",
"chapterProgressInNotificationIos": "Chapter progress on lock screen & CarPlay",
"chapterProgressOnSubtitleIos": "On - lock screen & CarPlay show chapter progress",
+ "nowPlayingText": "Now playing text",
+ "nowPlayingTextSubtitle": "Choose what the media controls show on each line",
+ "nowPlayingTopLine": "Top line",
+ "nowPlayingSecondLine": "Second line",
+ "nowPlayingNotShown": "Not shown",
+ "nowPlayingTopLineRequired": "The top line needs at least one item",
+ "nowPlayingPieceChapter": "Chapter",
+ "nowPlayingPieceTitle": "Book title",
+ "nowPlayingPieceNarrator": "Narrator",
+ "nowPlayingPieceSeries": "Series",
+ "nowPlayingPiecePercent": "Book percentage",
+ "nowPlayingPieceChapterNumber": "Chapter number",
+ "nowPlayingPieceTimeLeft": "Time left",
+ "nowPlayingChapterNumber": "Ch. {number}/{total}",
+ "@nowPlayingChapterNumber": {
+ "placeholders": {
+ "number": {
+ "type": "int"
+ },
+ "total": {
+ "type": "int"
+ }
+ }
+ },
+ "nowPlayingTimeLeft": "{time} left",
+ "@nowPlayingTimeLeft": {
+ "placeholders": {
+ "time": {
+ "type": "String"
+ }
+ }
+ },
"speedBookmarkInControls": "Speed & bookmark in media controls",
"speedBookmarkOnSubtitle": "On - notification shows speed & bookmark; chapter skip stays in Android Auto",
"speedBookmarkOffSubtitle": "Off - notification shows chapter skip; speed & bookmark stay in Android Auto",
diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart
index 728842b9..f373f34f 100644
--- a/lib/l10n/app_localizations.dart
+++ b/lib/l10n/app_localizations.dart
@@ -3268,6 +3268,96 @@ abstract class AppLocalizations {
/// **'On - lock screen & CarPlay show chapter progress'**
String get chapterProgressOnSubtitleIos;
+ /// No description provided for @nowPlayingText.
+ ///
+ /// In en, this message translates to:
+ /// **'Now playing text'**
+ String get nowPlayingText;
+
+ /// No description provided for @nowPlayingTextSubtitle.
+ ///
+ /// In en, this message translates to:
+ /// **'Choose what the media controls show on each line'**
+ String get nowPlayingTextSubtitle;
+
+ /// No description provided for @nowPlayingTopLine.
+ ///
+ /// In en, this message translates to:
+ /// **'Top line'**
+ String get nowPlayingTopLine;
+
+ /// No description provided for @nowPlayingSecondLine.
+ ///
+ /// In en, this message translates to:
+ /// **'Second line'**
+ String get nowPlayingSecondLine;
+
+ /// No description provided for @nowPlayingNotShown.
+ ///
+ /// In en, this message translates to:
+ /// **'Not shown'**
+ String get nowPlayingNotShown;
+
+ /// No description provided for @nowPlayingTopLineRequired.
+ ///
+ /// In en, this message translates to:
+ /// **'The top line needs at least one item'**
+ String get nowPlayingTopLineRequired;
+
+ /// No description provided for @nowPlayingPieceChapter.
+ ///
+ /// In en, this message translates to:
+ /// **'Chapter'**
+ String get nowPlayingPieceChapter;
+
+ /// No description provided for @nowPlayingPieceTitle.
+ ///
+ /// In en, this message translates to:
+ /// **'Book title'**
+ String get nowPlayingPieceTitle;
+
+ /// No description provided for @nowPlayingPieceNarrator.
+ ///
+ /// In en, this message translates to:
+ /// **'Narrator'**
+ String get nowPlayingPieceNarrator;
+
+ /// No description provided for @nowPlayingPieceSeries.
+ ///
+ /// In en, this message translates to:
+ /// **'Series'**
+ String get nowPlayingPieceSeries;
+
+ /// No description provided for @nowPlayingPiecePercent.
+ ///
+ /// In en, this message translates to:
+ /// **'Book percentage'**
+ String get nowPlayingPiecePercent;
+
+ /// No description provided for @nowPlayingPieceChapterNumber.
+ ///
+ /// In en, this message translates to:
+ /// **'Chapter number'**
+ String get nowPlayingPieceChapterNumber;
+
+ /// No description provided for @nowPlayingPieceTimeLeft.
+ ///
+ /// In en, this message translates to:
+ /// **'Time left'**
+ String get nowPlayingPieceTimeLeft;
+
+ /// No description provided for @nowPlayingChapterNumber.
+ ///
+ /// In en, this message translates to:
+ /// **'Ch. {number}/{total}'**
+ String nowPlayingChapterNumber(int number, int total);
+
+ /// No description provided for @nowPlayingTimeLeft.
+ ///
+ /// In en, this message translates to:
+ /// **'{time} left'**
+ String nowPlayingTimeLeft(String time);
+
/// No description provided for @speedBookmarkInControls.
///
/// In en, this message translates to:
diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart
index a7d0a721..83f3fdd5 100644
--- a/lib/l10n/app_localizations_de.dart
+++ b/lib/l10n/app_localizations_de.dart
@@ -1775,6 +1775,57 @@ class AppLocalizationsDe extends AppLocalizations {
String get chapterProgressOnSubtitleIos =>
'An - Sperrbildschirm & CarPlay zeigen Kapitel Fortschritt';
+ @override
+ String get nowPlayingText => 'Now playing text';
+
+ @override
+ String get nowPlayingTextSubtitle =>
+ 'Choose what the media controls show on each line';
+
+ @override
+ String get nowPlayingTopLine => 'Top line';
+
+ @override
+ String get nowPlayingSecondLine => 'Second line';
+
+ @override
+ String get nowPlayingNotShown => 'Not shown';
+
+ @override
+ String get nowPlayingTopLineRequired =>
+ 'The top line needs at least one item';
+
+ @override
+ String get nowPlayingPieceChapter => 'Chapter';
+
+ @override
+ String get nowPlayingPieceTitle => 'Book title';
+
+ @override
+ String get nowPlayingPieceNarrator => 'Narrator';
+
+ @override
+ String get nowPlayingPieceSeries => 'Series';
+
+ @override
+ String get nowPlayingPiecePercent => 'Book percentage';
+
+ @override
+ String get nowPlayingPieceChapterNumber => 'Chapter number';
+
+ @override
+ String get nowPlayingPieceTimeLeft => 'Time left';
+
+ @override
+ String nowPlayingChapterNumber(int number, int total) {
+ return 'Ch. $number/$total';
+ }
+
+ @override
+ String nowPlayingTimeLeft(String time) {
+ return '$time left';
+ }
+
@override
String get speedBookmarkInControls =>
'Geschwindigkeit & Lesezeichen in Mediensteuerung';
diff --git a/lib/l10n/app_localizations_el.dart b/lib/l10n/app_localizations_el.dart
index ab60eefc..234f763a 100644
--- a/lib/l10n/app_localizations_el.dart
+++ b/lib/l10n/app_localizations_el.dart
@@ -1755,6 +1755,57 @@ class AppLocalizationsEl extends AppLocalizations {
String get chapterProgressOnSubtitleIos =>
'On - lock screen & CarPlay show chapter progress';
+ @override
+ String get nowPlayingText => 'Now playing text';
+
+ @override
+ String get nowPlayingTextSubtitle =>
+ 'Choose what the media controls show on each line';
+
+ @override
+ String get nowPlayingTopLine => 'Top line';
+
+ @override
+ String get nowPlayingSecondLine => 'Second line';
+
+ @override
+ String get nowPlayingNotShown => 'Not shown';
+
+ @override
+ String get nowPlayingTopLineRequired =>
+ 'The top line needs at least one item';
+
+ @override
+ String get nowPlayingPieceChapter => 'Chapter';
+
+ @override
+ String get nowPlayingPieceTitle => 'Book title';
+
+ @override
+ String get nowPlayingPieceNarrator => 'Narrator';
+
+ @override
+ String get nowPlayingPieceSeries => 'Series';
+
+ @override
+ String get nowPlayingPiecePercent => 'Book percentage';
+
+ @override
+ String get nowPlayingPieceChapterNumber => 'Chapter number';
+
+ @override
+ String get nowPlayingPieceTimeLeft => 'Time left';
+
+ @override
+ String nowPlayingChapterNumber(int number, int total) {
+ return 'Ch. $number/$total';
+ }
+
+ @override
+ String nowPlayingTimeLeft(String time) {
+ return '$time left';
+ }
+
@override
String get speedBookmarkInControls => 'Speed & bookmark in media controls';
diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart
index 785721d3..2c6c5019 100644
--- a/lib/l10n/app_localizations_en.dart
+++ b/lib/l10n/app_localizations_en.dart
@@ -1755,6 +1755,57 @@ class AppLocalizationsEn extends AppLocalizations {
String get chapterProgressOnSubtitleIos =>
'On - lock screen & CarPlay show chapter progress';
+ @override
+ String get nowPlayingText => 'Now playing text';
+
+ @override
+ String get nowPlayingTextSubtitle =>
+ 'Choose what the media controls show on each line';
+
+ @override
+ String get nowPlayingTopLine => 'Top line';
+
+ @override
+ String get nowPlayingSecondLine => 'Second line';
+
+ @override
+ String get nowPlayingNotShown => 'Not shown';
+
+ @override
+ String get nowPlayingTopLineRequired =>
+ 'The top line needs at least one item';
+
+ @override
+ String get nowPlayingPieceChapter => 'Chapter';
+
+ @override
+ String get nowPlayingPieceTitle => 'Book title';
+
+ @override
+ String get nowPlayingPieceNarrator => 'Narrator';
+
+ @override
+ String get nowPlayingPieceSeries => 'Series';
+
+ @override
+ String get nowPlayingPiecePercent => 'Book percentage';
+
+ @override
+ String get nowPlayingPieceChapterNumber => 'Chapter number';
+
+ @override
+ String get nowPlayingPieceTimeLeft => 'Time left';
+
+ @override
+ String nowPlayingChapterNumber(int number, int total) {
+ return 'Ch. $number/$total';
+ }
+
+ @override
+ String nowPlayingTimeLeft(String time) {
+ return '$time left';
+ }
+
@override
String get speedBookmarkInControls => 'Speed & bookmark in media controls';
diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart
index 464ba077..f29ec0fe 100644
--- a/lib/l10n/app_localizations_es.dart
+++ b/lib/l10n/app_localizations_es.dart
@@ -1757,6 +1757,57 @@ class AppLocalizationsEs extends AppLocalizations {
String get chapterProgressOnSubtitleIos =>
'On - lock screen & CarPlay show chapter progress';
+ @override
+ String get nowPlayingText => 'Now playing text';
+
+ @override
+ String get nowPlayingTextSubtitle =>
+ 'Choose what the media controls show on each line';
+
+ @override
+ String get nowPlayingTopLine => 'Top line';
+
+ @override
+ String get nowPlayingSecondLine => 'Second line';
+
+ @override
+ String get nowPlayingNotShown => 'Not shown';
+
+ @override
+ String get nowPlayingTopLineRequired =>
+ 'The top line needs at least one item';
+
+ @override
+ String get nowPlayingPieceChapter => 'Chapter';
+
+ @override
+ String get nowPlayingPieceTitle => 'Book title';
+
+ @override
+ String get nowPlayingPieceNarrator => 'Narrator';
+
+ @override
+ String get nowPlayingPieceSeries => 'Series';
+
+ @override
+ String get nowPlayingPiecePercent => 'Book percentage';
+
+ @override
+ String get nowPlayingPieceChapterNumber => 'Chapter number';
+
+ @override
+ String get nowPlayingPieceTimeLeft => 'Time left';
+
+ @override
+ String nowPlayingChapterNumber(int number, int total) {
+ return 'Ch. $number/$total';
+ }
+
+ @override
+ String nowPlayingTimeLeft(String time) {
+ return '$time left';
+ }
+
@override
String get speedBookmarkInControls => 'Speed & bookmark in media controls';
diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart
index 1d53b454..91ea384a 100644
--- a/lib/l10n/app_localizations_fr.dart
+++ b/lib/l10n/app_localizations_fr.dart
@@ -1780,6 +1780,57 @@ class AppLocalizationsFr extends AppLocalizations {
String get chapterProgressOnSubtitleIos =>
'Activé - l\'écran de verrouillage & CarPlay montrent la progression du chapitre';
+ @override
+ String get nowPlayingText => 'Now playing text';
+
+ @override
+ String get nowPlayingTextSubtitle =>
+ 'Choose what the media controls show on each line';
+
+ @override
+ String get nowPlayingTopLine => 'Top line';
+
+ @override
+ String get nowPlayingSecondLine => 'Second line';
+
+ @override
+ String get nowPlayingNotShown => 'Not shown';
+
+ @override
+ String get nowPlayingTopLineRequired =>
+ 'The top line needs at least one item';
+
+ @override
+ String get nowPlayingPieceChapter => 'Chapter';
+
+ @override
+ String get nowPlayingPieceTitle => 'Book title';
+
+ @override
+ String get nowPlayingPieceNarrator => 'Narrator';
+
+ @override
+ String get nowPlayingPieceSeries => 'Series';
+
+ @override
+ String get nowPlayingPiecePercent => 'Book percentage';
+
+ @override
+ String get nowPlayingPieceChapterNumber => 'Chapter number';
+
+ @override
+ String get nowPlayingPieceTimeLeft => 'Time left';
+
+ @override
+ String nowPlayingChapterNumber(int number, int total) {
+ return 'Ch. $number/$total';
+ }
+
+ @override
+ String nowPlayingTimeLeft(String time) {
+ return '$time left';
+ }
+
@override
String get speedBookmarkInControls =>
'Vitesse et signet dans les contrôles des médias';
diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart
index 4021bf74..2ace4b54 100644
--- a/lib/l10n/app_localizations_it.dart
+++ b/lib/l10n/app_localizations_it.dart
@@ -1755,6 +1755,57 @@ class AppLocalizationsIt extends AppLocalizations {
String get chapterProgressOnSubtitleIos =>
'On - lock screen & CarPlay show chapter progress';
+ @override
+ String get nowPlayingText => 'Now playing text';
+
+ @override
+ String get nowPlayingTextSubtitle =>
+ 'Choose what the media controls show on each line';
+
+ @override
+ String get nowPlayingTopLine => 'Top line';
+
+ @override
+ String get nowPlayingSecondLine => 'Second line';
+
+ @override
+ String get nowPlayingNotShown => 'Not shown';
+
+ @override
+ String get nowPlayingTopLineRequired =>
+ 'The top line needs at least one item';
+
+ @override
+ String get nowPlayingPieceChapter => 'Chapter';
+
+ @override
+ String get nowPlayingPieceTitle => 'Book title';
+
+ @override
+ String get nowPlayingPieceNarrator => 'Narrator';
+
+ @override
+ String get nowPlayingPieceSeries => 'Series';
+
+ @override
+ String get nowPlayingPiecePercent => 'Book percentage';
+
+ @override
+ String get nowPlayingPieceChapterNumber => 'Chapter number';
+
+ @override
+ String get nowPlayingPieceTimeLeft => 'Time left';
+
+ @override
+ String nowPlayingChapterNumber(int number, int total) {
+ return 'Ch. $number/$total';
+ }
+
+ @override
+ String nowPlayingTimeLeft(String time) {
+ return '$time left';
+ }
+
@override
String get speedBookmarkInControls => 'Speed & bookmark in media controls';
diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart
index 600d3595..f95a1c21 100644
--- a/lib/l10n/app_localizations_ja.dart
+++ b/lib/l10n/app_localizations_ja.dart
@@ -1755,6 +1755,57 @@ class AppLocalizationsJa extends AppLocalizations {
String get chapterProgressOnSubtitleIos =>
'On - lock screen & CarPlay show chapter progress';
+ @override
+ String get nowPlayingText => 'Now playing text';
+
+ @override
+ String get nowPlayingTextSubtitle =>
+ 'Choose what the media controls show on each line';
+
+ @override
+ String get nowPlayingTopLine => 'Top line';
+
+ @override
+ String get nowPlayingSecondLine => 'Second line';
+
+ @override
+ String get nowPlayingNotShown => 'Not shown';
+
+ @override
+ String get nowPlayingTopLineRequired =>
+ 'The top line needs at least one item';
+
+ @override
+ String get nowPlayingPieceChapter => 'Chapter';
+
+ @override
+ String get nowPlayingPieceTitle => 'Book title';
+
+ @override
+ String get nowPlayingPieceNarrator => 'Narrator';
+
+ @override
+ String get nowPlayingPieceSeries => 'Series';
+
+ @override
+ String get nowPlayingPiecePercent => 'Book percentage';
+
+ @override
+ String get nowPlayingPieceChapterNumber => 'Chapter number';
+
+ @override
+ String get nowPlayingPieceTimeLeft => 'Time left';
+
+ @override
+ String nowPlayingChapterNumber(int number, int total) {
+ return 'Ch. $number/$total';
+ }
+
+ @override
+ String nowPlayingTimeLeft(String time) {
+ return '$time left';
+ }
+
@override
String get speedBookmarkInControls => 'Speed & bookmark in media controls';
diff --git a/lib/l10n/app_localizations_no.dart b/lib/l10n/app_localizations_no.dart
index 3017fb3b..77585824 100644
--- a/lib/l10n/app_localizations_no.dart
+++ b/lib/l10n/app_localizations_no.dart
@@ -1755,6 +1755,57 @@ class AppLocalizationsNo extends AppLocalizations {
String get chapterProgressOnSubtitleIos =>
'On - lock screen & CarPlay show chapter progress';
+ @override
+ String get nowPlayingText => 'Now playing text';
+
+ @override
+ String get nowPlayingTextSubtitle =>
+ 'Choose what the media controls show on each line';
+
+ @override
+ String get nowPlayingTopLine => 'Top line';
+
+ @override
+ String get nowPlayingSecondLine => 'Second line';
+
+ @override
+ String get nowPlayingNotShown => 'Not shown';
+
+ @override
+ String get nowPlayingTopLineRequired =>
+ 'The top line needs at least one item';
+
+ @override
+ String get nowPlayingPieceChapter => 'Chapter';
+
+ @override
+ String get nowPlayingPieceTitle => 'Book title';
+
+ @override
+ String get nowPlayingPieceNarrator => 'Narrator';
+
+ @override
+ String get nowPlayingPieceSeries => 'Series';
+
+ @override
+ String get nowPlayingPiecePercent => 'Book percentage';
+
+ @override
+ String get nowPlayingPieceChapterNumber => 'Chapter number';
+
+ @override
+ String get nowPlayingPieceTimeLeft => 'Time left';
+
+ @override
+ String nowPlayingChapterNumber(int number, int total) {
+ return 'Ch. $number/$total';
+ }
+
+ @override
+ String nowPlayingTimeLeft(String time) {
+ return '$time left';
+ }
+
@override
String get speedBookmarkInControls => 'Speed & bookmark in media controls';
diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart
index 720fbf17..086d57a1 100644
--- a/lib/l10n/app_localizations_pt.dart
+++ b/lib/l10n/app_localizations_pt.dart
@@ -1755,6 +1755,57 @@ class AppLocalizationsPt extends AppLocalizations {
String get chapterProgressOnSubtitleIos =>
'On - lock screen & CarPlay show chapter progress';
+ @override
+ String get nowPlayingText => 'Now playing text';
+
+ @override
+ String get nowPlayingTextSubtitle =>
+ 'Choose what the media controls show on each line';
+
+ @override
+ String get nowPlayingTopLine => 'Top line';
+
+ @override
+ String get nowPlayingSecondLine => 'Second line';
+
+ @override
+ String get nowPlayingNotShown => 'Not shown';
+
+ @override
+ String get nowPlayingTopLineRequired =>
+ 'The top line needs at least one item';
+
+ @override
+ String get nowPlayingPieceChapter => 'Chapter';
+
+ @override
+ String get nowPlayingPieceTitle => 'Book title';
+
+ @override
+ String get nowPlayingPieceNarrator => 'Narrator';
+
+ @override
+ String get nowPlayingPieceSeries => 'Series';
+
+ @override
+ String get nowPlayingPiecePercent => 'Book percentage';
+
+ @override
+ String get nowPlayingPieceChapterNumber => 'Chapter number';
+
+ @override
+ String get nowPlayingPieceTimeLeft => 'Time left';
+
+ @override
+ String nowPlayingChapterNumber(int number, int total) {
+ return 'Ch. $number/$total';
+ }
+
+ @override
+ String nowPlayingTimeLeft(String time) {
+ return '$time left';
+ }
+
@override
String get speedBookmarkInControls => 'Speed & bookmark in media controls';
diff --git a/lib/l10n/app_localizations_ro.dart b/lib/l10n/app_localizations_ro.dart
index abb0b0db..9c389c22 100644
--- a/lib/l10n/app_localizations_ro.dart
+++ b/lib/l10n/app_localizations_ro.dart
@@ -1755,6 +1755,57 @@ class AppLocalizationsRo extends AppLocalizations {
String get chapterProgressOnSubtitleIos =>
'On - lock screen & CarPlay show chapter progress';
+ @override
+ String get nowPlayingText => 'Now playing text';
+
+ @override
+ String get nowPlayingTextSubtitle =>
+ 'Choose what the media controls show on each line';
+
+ @override
+ String get nowPlayingTopLine => 'Top line';
+
+ @override
+ String get nowPlayingSecondLine => 'Second line';
+
+ @override
+ String get nowPlayingNotShown => 'Not shown';
+
+ @override
+ String get nowPlayingTopLineRequired =>
+ 'The top line needs at least one item';
+
+ @override
+ String get nowPlayingPieceChapter => 'Chapter';
+
+ @override
+ String get nowPlayingPieceTitle => 'Book title';
+
+ @override
+ String get nowPlayingPieceNarrator => 'Narrator';
+
+ @override
+ String get nowPlayingPieceSeries => 'Series';
+
+ @override
+ String get nowPlayingPiecePercent => 'Book percentage';
+
+ @override
+ String get nowPlayingPieceChapterNumber => 'Chapter number';
+
+ @override
+ String get nowPlayingPieceTimeLeft => 'Time left';
+
+ @override
+ String nowPlayingChapterNumber(int number, int total) {
+ return 'Ch. $number/$total';
+ }
+
+ @override
+ String nowPlayingTimeLeft(String time) {
+ return '$time left';
+ }
+
@override
String get speedBookmarkInControls => 'Speed & bookmark in media controls';
diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart
index 318f9a2c..1cf3e4cf 100644
--- a/lib/l10n/app_localizations_ru.dart
+++ b/lib/l10n/app_localizations_ru.dart
@@ -1758,6 +1758,57 @@ class AppLocalizationsRu extends AppLocalizations {
String get chapterProgressOnSubtitleIos =>
'Вкл. - блокировка экрана и CarPlay покажут прогресс главы';
+ @override
+ String get nowPlayingText => 'Now playing text';
+
+ @override
+ String get nowPlayingTextSubtitle =>
+ 'Choose what the media controls show on each line';
+
+ @override
+ String get nowPlayingTopLine => 'Top line';
+
+ @override
+ String get nowPlayingSecondLine => 'Second line';
+
+ @override
+ String get nowPlayingNotShown => 'Not shown';
+
+ @override
+ String get nowPlayingTopLineRequired =>
+ 'The top line needs at least one item';
+
+ @override
+ String get nowPlayingPieceChapter => 'Chapter';
+
+ @override
+ String get nowPlayingPieceTitle => 'Book title';
+
+ @override
+ String get nowPlayingPieceNarrator => 'Narrator';
+
+ @override
+ String get nowPlayingPieceSeries => 'Series';
+
+ @override
+ String get nowPlayingPiecePercent => 'Book percentage';
+
+ @override
+ String get nowPlayingPieceChapterNumber => 'Chapter number';
+
+ @override
+ String get nowPlayingPieceTimeLeft => 'Time left';
+
+ @override
+ String nowPlayingChapterNumber(int number, int total) {
+ return 'Ch. $number/$total';
+ }
+
+ @override
+ String nowPlayingTimeLeft(String time) {
+ return '$time left';
+ }
+
@override
String get speedBookmarkInControls =>
'Скорость и закладки в панели управления медиа';
diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart
index 88b4ac17..eeccfdd8 100644
--- a/lib/l10n/app_localizations_zh.dart
+++ b/lib/l10n/app_localizations_zh.dart
@@ -1728,6 +1728,57 @@ class AppLocalizationsZh extends AppLocalizations {
String get chapterProgressOnSubtitleIos =>
'On - lock screen & CarPlay show chapter progress';
+ @override
+ String get nowPlayingText => 'Now playing text';
+
+ @override
+ String get nowPlayingTextSubtitle =>
+ 'Choose what the media controls show on each line';
+
+ @override
+ String get nowPlayingTopLine => 'Top line';
+
+ @override
+ String get nowPlayingSecondLine => 'Second line';
+
+ @override
+ String get nowPlayingNotShown => 'Not shown';
+
+ @override
+ String get nowPlayingTopLineRequired =>
+ 'The top line needs at least one item';
+
+ @override
+ String get nowPlayingPieceChapter => 'Chapter';
+
+ @override
+ String get nowPlayingPieceTitle => 'Book title';
+
+ @override
+ String get nowPlayingPieceNarrator => 'Narrator';
+
+ @override
+ String get nowPlayingPieceSeries => 'Series';
+
+ @override
+ String get nowPlayingPiecePercent => 'Book percentage';
+
+ @override
+ String get nowPlayingPieceChapterNumber => 'Chapter number';
+
+ @override
+ String get nowPlayingPieceTimeLeft => 'Time left';
+
+ @override
+ String nowPlayingChapterNumber(int number, int total) {
+ return 'Ch. $number/$total';
+ }
+
+ @override
+ String nowPlayingTimeLeft(String time) {
+ return '$time left';
+ }
+
@override
String get speedBookmarkInControls => 'Speed & bookmark in media controls';
diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart
index 60c771dd..b0da4060 100644
--- a/lib/screens/settings_screen.dart
+++ b/lib/screens/settings_screen.dart
@@ -25,6 +25,7 @@ import '../services/update_checker_service.dart';
import '../services/audiobookshelf_update_service.dart';
import '../widgets/update_dialog.dart';
import '../widgets/nav_hold_options.dart';
+import '../widgets/now_playing_text_sheet.dart';
import '../screens/admin_screen.dart';
import '../screens/downloads_screen.dart';
import '../screens/bookmarks_screen.dart';
@@ -3092,6 +3093,14 @@ class _SettingsScreenState extends State<SettingsScreen> {
} : null,
),
const Divider(height: 1, indent: 16, endIndent: 16),
+ ListTile(
+ title: Text(l.nowPlayingText),
+ subtitle: Text(l.nowPlayingTextSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ trailing: Icon(Icons.chevron_right_rounded, color: cs.onSurfaceVariant),
+ onTap: () => NowPlayingTextSheet.show(context),
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
// Cross-platform: drops the seek action so the scrubber in the
// notification / lockscreen / car can't be dragged.
SwitchListTile(
diff --git a/lib/screens/settings_search_index.dart b/lib/screens/settings_search_index.dart
index 41fd53ec..a5303eb3 100644
--- a/lib/screens/settings_search_index.dart
+++ b/lib/screens/settings_search_index.dart
@@ -70,6 +70,7 @@ List<SettingSearchEntry> settingsSearchEntries(BuildContext context) {
// ── Media Controls ──
SettingSearchEntry('Media Controls', l.sectionMediaControls, l.chapterProgressInNotification, [l.chapterProgressInNotificationIos, l.chapterProgressOnSubtitle, l.chapterProgressOnSubtitleIos, l.chapterProgressOffSubtitle]),
+ SettingSearchEntry('Media Controls', l.sectionMediaControls, l.nowPlayingText, [l.nowPlayingTextSubtitle, l.nowPlayingPiecePercent, l.nowPlayingPieceTimeLeft, l.nowPlayingPieceNarrator, l.nowPlayingPieceSeries]),
SettingSearchEntry('Media Controls', l.sectionMediaControls, l.lockSeekBar, [l.lockSeekBarOnSubtitle, l.lockSeekBarOffSubtitle]),
if (Platform.isAndroid) ...[
SettingSearchEntry('Media Controls', l.sectionMediaControls, 'Duck brief interruptions', const ['Notifications and prompts lower the volume instead of pausing', 'Notifications and prompts pause playback']),
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dart
index 1e074045..77791db0 100644
--- a/lib/services/audio_player_service.dart
+++ b/lib/services/audio_player_service.dart
@@ -1,6 +1,7 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
+import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '_audio_player.dart';
@@ -21,6 +22,7 @@ import 'external_audio_output_types.dart';
import 'android_auto_service.dart';
import 'chromecast_service.dart';
import 'chapter_lookup.dart';
+import 'now_playing_layout.dart';
import 'cold_start_play_policy.dart';
import 'playback_error_policy.dart';
import 'player_settings.dart';
@@ -29,6 +31,9 @@ import 'home_widget_service.dart';
import 'bookmark_service.dart';
import 'review_service.dart';
import '../utils/episode_key.dart';
+import '../utils/duration_format.dart';
+import '../l10n/app_localizations.dart';
+import '../main.dart' show rootNavigatorKey;
export 'player_settings.dart';
String playbackDownloadKey(String itemId, String? episodeId) =>
@@ -1622,28 +1627,40 @@ class AudioPlayerService extends ChangeNotifier {
double _currentChapterStart = 0;
double _currentChapterEnd = 0;
bool get notifChapterMode => _notifChapterMode && _chapters.isNotEmpty;
+ NowPlayingLayout _nowPlayingLayout = NowPlayingLayout.standard;
+ String _nowPlayingLayoutJson = '';
+ bool _speedAdjustedTime = true;
+ // The moving parts (percent, minutes left) the media controls last showed.
+ String _lastNowPlayingTicker = '-1|-1';
+ String? _currentNarrator;
+ String? _currentSeries;
double get currentChapterStart => _currentChapterStart;
double get currentChapterEnd => _currentChapterEnd;
void _onSettingsChanged() {
- PlayerSettings.getNotificationChapterProgress().then((v) {
- if (v == _notifChapterMode) return;
- _notifChapterMode = v;
+ Future.wait<Object>([
+ PlayerSettings.getNotificationChapterProgress(),
+ PlayerSettings.getNowPlayingLayout(),
+ PlayerSettings.getSpeedAdjustedTime(),
+ ]).then((v) {
+ final chapterMode = v[0] as bool;
+ final layoutJson = v[1] as String;
+ final speedAdjusted = v[2] as bool;
+ final chapterModeChanged = chapterMode != _notifChapterMode;
+ final textChanged = layoutJson != _nowPlayingLayoutJson ||
+ (speedAdjusted != _speedAdjustedTime &&
+ _nowPlayingLayout.uses(NowPlayingPiece.timeLeft));
+ _notifChapterMode = chapterMode;
+ _speedAdjustedTime = speedAdjusted;
+ if (layoutJson != _nowPlayingLayoutJson) {
+ _nowPlayingLayoutJson = layoutJson;
+ _nowPlayingLayout = NowPlayingLayout.fromJson(layoutJson);
+ }
+ if (!chapterModeChanged && !textChanged) return;
// Re-push MediaItem + PlaybackState so notification updates immediately
if (_currentItemId != null) {
- _pushMediaItem(
- _mediaItemKey,
- _currentTitle ?? '',
- _currentAuthor ?? '',
- _currentCoverUrl,
- _totalDuration,
- chapter: _lastNotifiedChapterIndex >= 0 && _chapters.isNotEmpty
- ? (_chapters[_lastNotifiedChapterIndex]
- as Map<String, dynamic>)['title']
- as String?
- : null,
- );
- _handler?.refreshPlaybackState();
+ _repushNotifiedMediaItem();
+ if (chapterModeChanged) _handler?.refreshPlaybackState();
}
});
// Update cached skip amounts so notification icons stay in sync
@@ -2099,15 +2116,22 @@ class AudioPlayerService extends ChangeNotifier {
final startS = (next['startS'] as num?)?.toDouble() ?? 0;
- // GH #298: label the pre-buffered next book like the lock screen — its
- // chapter at the resume point as title, "Author · Book" beneath.
- final nextLabels = nowPlayingLabels(
- (next['title'] as String?) ?? '',
- (next['author'] as String?) ?? '',
- _chapterTitleAt(
- (next['chapters'] as List<dynamic>?) ?? const [],
- startS,
- ),
+ // Label the pre-buffered next book like the lock screen: the same
+ // layout, at its resume point.
+ final nextTitle = (next['title'] as String?) ?? '';
+ final nextChapters = (next['chapters'] as List<dynamic>?) ?? const [];
+ final nextChapterIndex = _chapterIndexAt(nextChapters, startS);
+ final nextLabels = _nowPlayingLines(
+ title: nextTitle,
+ author: (next['author'] as String?) ?? '',
+ chapter: nextChapterIndex >= 0
+ ? (nextChapters[nextChapterIndex] as Map<String, dynamic>)['title']
+ as String?
+ : null,
+ chapterIndex: nextChapterIndex,
+ chapterCount: nextChapters.length,
+ posSec: startS,
+ totalDuration: (next['duration'] as num?)?.toDouble() ?? 0,
);
final ok = await _queueAdvancerChannel.invokeMethod<bool>('prepareNext', {
@@ -2116,6 +2140,7 @@ class AudioPlayerService extends ChangeNotifier {
'headers': audioHeaders ?? <String, String>{},
'title': nextLabels.title,
'artist': nextLabels.subtitle,
+ 'album': nextTitle,
'durationS': (next['duration'] as num?)?.toDouble() ?? 0,
'coverPath': coverPath,
'startS': startS,
@@ -2151,6 +2176,8 @@ class AudioPlayerService extends ChangeNotifier {
_syncNotifSkipCache();
_currentTitle = next['title'] as String?;
_currentAuthor = next['author'] as String?;
+ _currentNarrator = null;
+ _currentSeries = null;
_currentCoverUrl = next['coverUrl'] as String?;
_totalDuration = (next['duration'] as num?)?.toDouble() ?? 0;
_metaDuration = _totalDuration;
@@ -2527,12 +2554,23 @@ class AudioPlayerService extends ChangeNotifier {
String? chapter,
}) async {
if (!Platform.isIOS) return;
- // GH #298: match the lock screen — chapter as title, "Author · Book" beneath.
- final labels = nowPlayingLabels(title, artist, chapter);
+ // Match the lock screen, which uses the same layout.
+ final labels = _nowPlayingLines(
+ title: title,
+ author: artist,
+ chapter: chapter,
+ chapterIndex: chapter == null ? -1 : _lastNotifiedChapterIndex,
+ chapterCount: _chapters.length,
+ posSec: elapsed,
+ totalDuration: duration,
+ narrator: _currentNarrator,
+ series: _currentSeries,
+ );
try {
await _eqChannelForDiag.invokeMethod('primeNowPlaying', {
'title': labels.title,
'artist': labels.subtitle,
+ 'album': title,
'duration': duration,
'elapsed': elapsed,
});
@@ -2960,6 +2998,11 @@ class AudioPlayerService extends ChangeNotifier {
// Load notification chapter progress setting and watch for changes
_instance._notifChapterMode =
await PlayerSettings.getNotificationChapterProgress();
+ _instance._nowPlayingLayoutJson =
+ await PlayerSettings.getNowPlayingLayout();
+ _instance._nowPlayingLayout =
+ NowPlayingLayout.fromJson(_instance._nowPlayingLayoutJson);
+ _instance._speedAdjustedTime = await PlayerSettings.getSpeedAdjustedTime();
PlayerSettings.settingsChanged.addListener(_instance._onSettingsChanged);
// Configure audio session for audiobook playback
await _configureAudioSession();
@@ -3652,6 +3695,8 @@ class AudioPlayerService extends ChangeNotifier {
_currentEpisodeTitle = episodeTitle;
_currentTitle = title;
_currentAuthor = author;
+ _currentNarrator = null;
+ _currentSeries = null;
_currentCoverUrl = coverUrl;
_totalDuration = totalDuration;
_metaDuration = totalDuration;
@@ -4318,6 +4363,7 @@ class AudioPlayerService extends ChangeNotifier {
try {
final session = jsonDecode(cachedJson) as Map<String, dynamic>;
audioTracks = session['audioTracks'] as List<dynamic>?;
+ _captureNowPlayingCredits(session);
// Fall back to the cached session duration when the caller didn't have
// one (e.g. podcast cold-start from Android Auto pushes dur=0). Replaces
// the old /play-response duration fallback now that local plays skip it.
@@ -4770,6 +4816,7 @@ class AudioPlayerService extends ChangeNotifier {
_playbackSessionId = sessionData['id'] as String?;
_lastServerSync = DateTime.now();
debugPrint('[Player] Background session refreshed: $_playbackSessionId');
+ _captureNowPlayingCredits(sessionData);
_logEvent(PlaybackEventType.sessionStart, detail: 'refresh');
// Update cached session with fresh track data in case it changed
@@ -4873,6 +4920,7 @@ class AudioPlayerService extends ChangeNotifier {
}
_playbackSessionId = ownSessionId;
+ _captureNowPlayingCredits(sessionData);
// Sessions know their library; adopt it when the caller couldn't provide
// one so per-library skip amounts work for lean/merged shelf items.
final sessionLibId = sessionData['libraryId'] as String?;
@@ -5398,17 +5446,18 @@ class AudioPlayerService extends ChangeNotifier {
}
/// Set _currentChapterStart/End for the chapter containing [posSeconds].
- /// Chapter title covering [posSeconds] in an arbitrary chapter list (used for
- /// the pre-buffered next book, whose chapters aren't in [_chapters] yet).
- String? _chapterTitleAt(List<dynamic> chapters, double posSeconds) {
- if (chapters.isEmpty) return null;
- for (final ch in chapters) {
- final m = ch as Map<String, dynamic>;
+ /// Index of the chapter covering [posSeconds] in an arbitrary chapter list
+ /// (used for the pre-buffered next book, whose chapters aren't in
+ /// [_chapters] yet), the first one when none does, or -1 with no chapters.
+ int _chapterIndexAt(List<dynamic> chapters, double posSeconds) {
+ if (chapters.isEmpty) return -1;
+ for (var i = 0; i < chapters.length; i++) {
+ final m = chapters[i] as Map<String, dynamic>;
final start = (m['start'] as num?)?.toDouble() ?? 0;
final end = (m['end'] as num?)?.toDouble() ?? double.infinity;
- if (posSeconds >= start && posSeconds < end) return m['title'] as String?;
+ if (posSeconds >= start && posSeconds < end) return i;
}
- return (chapters.first as Map<String, dynamic>)['title'] as String?;
+ return 0;
}
/// Returns the chapter title (or null) so _pushMediaItem can show it.
@@ -5457,6 +5506,7 @@ class AudioPlayerService extends ChangeNotifier {
double totalDuration, {
String? chapter,
int? coverCacheBust,
+ double? positionSec,
}) {
// Alpha [PodDur]: trace every push-site. We want to see which callers
// pass only the parent itemId (missing -episodeId suffix) and/or a zero
@@ -5507,9 +5557,157 @@ class AudioPlayerService extends ChangeNotifier {
effectiveCoverUrl,
totalDuration,
chapter: chapter,
+ positionSec: positionSec,
);
}
+ /// Push the media item again for the chapter already showing, e.g. when a
+ /// setting or the book percentage changes.
+ void _repushNotifiedMediaItem({double? positionSec}) {
+ _pushMediaItem(
+ _mediaItemKey,
+ _currentTitle ?? '',
+ _currentAuthor ?? '',
+ _currentCoverUrl,
+ _totalDuration,
+ chapter: _lastNotifiedChapterIndex >= 0 &&
+ _lastNotifiedChapterIndex < _chapters.length
+ ? (_chapters[_lastNotifiedChapterIndex]
+ as Map<String, dynamic>)['title']
+ as String?
+ : null,
+ positionSec: positionSec,
+ );
+ }
+
+ static int _bookPercent(double posSec, double totalDuration) =>
+ totalDuration > 0
+ ? (posSec / totalDuration * 100).floor().clamp(0, 100)
+ : -1;
+
+ double _secondsLeft(double posSec, double totalDuration) {
+ final left = math.max(0.0, totalDuration - posSec);
+ final speed = _player?.speed ?? 1.0;
+ return _speedAdjustedTime && speed > 0 ? left / speed : left;
+ }
+
+ /// The moving parts of the media controls text at [posSec], so the
+ /// position tick only re-sends it when what it shows would change.
+ String _nowPlayingTicker(double posSec, double totalDuration) {
+ final layout = _nowPlayingLayout;
+ final percent = layout.uses(NowPlayingPiece.percent)
+ ? _bookPercent(posSec, totalDuration)
+ : -1;
+ final minutes = layout.uses(NowPlayingPiece.timeLeft) && totalDuration > 0
+ ? (_secondsLeft(posSec, totalDuration) / 60).floor()
+ : -1;
+ return '$percent|$minutes';
+ }
+
+ static AppLocalizations? _l10n() {
+ final ctx = rootNavigatorKey.currentContext;
+ return ctx != null ? AppLocalizations.of(ctx) : null;
+ }
+
+ /// Both lines of the media controls for an item, in the layout the user
+ /// picked (Settings > Media Controls > Now playing text).
+ ({String title, String subtitle}) _nowPlayingLines({
+ required String title,
+ required String author,
+ required String? chapter,
+ required int chapterIndex,
+ required int chapterCount,
+ required double posSec,
+ required double totalDuration,
+ String? narrator,
+ String? series,
+ NowPlayingLayout? layout,
+ }) {
+ final l = _l10n();
+ final percent = _bookPercent(posSec, totalDuration);
+ final left = totalDuration > 0
+ ? formatHm(_secondsLeft(posSec, totalDuration))
+ : null;
+ final hasChapter = chapterIndex >= 0 && chapterCount > 0;
+ return (layout ?? _nowPlayingLayout).build(NowPlayingValues(
+ title: title,
+ author: author,
+ chapter: chapter,
+ narrator: narrator,
+ series: series,
+ percent: percent >= 0 ? '$percent%' : null,
+ chapterNumber: hasChapter
+ ? (l?.nowPlayingChapterNumber(chapterIndex + 1, chapterCount) ??
+ 'Ch. ${chapterIndex + 1}/$chapterCount')
+ : null,
+ timeLeft: left == null
+ ? null
+ : (l?.nowPlayingTimeLeft(left) ?? '$left left'),
+ ));
+ }
+
+ /// What the media controls would show for the playing item with [layout],
+ /// for the settings preview; null with nothing loaded.
+ ({String title, String subtitle})? previewNowPlayingLines(
+ NowPlayingLayout layout,
+ ) {
+ if (_currentItemId == null) return null;
+ final chapterIndex = _lastNotifiedChapterIndex >= 0 &&
+ _lastNotifiedChapterIndex < _chapters.length
+ ? _lastNotifiedChapterIndex
+ : -1;
+ return _nowPlayingLines(
+ title: _currentTitle ?? '',
+ author: _currentAuthor ?? '',
+ chapter: chapterIndex >= 0
+ ? (_chapters[chapterIndex] as Map<String, dynamic>)['title'] as String?
+ : null,
+ chapterIndex: chapterIndex,
+ chapterCount: _chapters.length,
+ posSec: position.inMilliseconds / 1000.0,
+ totalDuration: _totalDuration,
+ narrator: _currentNarrator,
+ series: _currentSeries,
+ layout: layout,
+ );
+ }
+
+ /// Narrator and series for the media controls, from a playback session's
+ /// book details. Re-sends the text when they arrive after it went out.
+ void _captureNowPlayingCredits(Map<String, dynamic>? session) {
+ final meta = session?['mediaMetadata'];
+ if (meta is! Map) return;
+ String? joined(Object? names) {
+ if (names is! List) return null;
+ final parts = names
+ .map((n) => (n is Map ? n['name'] : n)?.toString().trim() ?? '')
+ .where((n) => n.isNotEmpty);
+ return parts.isEmpty ? null : parts.join(', ');
+ }
+ final narrator = joined(meta['narrators']) ??
+ (meta['narratorName'] is String ? meta['narratorName'] as String : null);
+ String? series;
+ final seriesList = meta['series'];
+ if (seriesList is List && seriesList.isNotEmpty && seriesList.first is Map) {
+ final first = seriesList.first as Map;
+ final name = first['name']?.toString().trim() ?? '';
+ final sequence = first['sequence']?.toString().trim() ?? '';
+ if (name.isNotEmpty) {
+ series = sequence.isEmpty ? name : '$name #$sequence';
+ }
+ } else if (meta['seriesName'] is String) {
+ series = meta['seriesName'] as String;
+ }
+ if (narrator == _currentNarrator && series == _currentSeries) return;
+ _currentNarrator = narrator;
+ _currentSeries = series;
+ if (_currentItemId != null &&
+ (_nowPlayingLayout.uses(NowPlayingPiece.narrator) ||
+ _nowPlayingLayout.uses(NowPlayingPiece.series))) {
+ _repushNotifiedMediaItem();
+ }
+ }
+
void _scheduleStreamedCoverRepush(String itemId) {
_coverRepushTimer?.cancel();
_coverRepushTimer = Timer(const Duration(seconds: 3), () {
@@ -5541,9 +5739,21 @@ class AudioPlayerService extends ChangeNotifier {
String? coverUrl,
double totalDuration, {
String? chapter,
+ double? positionSec,
}) {
- // GH #298: chapter becomes the title, book moves beside the author.
- final labels = nowPlayingLabels(title, author, chapter);
+ final posSec = positionSec ?? position.inMilliseconds / 1000.0;
+ final labels = _nowPlayingLines(
+ title: title,
+ author: author,
+ chapter: chapter,
+ chapterIndex: chapter == null ? -1 : _lastNotifiedChapterIndex,
+ chapterCount: _chapters.length,
+ posSec: posSec,
+ totalDuration: totalDuration,
+ narrator: _currentNarrator,
+ series: _currentSeries,
+ );
+ _lastNowPlayingTicker = _nowPlayingTicker(posSec, totalDuration);
// In chapter progress mode, show chapter duration instead of full book
final rawDuration = notifChapterMode
? (_currentChapterEnd - _currentChapterStart)
@@ -5580,6 +5790,8 @@ class AudioPlayerService extends ChangeNotifier {
_currentEpisodeTitle = null;
_currentTitle = null;
_currentAuthor = null;
+ _currentNarrator = null;
+ _currentSeries = null;
_currentCoverUrl = null;
_coverRepushTimer?.cancel();
_coverRepushItem = null;
@@ -6122,6 +6334,7 @@ class AudioPlayerService extends ChangeNotifier {
_currentCoverUrl,
_totalDuration,
chapter: chapterTitle,
+ positionSec: posSec,
);
// Force PlaybackState refresh so the notification position resets
// to 0 immediately instead of waiting for the next stream event.
@@ -6129,6 +6342,12 @@ class AudioPlayerService extends ChangeNotifier {
}
}
+ if (_currentItemId != null &&
+ _nowPlayingTicker(posSec, _totalDuration) !=
+ _lastNowPlayingTicker) {
+ _repushNotifiedMediaItem(positionSec: posSec);
+ }
+
// ─── Completion detection (fallback) ───────────────────
// processingStateStream is the primary signal; this is a safety net.
if (_totalDuration > 0 && posSec >= _totalDuration - 1.0) {
diff --git a/lib/services/backup_service.dart b/lib/services/backup_service.dart
index 092c10bc..4b9c17c9 100644
--- a/lib/services/backup_service.dart
+++ b/lib/services/backup_service.dart
@@ -76,6 +76,7 @@ class BackupService {
'bookmarkSort': await PlayerSettings.getBookmarkSort(),
'autoDownloadOnStream': await PlayerSettings.getAutoDownloadOnStream(),
'notificationChapterProgress': await PlayerSettings.getNotificationChapterProgress(),
+ 'nowPlayingLayout': await PlayerSettings.getNowPlayingLayout(),
'sleepTimerMinutes': await PlayerSettings.getSleepTimerMinutes(),
'sleepTimerChapters': await PlayerSettings.getSleepTimerChapters(),
'streamingCacheSizeMb': await PlayerSettings.getStreamingCacheSizeMb(),
@@ -601,6 +602,7 @@ class BackupService {
if (s['bookmarkSort'] != null) PlayerSettings.setBookmarkSort(s['bookmarkSort'] as String);
if (s['autoDownloadOnStream'] != null) PlayerSettings.setAutoDownloadOnStream(s['autoDownloadOnStream'] as bool);
if (s['notificationChapterProgress'] != null) PlayerSettings.setNotificationChapterProgress(s['notificationChapterProgress'] as bool);
+ if (s['nowPlayingLayout'] is String) PlayerSettings.setNowPlayingLayout(s['nowPlayingLayout'] as String);
if (s['sleepTimerMinutes'] != null) PlayerSettings.setSleepTimerMinutes(s['sleepTimerMinutes'] as int);
if (s['sleepTimerChapters'] != null) PlayerSettings.setSleepTimerChapters(s['sleepTimerChapters'] as int);
if (s['streamingCacheSizeMb'] != null) PlayerSettings.setStreamingCacheSizeMb(s['streamingCacheSizeMb'] as int);
diff --git a/lib/services/now_playing_layout.dart b/lib/services/now_playing_layout.dart
new file mode 100644
index 00000000..4233ff54
--- /dev/null
+++ b/lib/services/now_playing_layout.dart
@@ -0,0 +1,137 @@
+import 'dart:convert';
+
+/// A piece of text the media controls (notification, Android Auto, lock
+/// screen, CarPlay) can show on one of their two lines.
+enum NowPlayingPiece {
+ chapter,
+ title,
+ author,
+ narrator,
+ series,
+ percent,
+ chapterNumber,
+ timeLeft,
+}
+
+/// The text each piece shows for the playing item, already formatted.
+class NowPlayingValues {
+ final String title;
+ final String author;
+ final String? chapter;
+ final String? narrator;
+ final String? series;
+ final String? percent;
+ final String? chapterNumber;
+ final String? timeLeft;
+
+ const NowPlayingValues({
+ required this.title,
+ required this.author,
+ this.chapter,
+ this.narrator,
+ this.series,
+ this.percent,
+ this.chapterNumber,
+ this.timeLeft,
+ });
+
+ String textFor(NowPlayingPiece piece) {
+ final text = switch (piece) {
+ NowPlayingPiece.chapter => chapter,
+ NowPlayingPiece.title => title,
+ NowPlayingPiece.author => author,
+ NowPlayingPiece.narrator => narrator,
+ NowPlayingPiece.series => series,
+ NowPlayingPiece.percent => percent,
+ NowPlayingPiece.chapterNumber => chapterNumber,
+ NowPlayingPiece.timeLeft => timeLeft,
+ };
+ return text?.trim() ?? '';
+ }
+}
+
+/// Which pieces go on the top and second line, in order.
+class NowPlayingLayout {
+ final List<NowPlayingPiece> top;
+ final List<NowPlayingPiece> second;
+
+ const NowPlayingLayout({required this.top, required this.second});
+
+ /// GH #298: the chapter on top, "Author · Book" beneath.
+ static const standard = NowPlayingLayout(
+ top: [NowPlayingPiece.chapter],
+ second: [NowPlayingPiece.author, NowPlayingPiece.title],
+ );
+
+ static const separator = ' · ';
+
+ // Tried in order when nothing on the top line has text (no chapters, say).
+ static const _topFallbacks = [
+ NowPlayingPiece.title,
+ NowPlayingPiece.chapter,
+ NowPlayingPiece.author,
+ ];
+
+ bool uses(NowPlayingPiece piece) =>
+ top.contains(piece) || second.contains(piece);
+
+ List<NowPlayingPiece> get unused =>
+ NowPlayingPiece.values.where((p) => !uses(p)).toList();
+
+ bool get isStandard =>
+ _sameOrder(top, standard.top) && _sameOrder(second, standard.second);
+
+ ({String title, String subtitle}) build(NowPlayingValues values) {
+ String line(Iterable<NowPlayingPiece> pieces) => pieces
+ .map(values.textFor)
+ .where((text) => text.isNotEmpty)
+ .join(separator);
+
+ var title = line(top);
+ var secondPieces = second;
+ if (title.isEmpty) {
+ for (final piece in _topFallbacks) {
+ final text = values.textFor(piece);
+ if (text.isEmpty) continue;
+ title = text;
+ secondPieces = second.where((p) => p != piece).toList();
+ break;
+ }
+ }
+ return (title: title, subtitle: line(secondPieces));
+ }
+
+ String toJson() => jsonEncode({
+ 'top': top.map((p) => p.name).toList(),
+ 'second': second.map((p) => p.name).toList(),
+ });
+
+ /// Unknown names are dropped and a piece only shows once; anything
+ /// unreadable, or an empty top line, falls back to [standard].
+ static NowPlayingLayout fromJson(String? raw) {
+ if (raw == null || raw.isEmpty) return standard;
+ try {
+ final map = jsonDecode(raw) as Map<String, dynamic>;
+ final seen = <NowPlayingPiece>{};
+ List<NowPlayingPiece> read(Object? names) => [
+ for (final name in (names as List?) ?? const [])
+ for (final piece in NowPlayingPiece.values)
+ if (piece.name == name && seen.add(piece)) piece,
+ ];
+ final top = read(map['top']);
+ final second = read(map['second']);
+ if (top.isEmpty) return standard;
+ return NowPlayingLayout(top: top, second: second);
+ } catch (_) {
+ return standard;
+ }
+ }
+
+ static bool _sameOrder(List<NowPlayingPiece> a, List<NowPlayingPiece> b) {
+ if (a.length != b.length) return false;
+ for (var i = 0; i < a.length; i++) {
+ if (a[i] != b[i]) return false;
+ }
+ return true;
+ }
+}
diff --git a/lib/services/player_settings.dart b/lib/services/player_settings.dart
index 58a346d4..e75318e4 100644
--- a/lib/services/player_settings.dart
+++ b/lib/services/player_settings.dart
@@ -833,6 +833,11 @@ class PlayerSettings {
static Future<bool> getNotificationChapterProgress() => _get('notificationChapterProgress', false);
static Future<void> setNotificationChapterProgress(bool value) => _set('notificationChapterProgress', value, notify: true);
+ // Which pieces the media controls show on each line, as
+ // NowPlayingLayout JSON. Empty = the standard layout.
+ static Future<String> getNowPlayingLayout() => _get('nowPlayingLayout', '');
+ static Future<void> setNowPlayingLayout(String json) => _set('nowPlayingLayout', json, notify: true);
+
// Android only: when true, the phone media controls show speed + bookmark in
// the two extra slots instead of chapter skip. Android Auto shows all of them
// either way; this just reorders which pair the phone "borrows".
diff --git a/lib/widgets/now_playing_text_sheet.dart b/lib/widgets/now_playing_text_sheet.dart
new file mode 100644
index 00000000..10c4c5db
--- /dev/null
+++ b/lib/widgets/now_playing_text_sheet.dart
@@ -0,0 +1,264 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+
+import '../l10n/app_localizations.dart';
+import '../services/audio_player_service.dart';
+import '../services/now_playing_layout.dart';
+import 'overlay_toast.dart';
+
+/// Settings > Media Controls > Now playing text: drag pieces onto the media
+/// controls' top and second line, or off them. Saves as it goes.
+class NowPlayingTextSheet extends StatefulWidget {
+ final ScrollController? scrollController;
+
+ const NowPlayingTextSheet({super.key, this.scrollController});
+
+ static void show(BuildContext context) {
+ showModalBottomSheet(
+ context: context,
+ isScrollControlled: true,
+ useSafeArea: true,
+ backgroundColor: Colors.transparent,
+ builder: (context) {
+ return GestureDetector(
+ onTap: () => Navigator.pop(context),
+ behavior: HitTestBehavior.opaque,
+ child: DraggableScrollableSheet(
+ initialChildSize: 0.75,
+ minChildSize: 0.4,
+ maxChildSize: 0.92,
+ builder: (context, scrollController) {
+ return GestureDetector(
+ onTap: () {},
+ child: Container(
+ decoration: BoxDecoration(
+ color: Theme.of(context).bottomSheetTheme.backgroundColor ??
+ Theme.of(context).colorScheme.surface,
+ borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
+ ),
+ child: NowPlayingTextSheet(scrollController: scrollController),
+ ),
+ );
+ },
+ ),
+ );
+ },
+ );
+ }
+
+ @override
+ State<NowPlayingTextSheet> createState() => _NowPlayingTextSheetState();
+}
+
+enum _Zone { top, second, unused }
+
+/// One row of the list: a zone header or a piece.
+class _Row {
+ final _Zone? header;
+ final NowPlayingPiece? piece;
+ const _Row.header(_Zone zone) : header = zone, piece = null;
+ const _Row.piece(NowPlayingPiece p) : header = null, piece = p;
+}
+
+class _NowPlayingTextSheetState extends State<NowPlayingTextSheet> {
+ NowPlayingLayout _layout = NowPlayingLayout.standard;
+ bool _loaded = false;
+
+ @override
+ void initState() {
+ super.initState();
+ PlayerSettings.getNowPlayingLayout().then((json) {
+ if (!mounted) return;
+ setState(() {
+ _layout = NowPlayingLayout.fromJson(json);
+ _loaded = true;
+ });
+ });
+ }
+
+ List<_Row> get _rows => [
+ const _Row.header(_Zone.top),
+ for (final p in _layout.top) _Row.piece(p),
+ const _Row.header(_Zone.second),
+ for (final p in _layout.second) _Row.piece(p),
+ const _Row.header(_Zone.unused),
+ for (final p in _layout.unused) _Row.piece(p),
+ ];
+
+ void _save(NowPlayingLayout layout) {
+ setState(() => _layout = layout);
+ PlayerSettings.setNowPlayingLayout(layout.isStandard ? '' : layout.toJson());
+ }
+
+ void _onReorder(int oldIndex, int newIndex) {
+ final rows = _rows;
+ if (rows[oldIndex].piece == null) return;
+ if (newIndex > oldIndex) newIndex--;
+ final moved = rows.removeAt(oldIndex);
+ // Nothing goes above the first header.
+ rows.insert(newIndex.clamp(1, rows.length), moved);
+
+ final top = <NowPlayingPiece>[];
+ final second = <NowPlayingPiece>[];
+ var zone = _Zone.top;
+ for (final row in rows) {
+ if (row.header != null) {
+ zone = row.header!;
+ } else if (zone == _Zone.top) {
+ top.add(row.piece!);
+ } else if (zone == _Zone.second) {
+ second.add(row.piece!);
+ }
+ }
+ if (top.isEmpty) {
+ showOverlayToast(context, AppLocalizations.of(context)!.nowPlayingTopLineRequired,
+ icon: Icons.info_outline_rounded);
+ return;
+ }
+ _save(NowPlayingLayout(top: top, second: second));
+ }
+
+ String _pieceName(AppLocalizations l, NowPlayingPiece piece) => switch (piece) {
+ NowPlayingPiece.chapter => l.nowPlayingPieceChapter,
+ NowPlayingPiece.title => l.nowPlayingPieceTitle,
+ NowPlayingPiece.author => l.author,
+ NowPlayingPiece.narrator => l.nowPlayingPieceNarrator,
+ NowPlayingPiece.series => l.nowPlayingPieceSeries,
+ NowPlayingPiece.percent => l.nowPlayingPiecePercent,
+ NowPlayingPiece.chapterNumber => l.nowPlayingPieceChapterNumber,
+ NowPlayingPiece.timeLeft => l.nowPlayingPieceTimeLeft,
+ };
+
+ IconData _pieceIcon(NowPlayingPiece piece) => switch (piece) {
+ NowPlayingPiece.chapter => Icons.bookmark_outline_rounded,
+ NowPlayingPiece.title => Icons.menu_book_rounded,
+ NowPlayingPiece.author => Icons.person_outline_rounded,
+ NowPlayingPiece.narrator => Icons.record_voice_over_outlined,
+ NowPlayingPiece.series => Icons.collections_bookmark_outlined,
+ NowPlayingPiece.percent => Icons.percent_rounded,
+ NowPlayingPiece.chapterNumber => Icons.format_list_numbered_rounded,
+ NowPlayingPiece.timeLeft => Icons.timelapse_rounded,
+ };
+
+ String _zoneName(AppLocalizations l, _Zone zone) => switch (zone) {
+ _Zone.top => l.nowPlayingTopLine,
+ _Zone.second => l.nowPlayingSecondLine,
+ _Zone.unused => l.nowPlayingNotShown,
+ };
+
+ /// The playing book in this layout, or the piece names with nothing playing.
+ ({String title, String subtitle}) _preview(AppLocalizations l) {
+ return AudioPlayerService().previewNowPlayingLines(_layout) ??
+ _layout.build(NowPlayingValues(
+ title: _pieceName(l, NowPlayingPiece.title),
+ author: _pieceName(l, NowPlayingPiece.author),
+ chapter: _pieceName(l, NowPlayingPiece.chapter),
+ narrator: _pieceName(l, NowPlayingPiece.narrator),
+ series: _pieceName(l, NowPlayingPiece.series),
+ percent: _pieceName(l, NowPlayingPiece.percent),
+ chapterNumber: _pieceName(l, NowPlayingPiece.chapterNumber),
+ timeLeft: _pieceName(l, NowPlayingPiece.timeLeft),
+ ));
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+ final l = AppLocalizations.of(context)!;
+ final rows = _rows;
+ final preview = _preview(l);
+
+ return Column(children: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(20, 16, 8, 4),
+ child: Row(children: [
+ Expanded(child: Text(l.nowPlayingText, style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w700))),
+ TextButton(
+ onPressed: !_loaded || _layout.isStandard ? null : () => _save(NowPlayingLayout.standard),
+ child: Text(l.resetToDefault),
+ ),
+ ]),
+ ),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 4, 16, 8),
+ child: Container(
+ padding: const EdgeInsets.all(12),
+ decoration: BoxDecoration(color: cs.surfaceContainerHigh, borderRadius: BorderRadius.circular(16)),
+ child: Row(children: [
+ Container(
+ width: 44,
+ height: 44,
+ decoration: BoxDecoration(color: cs.primary.withValues(alpha: 0.15), borderRadius: BorderRadius.circular(8)),
+ child: Icon(Icons.headphones_rounded, color: cs.primary, size: 22),
+ ),
+ const SizedBox(width: 12),
+ Expanded(
+ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Text(preview.title, maxLines: 1, overflow: TextOverflow.ellipsis,
+ style: tt.bodyMedium?.copyWith(fontWeight: FontWeight.w600)),
+ if (preview.subtitle.isNotEmpty)
+ Text(preview.subtitle, maxLines: 1, overflow: TextOverflow.ellipsis,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ ]),
+ ),
+ ]),
+ ),
+ ),
+ Expanded(
+ child: !_loaded
+ ? const SizedBox.shrink()
+ : ReorderableListView.builder(
+ scrollController: widget.scrollController,
+ buildDefaultDragHandles: false,
+ padding: const EdgeInsets.only(bottom: 24),
+ onReorderStart: (_) => HapticFeedback.mediumImpact(),
+ proxyDecorator: (child, index, animation) => Material(
+ elevation: 4,
+ borderRadius: BorderRadius.circular(12),
+ color: cs.surfaceContainer,
+ child: child,
+ ),
+ itemCount: rows.length,
+ onReorder: _onReorder,
+ itemBuilder: (context, i) {
+ final row = rows[i];
+ if (row.header != null) {
+ return Padding(
+ key: ValueKey('header-${row.header!.name}'),
+ padding: const EdgeInsets.fromLTRB(20, 14, 20, 6),
+ child: Text(_zoneName(l, row.header!),
+ style: tt.labelLarge?.copyWith(
+ color: cs.onSurfaceVariant.withValues(alpha: 0.7),
+ fontWeight: FontWeight.w600,
+ letterSpacing: 0.5)),
+ );
+ }
+ final piece = row.piece!;
+ final shown = _layout.uses(piece);
+ return Padding(
+ key: ValueKey(piece.name),
+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 2),
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
+ decoration: BoxDecoration(
+ color: shown ? cs.primary.withValues(alpha: 0.08) : Colors.transparent,
+ borderRadius: BorderRadius.circular(12),
+ ),
+ child: Row(children: [
+ Icon(_pieceIcon(piece), size: 20, color: cs.onSurface.withValues(alpha: 0.7)),
+ const SizedBox(width: 12),
+ Expanded(child: Text(_pieceName(l, piece), style: tt.bodyMedium)),
+ ReorderableDragStartListener(
+ index: i,
+ child: Icon(Icons.drag_handle_rounded, size: 20, color: cs.onSurface.withValues(alpha: 0.3)),
+ ),
+ ]),
+ ),
+ );
+ },
+ ),
+ ),
+ ]);
+ }
+}