Expand narrated story, preserve solved patterns, and add ambience

Connect the island story with new character memories and narrative transitions.
Blend each solved symbol into its artwork and retain a replayable pattern stamp.
Allow completed grids to be inspected after navigation and app restarts.
Reduce campaign difficulty spikes and keep explained story hints free.

Append 24 narrated continuations while preserving original PCM takes. Add
four offline environmental loops with saved mute/volume controls, scene
fades, narration ducking and lifecycle handling.

Validation: 31 unit/widget tests, Flutter analysis, narration and soundscape
asset checks, tablet discovery layouts and extended-audio integration,
including simultaneous active voice and ambience mixer tracks.
This commit is contained in:
Hadrian Burkhardt
2026-11-02 05:04:57 +01:00
parent 6bd14a9e20
commit 68871ec573
102 changed files with 2322 additions and 520 deletions
+12 -2
View File
@@ -14,13 +14,21 @@ assert {r['pageId'] for r in canonical}==set(manifest['tracks'])
for record in canonical:
if record['pageId'].startswith('campaign.'):
_,index,phase=record['pageId'].split('.')
assert record['text']==campaign[int(index)][phase], 'Campaign narration is stale'
level=campaign[int(index)]
expected='\n\n'.join(p for p in [level[phase],level.get(phase+'Continuation','')] if p)
assert record['text']==expected, 'Campaign narration is stale'
elif record.get('speaker')=='Narrator':
page=pages[record['pageId']]
expected=campaign[page['campaignIndex']][page['textSource']] if page.get('textSource') in ('before','after') else page['text']
if page.get('textSource') in ('before','after'):
level=campaign[page['campaignIndex']];phase=page['textSource']
expected='\n\n'.join(p for p in [level[phase],page.get('continuation',level.get(phase+'Continuation',''))] if p)
else:expected='\n\n'.join(p for p in [page['text'],page.get('continuation','')] if p)
assert record['text']==expected, 'Notebook narration is stale'
track=manifest['tracks'][record['pageId']]
assert track['text']==record['text']
if record.get('continuation'):
assert record['text']==record['baseText']+'\n\n'+record['continuation']
assert track['continuationSpeaker']=='Narrator'
assert track['textSha256']==hashlib.sha256(record['text'].encode()).hexdigest()
assert track['resource']==record['resource']
if record.get('speaker')=='Narrator':
@@ -39,6 +47,8 @@ for record in canonical:
assert reader.getnchannels()==1 and reader.getsampwidth()==2 and reader.getframerate()==24000
assert reader.getnframes()==track['frames']
master=reader.readframes(reader.getnframes())
if track.get('originalFrames'):
assert hashlib.sha256(master[:track['originalFrames']*2]).hexdigest()==track['originalPcmSha256'],'Original take was changed'
samples=array.array('h',master);peak=max(abs(v) for v in samples)
assert 1000<peak<32767,'Silent or clipped audio'
decoded=subprocess.check_output(['ffmpeg','-v','error','-i',str(flac),'-f','s16le','-acodec','pcm_s16le','-'])
+29
View File
@@ -0,0 +1,29 @@
#!/usr/bin/env python3
"""Check bundled soundscapes without synthesis dependencies."""
import array
import hashlib
import json
import math
import wave
from pathlib import Path
root = Path(__file__).resolve().parents[1]
audio = root / 'assets/audio'
manifest = json.loads((audio / 'ambience_manifest.json').read_text())
assert set(manifest['tracks']) == {'cottage', 'harbour', 'bridge', 'tower'}
pubspec = (root / 'pubspec.yaml').read_text()
for scene, track in manifest['tracks'].items():
path = audio / track['file']
assert 'assets/audio/' + path.name in pubspec
assert hashlib.sha256(path.read_bytes()).hexdigest() == track['wavSha256']
with wave.open(str(path), 'rb') as reader:
assert reader.getnchannels() == 1 and reader.getsampwidth() == 2
assert reader.getframerate() == track['sampleRate'] == 24000
assert reader.getnframes() == track['frames']
samples = array.array('h', reader.readframes(reader.getnframes()))
rms = math.sqrt(sum(v * v for v in samples) / len(samples)) / 32768
peak = max(abs(v) for v in samples) / 32768
assert .05 < rms < .15 and peak < .73, 'Silent or clipped soundscape'
assert abs(samples[-1] - samples[0]) <= 1, 'Discontinuous loop join'
assert track['durationMs'] == len(samples) * 1000 // 24000
print(f'PASS {scene}: bundled PCM, checksum, level and loop join verified')
+80
View File
@@ -0,0 +1,80 @@
#!/usr/bin/env python3
"""Render original, deterministic sound textures; no downloaded samples or runtime synthesis."""
import hashlib
import json
from pathlib import Path
import numpy as np
import soundfile as sf
ROOT = Path(__file__).resolve().parents[1]
RATE = 24000
SECONDS = 24
N = RATE * SECONDS
T = np.arange(N) / RATE
F = np.fft.rfftfreq(N, 1 / RATE)
OUT = ROOT / 'assets/audio'
def render(scene, seed):
rng = np.random.default_rng(seed)
def noise(low, high):
spectrum = np.fft.rfft(rng.normal(size=N))
spectrum *= (1 - np.exp(-(F / low) ** 4)) * np.exp(-(F / high) ** 2)
signal = np.fft.irfft(spectrum, n=N)
return signal / np.sqrt(np.mean(signal ** 2))
def swell(cycles, depth, phase):
return 1 + depth * np.sin(2 * np.pi * cycles * T / SECONDS + phase)
if scene == 'cottage':
# Air through trees beyond the shutter, with very soft timber movement.
signal = .65 * noise(100, 1250) * swell(2, .35, .3)
signal += .12 * noise(600, 3200) * swell(5, .4, 1.8)
for centre in [5.2, 14.1, 20.3]:
distance = (T - centre + SECONDS / 2) % SECONDS - SECONDS / 2
signal += .045 * np.sin(2 * np.pi * 270 * T) * np.exp(-(distance / .12) ** 2)
elif scene == 'harbour':
# Uneven small swells and a brighter wash as water meets the harbour wall.
signal = .8 * noise(70, 1700) * swell(7, .5, .5) * swell(3, .3, 1.3)
signal += .25 * noise(900, 4800) * swell(7, .6, 1.6)
elif scene == 'bridge':
# Continuous current under the stones, with irregular surface turbulence.
signal = .8 * noise(260, 6500) * swell(3, .18, .9) * swell(11, .15, 2.1)
signal += .4 * noise(80, 1800) * swell(5, .28, 1.8)
elif scene == 'tower':
# Sheltered low wind around the tower, with gentle gusts above it.
signal = .8 * noise(45, 700) * swell(2, .55, 1.2)
signal += .2 * noise(400, 2200) * swell(4, .65, .2)
else:
raise ValueError(scene)
signal -= np.mean(signal)
# Ease the last 50 ms onto the first sample, without a discontinuity at wrap.
ramp = np.linspace(0, 1, RATE // 20)
signal[-len(ramp):] -= (signal[-1] - signal[0]) * ramp * ramp * (3 - 2 * ramp)
signal *= .13 / np.sqrt(np.mean(signal ** 2))
signal *= min(1, .72 / np.max(np.abs(signal)))
return signal
if __name__ == '__main__':
tracks = {}
for scene, seed in [('cottage', 104), ('harbour', 205), ('bridge', 306), ('tower', 407)]:
path = OUT / f'ambience_{scene}.wav'
sf.write(path, render(scene, seed), RATE, subtype='PCM_16')
samples, rate = sf.read(path)
assert rate == RATE and len(samples) == N
assert .05 < np.sqrt(np.mean(samples ** 2)) < .15
assert np.max(np.abs(samples)) < .73
# A loop join must have no exceptional jump compared with normal samples.
assert abs(samples[-1] - samples[0]) <= 1 / 32768
tracks[scene] = {
'file': path.name, 'sampleRate': RATE, 'channels': 1,
'durationMs': SECONDS * 1000, 'frames': N, 'seed': seed,
'wavSha256': hashlib.sha256(path.read_bytes()).hexdigest(),
}
print(f'{scene}: {SECONDS}s loop, peak {np.max(np.abs(samples)):.3f}, RMS {np.sqrt(np.mean(samples ** 2)):.3f}')
(OUT / 'ambience_manifest.json').write_text(json.dumps({
'method': 'Original procedural sound textures rendered offline by scripts/render_ambience.py; no third-party samples.',
'tracks': tracks,
}, indent=2) + '\n')
+33 -7
View File
@@ -15,6 +15,7 @@ parser.add_argument('--voices',type=Path,required=True)
parser.add_argument('--voice',default='bf_emma')
parser.add_argument('--speed',type=float,default=.82)
parser.add_argument('--speaker', help='Render only this speaker, preserving all other recordings')
parser.add_argument('--append-continuations', action='store_true', help='Preserve existing takes and append the new narrator passages')
parser.add_argument('--root',type=Path,default=Path(__file__).resolve().parents[1])
a=parser.parse_args()
source=a.root/'assets/narration';raw=a.root/'assets/audio'
@@ -25,28 +26,48 @@ session.disable_fallback()
config=EspeakConfig(lib_path=str(espeakng_loader.get_library_path()),data_path=str(espeakng_loader.get_data_path()))
engine=Kokoro.from_session(session,str(a.voices),espeak_config=config)
previous=json.loads((source/'manifest.json').read_text()) if (source/'manifest.json').exists() else {}
tracks=dict(previous.get('tracks',{})) if a.speaker else {}
tracks=dict(previous.get('tracks',{})) if a.speaker or a.append_continuations else {}
for record in json.loads((source/'scripts.json').read_text()):
if a.speaker and record.get('speaker')!=a.speaker: continue
old=tracks.get(record['pageId'])
if a.append_continuations:
if old and old['text']==record['text']:
assert old['wavSha256']==hashlib.sha256((source/'wav'/old['file']).read_bytes()).hexdigest()
continue
assert old and old['text']==record['baseText'], f"Cannot append to stale take: {record['pageId']}"
paragraphs=[]
for part in record['text'].split('\n\n'):
text=record['continuation'] if a.append_continuations else record.get('baseText',record['text'])
for part in text.split('\n\n'):
if paragraphs and len(part)<45:paragraphs[-1]+='\n\n'+part
elif paragraphs and len(paragraphs[-1])<45:paragraphs[-1]+='\n\n'+part
else:paragraphs.append(part)
rate=24000;pieces=[np.zeros(int(rate*.18),dtype=np.float32)];frames=len(pieces[0]);cues=[]
for part in paragraphs:
print(f"Rendering {record['pageId']} · {len(cues)+1}/{len(paragraphs)}",flush=True)
samples,sample_rate=engine.create(part.replace('\n',' '),voice=record.get('voice',a.voice),speed=record.get('speed',a.speed),lang='en-gb',sentence_pause=.38,clause_pause=.14)
if a.append_continuations:
original,_=sf.read(source/'wav'/old['file'],dtype='int16')
master,master_rate=sf.read(source/'wav'/old['file'],dtype='float32')
assert master_rate==rate
pieces=[master,np.zeros(int(rate*.18),dtype=np.float32)];frames=sum(len(p) for p in pieces)
cues=[{**c,'speaker':c.get('speaker',record['speaker'])} for c in old['cues']]
sections=[(part,'Narrator' if a.append_continuations else record['speaker']) for part in paragraphs]
if not a.append_continuations and record.get('continuation'):
sections.extend((part,'Narrator') for part in record['continuation'].split('\n\n'))
for number,(part,speaker) in enumerate(sections,1):
print(f"Rendering {record['pageId']} · {number}/{len(sections)}",flush=True)
voice='bm_george' if speaker=='Narrator' else record.get('voice',a.voice)
speed=.88 if speaker=='Narrator' else record.get('speed',a.speed)
samples,sample_rate=engine.create(part.replace('\n',' '),voice=voice,speed=speed,lang='en-gb',sentence_pause=.38,clause_pause=.14)
assert sample_rate==rate
samples=np.asarray(samples,dtype=np.float32).reshape(-1)
assert len(samples)>rate*.3 and np.isfinite(samples).all()
fade=min(240,len(samples)//4)
samples[:fade]*=np.linspace(0,1,fade);samples[-fade:]*=np.linspace(1,0,fade)
peak=float(np.max(np.abs(samples)));assert peak>.01
samples*=.86/peak
start=frames;pieces.append(samples);frames+=len(samples)
cues.append({'startMs':round(start*1000/rate),'endMs':round(frames*1000/rate),'text':part})
cues.append({'startMs':round(start*1000/rate),'endMs':round(frames*1000/rate),'text':part,'speaker':speaker})
pause=np.zeros(int(rate*.60),dtype=np.float32);pieces.append(pause);frames+=len(pause)
audio=np.concatenate(pieces);peak=float(np.max(np.abs(audio)));assert peak>.01
audio*=.86/peak
assert peak<1
wav=source/'wav'/f"{record['resource']}.wav";flac=raw/f"{record['resource']}.flac"
sf.write(wav,audio,rate,subtype='PCM_16')
shutil.copyfile(wav,raw/wav.name)
@@ -56,6 +77,11 @@ for record in json.loads((source/'scripts.json').read_text()):
tracks[record['pageId']]={**record,'file':wav.name,'flacFile':flac.name,'wavSha256':hashlib.sha256(wav.read_bytes()).hexdigest(),'sampleRate':rate,'channels':1,'frames':len(audio),
'durationMs':round(len(audio)*1000/rate),'textSha256':hashlib.sha256(record['text'].encode()).hexdigest(),
'flacSha256':hashlib.sha256(flac.read_bytes()).hexdigest(),'cues':cues}
if a.append_continuations:
output,_=sf.read(wav,dtype='int16')
assert np.array_equal(output[:len(original)],original),'Original take changed while appending'
tracks[record['pageId']]['originalFrames']=len(original)
tracks[record['pageId']]['originalPcmSha256']=hashlib.sha256(original.tobytes()).hexdigest()
print(f"Saved {wav.name}: {len(audio)/rate:.1f}s; lossless FLAC verified",flush=True)
manifest={'voice':a.voice,'speed':a.speed,'language':'en-gb','method':'Synthetic narration rendered during development; bundled file playback only.',
'speakers':{'Mara':{'voice':'bf_emma','speed':.82},'Narrator':{'voice':'bm_george','speed':.88}},