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 load(Soundscape scene); Future volume(double value); Future play(); Future stop(); Future 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 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 volume(double value) => _player.setVolume(value); @override Future play() => _player.play(); @override Future stop() => _player.stop(); @override Future 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 _pending = Future.value(); int _revision = 0; bool _disposed = false; Soundscape? _desired, _loaded; double _target = 0, _volume = 0; String error = ''; Future 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 _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.delayed(const Duration(milliseconds: 30)); } } Future _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(); } }