Files
logic-puzzle/lib/services/narrator.dart
T
Hadrian Burkhardt 7e6b203a02 Add browser playtest and improve library, media and input
Bundle web bootstrap, icons, local font fallbacks and hosting instructions.
Add optimized WebP/MP3 packaging, asset checks and a browser narration
regression tool. Support browser audio handoff and ad-free explained hints.

Refresh the responsive bookshelf and reduce unnecessary app, narration and
paper repaint work. Preserve deliberate page swipes while tolerating small
mouse movements during cell and navigation clicks.

Validation: all 77 Flutter tests pass; shell, JavaScript and Python scripts
parse; locale and web manifests are valid JSON; git diff --check passes.
2026-11-06 03:33:26 +01:00

213 lines
6.5 KiB
Dart

import 'browser_assets.dart';
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:just_audio/just_audio.dart';
import 'package:audio_session/audio_session.dart';
class Narrator extends ChangeNotifier {
Narrator(this.tracks) {
_subscriptions.add(
_player.playerStateStream.listen((_) => notifyListeners()),
);
_subscriptions.add(
_player.positionStream.listen((position) {
final state = (position.inSeconds, passage, speaker);
if (state == _positionState) return;
_positionState = state;
notifyListeners();
}),
);
}
(int, String, String)? _positionState;
final ValueNotifier<String> highlightedPassage = ValueNotifier('');
@override
void notifyListeners() {
highlightedPassage.value = passage;
super.notifyListeners();
}
Map<String, dynamic> tracks;
void replaceTracks(Map<String, dynamic> value) {
unawaited(stop());
tracks = value;
}
final _player = AudioPlayer();
final List<StreamSubscription<dynamic>> _subscriptions = [];
String page = '', error = '';
bool loading = false;
Timer? _autoplay;
bool get autoplayPending => _autoplay?.isActive ?? false;
int _generation = 0;
bool get playing =>
_player.playing && _player.processingState != ProcessingState.completed;
bool get finished => _player.processingState == ProcessingState.completed;
bool get paused => page.isNotEmpty && !playing && !finished && !loading;
Duration get position => _player.position;
String get label => error.isNotEmpty
? 'Play this reading'
: loading
? 'Opening recording…'
: playing
? 'Pause recording'
: finished
? 'Replay recording'
: paused
? 'Resume recording'
: 'Play this reading';
String _time(Duration d) =>
'${d.inMinutes}:${(d.inSeconds % 60).toString().padLeft(2, '0')}';
String get status => error.isNotEmpty
? error
: page.isEmpty
? autoplayPending
? 'The reading starts automatically in 3 seconds'
: 'A recorded reading, kept with this page'
: finished
? 'End of the reading · listen again whenever you like'
: '${playing ? 'Playing' : 'Paused'} · ${_time(position)} / ${_time(_player.duration ?? Duration.zero)}';
String get passage {
if (page.isEmpty || finished) return '';
for (final cue in tracks[page]?['cues'] ?? []) {
if (position.inMilliseconds >= cue['startMs'] &&
position.inMilliseconds < cue['endMs']) {
return cue['text'];
}
}
return '';
}
String get speaker {
var current = tracks[page]?['speaker'] as String? ?? '';
for (final cue in tracks[page]?['cues'] ?? []) {
if (position.inMilliseconds < cue['startMs']) break;
current = cue['speaker'] as String? ?? current;
}
// Hold the role through its pause, instead of flashing back to Narrator.
return current;
}
void scheduleAutoplay(String? id, double speed) {
cancelAutoplay();
if (id == null || !tracks.containsKey(id)) return;
_autoplay = Timer(const Duration(seconds: 3), () {
_autoplay = null;
notifyListeners();
if (!playing && !loading) unawaited(toggle(id, speed));
});
notifyListeners();
}
void cancelAutoplay() {
if (_autoplay == null) return;
_autoplay!.cancel();
_autoplay = null;
notifyListeners();
}
Future<void> toggle(String id, double speed) async {
cancelAutoplay();
if (loading) return;
if (playing && page == id) {
await _player.pause();
return;
}
final generation = ++_generation;
error = '';
try {
if (page != id) {
loading = true;
error = '';
notifyListeners();
if (!kIsWeb) {
final session = await AudioSession.instance;
await session.configure(const AudioSessionConfiguration.speech());
}
if (generation != _generation) return;
page = id;
final asset =
tracks[id]['asset'] as String? ??
'assets/audio/${tracks[id]['file']}';
if (kIsWeb) {
final url = browserAudioUrl(asset);
if (_player.audioSources.isEmpty) {
await _player.setUrl(url, initialPosition: Duration.zero);
} else {
// The web backend caches the root playlist by ID. Reusing setUrl
// on an active player can replay its cached first child. Mutate
// the playlist through its API so the browser receives the new
// source, while retaining the already-authorized media element.
await _player.pause();
await _player.clearAudioSources();
if (generation != _generation) return;
await _player.addAudioSource(AudioSource.uri(Uri.parse(url)));
if (generation != _generation) return;
await _player.seek(Duration.zero, index: 0);
}
} else {
// PCM WAV remains the tested format for the Android tablet.
await _player.setAsset(asset);
}
if (generation != _generation) return;
} else if (finished) {
await _player.seek(Duration.zero);
}
await _player.setSpeed(speed);
if (generation != _generation) return;
loading = false;
notifyListeners();
unawaited(
_player.play().catchError((Object e) {
if (generation != _generation) return;
unawaited(_player.pause());
error = kIsWeb ? 'Tap Play again to allow audio in your browser.' : 'This recording could not be played. You can still read the entry.';
notifyListeners();
}),
);
} catch (e) {
if (generation == _generation) {
error =
'This recording could not be played. You can still read the entry.';
loading = false;
page = '';
notifyListeners();
}
}
}
Future<void> pause() async {
cancelAutoplay();
await _player.pause();
}
Future<void> stop() async {
cancelAutoplay();
++_generation;
page = '';
loading = false;
error = '';
notifyListeners();
if (kIsWeb) {
// Retain the browser media element and its audio permission between pages.
// stop() tears down the web decoder, making the next page start cold.
await _player.pause();
await _player.seek(Duration.zero);
} else {
await _player.stop();
}
}
@override
void dispose() {
_autoplay?.cancel();
for (final s in _subscriptions) {
unawaited(s.cancel());
}
unawaited(_player.dispose());
highlightedPassage.dispose();
super.dispose();
}
}