Files
logic-puzzle/lib/services/ambience.dart
T
Hadrian Burkhardt 0718e3f252 Open Lumen on a responsive bookshelf and land pending story work
- Start the app on a shelf of every installed book instead of the last
  book's home. Cards show the cover, translated metadata, available
  languages, restored patterns and either "Continue reading" or a way in.
- Keep each book's saved route: the shelf is never written to
  flutter_screen, so choosing a book resumes its own leaf.
- Lay the shelf out responsively: dense single-column cards on phones,
  a two-column grid from 720 logical pixels, a centred 860 px column on
  tablets and a chevron that exists in the bundled handwriting font.
- Keep Settings reachable from the shelf and let the home page's story
  library button open the shelf instead of a dialog.
- Add tool/shelf_screenshots_test.dart, which renders the shelf at phone
  and tablet metrics, checks that every card and Settings stay reachable
  without overflow, and writes artifacts/library/shelf-*.png.
- Commit the pending Midnight Invitation package (campaign, notebook,
  narration and artwork), cast drama and ambience tooling, region
  selection, phone/tablet integration coverage and related docs.

flutter analyze is clean and all 74 widget/domain tests pass.
2026-11-05 14:29:50 +01:00

147 lines
4.3 KiB
Dart

import 'dart:async';
import 'package:audio_session/audio_session.dart';
import 'package:flutter/foundation.dart';
import 'package:just_audio/just_audio.dart';
import '../domain/soundscape.dart';
export '../domain/soundscape.dart';
Soundscape soundscapeFor(int campaignIndex) => switch (campaignIndex) {
4 || 5 || 7 => Soundscape.harbour,
6 => Soundscape.bridge,
8 || 9 || 10 => Soundscape.tower,
_ => Soundscape.cottage,
};
/// Small output boundary lets tests exercise races and fades without a device.
abstract interface class AmbienceOutput {
Future<void> load(Soundscape scene);
Future<void> volume(double value);
Future<void> play();
Future<void> stop();
Future<void> dispose();
}
class _AudioOutput implements AmbienceOutput {
// One shared speech session; this layer must not steal focus from the voice.
final _player = AudioPlayer(handleAudioSessionActivation: false);
@override
Future<void> load(Soundscape scene) async {
final session = await AudioSession.instance;
await session.configure(const AudioSessionConfiguration.speech());
if (!await session.setActive(true)) {
throw StateError('Audio focus unavailable');
}
await _player.setLoopMode(LoopMode.one);
await _player.setAsset(scene.asset);
}
@override
Future<void> volume(double value) => _player.setVolume(value);
@override
Future<void> play() => _player.play();
@override
Future<void> stop() => _player.stop();
@override
Future<void> dispose() => _player.dispose();
}
/// Serialises scene changes, fading out old audio before loading the next loop.
/// The newest request wins, including mute/background requests during loading.
class Ambience extends ChangeNotifier {
Ambience({AmbienceOutput? output}) : _output = output ?? _AudioOutput();
final AmbienceOutput _output;
Future<void> _pending = Future.value();
int _revision = 0;
bool _disposed = false;
Soundscape? _desired, _loaded;
double _target = 0, _volume = 0;
String error = '';
Future<void> get settled => _pending;
void update({
required Soundscape? scene,
required bool enabled,
required bool foreground,
required bool narrating,
required double volume,
}) {
if (_disposed) return;
final desired = enabled && foreground ? scene : null;
final target = desired == null
? 0.0
: .4 * volume.clamp(0.0, 1.0) * (narrating ? .25 : 1);
if (_desired == desired && _target == target) return;
_desired = desired;
_target = target;
final revision = ++_revision;
_pending = _pending.then((_) => _apply(revision));
}
bool _current(int revision) => !_disposed && revision == _revision;
Future<void> _fade(double target, int revision) async {
final start = _volume;
for (var i = 1; i <= 8 && _current(revision); i++) {
_volume = start + (target - start) * i / 8;
await _output.volume(_volume);
await Future<void>.delayed(const Duration(milliseconds: 30));
}
}
Future<void> _apply(int revision) async {
if (!_current(revision)) return;
try {
final scene = _desired;
if (scene != _loaded || scene == null) {
// Muting/backgrounding stops immediately; scene changes fade gently.
if (scene != null && _loaded != null) await _fade(0, revision);
if (!_current(revision)) return;
await _output.stop();
_loaded = null;
_volume = 0;
await _output.volume(0);
if (scene == null || !_current(revision)) return;
await _output.load(scene);
if (!_current(revision)) return;
error = '';
_loaded = scene;
unawaited(
_output.play().catchError((Object _) {
if (_current(revision)) _failed();
}),
);
}
await _fade(_target, revision);
} catch (_) {
if (!_disposed) {
try {
await _output.stop();
} catch (_) {
// A missing or unavailable audio backend must not break the book.
}
_loaded = null;
_failed();
}
}
}
void _failed() {
if (_disposed) return;
error =
'The atmosphere could not be played. Your reading is still available.';
notifyListeners();
}
@override
void dispose() {
_disposed = true;
++_revision;
unawaited(_pending.whenComplete(_output.dispose));
super.dispose();
}
}