Compare commits

...
9 Commits
Author SHA1 Message Date
Gitea Actions b3a0e0ca5a Release 0.1.30 [auto-version-bump] 2026-10-15 10:25:53 +02:00
Ein Anderssono de915b4aa6 Migrate players to automatic voice replies
Build and publish frontend / publish (push) Successful in 38s
2026-10-15 10:25:35 +02:00
Gitea Actions 421b14c398 Release 0.1.29 [auto-version-bump] 2026-10-15 10:21:53 +02:00
Ein Anderssono 9efb602653 Keep screen reader voice mode test explicit
Build and publish frontend / publish (push) Successful in 38s
2026-10-15 10:21:29 +02:00
Ein Anderssono 222dcb9054 Enable automatic speech for game replies
Build and publish frontend / publish (push) Failing after 3s
2026-10-15 10:21:00 +02:00
Gitea Actions 0876538e58 Release 0.1.28 [auto-version-bump] 2026-10-15 10:06:31 +02:00
Ein Anderssono f2a2a3b30a Speak dialogue with persistent character voices
Build and publish frontend / publish (push) Successful in 50s
2026-10-15 10:06:04 +02:00
Gitea Actions c9e31d23ba Release 0.1.27 [auto-version-bump] 2026-10-15 09:57:23 +02:00
Ein Anderssono 1f9fc464d4 Disclose browser speech processing before microphone use
Build and publish frontend / publish (push) Successful in 43s
2026-10-15 09:56:46 +02:00
7 changed files with 124 additions and 31 deletions
+3 -1
View File
@@ -10,7 +10,9 @@ The separate `/admin` route provides an authenticated, read-only operations view
The game is text- and dialogue-based and uses no images. Place descriptions include sound, smell, air/temperature, touch/surface, and spatial-orientation cues. Visible details may also be described in words, but are never required to understand the scene or play. The transcript is screen-reader announced, and Enter submits the input while Shift+Enter inserts a newline; no separate send button is required. The game is text- and dialogue-based and uses no images. Place descriptions include sound, smell, air/temperature, touch/surface, and spatial-orientation cues. Visible details may also be described in words, but are never required to understand the scene or play. The transcript is screen-reader announced, and Enter submits the input while Shift+Enter inserts a newline; no separate send button is required.
Voice input and output are optional browser features. The microphone button beside the text field uses Web Speech API when available and sends only its final Swedish transcript through the same submission path as typed text. Writing `röstinställningar` or saying `röstkommando alternativ` opens the temporary controls in the dialogue. The player can choose `Spelets röst`, `Skärmläsare`, or `Endast text`, select available Swedish speech voices and rate, and enable auto-read and short audio cues. The default mode is `Skärmläsare`; auto-read is off. These preferences are stored in browser `localStorage`. If speech APIs are unavailable or permission is denied, text play remains available. No audio is uploaded or stored by this feature. Voice input and output are browser features. Every new game reply is read automatically with the browser's Swedish speech synthesis by default, including character creation and gameplay; the transcript remains available as text. The microphone button beside the text field uses Web Speech API when available and sends only its final Swedish transcript through the same submission path as typed text. Before its first use, the client explains that the browser may process audio through a provider-selected service; the game itself does not receive or store recordings, while the final transcript is saved as ordinary dialogue. Writing `röstinställningar` or saying `röstkommando alternativ` opens the temporary controls in the dialogue. The player can choose `Spelets röst`, `Skärmläsare`, or `Endast text`, select available Swedish speech voices and rate, and enable or disable auto-read and short audio cues. The default mode is `Spelets röst` with auto-read on. Screen-reader and text-only modes remain explicit alternatives. These preferences are stored in browser `localStorage`. If speech APIs are unavailable, text play remains available.
When a character or NPC is created, its saved voice identity is masculine, feminine, or neutral. The biography prompt only assigns masculine/feminine when the character is explicitly described that way; otherwise it uses neutral. Speech synthesis applies a stable, subtly varied pitch/rate profile per character, so a character keeps the same sound across visits. Narration always uses neutral pitch. The browser's selected Swedish voice still determines the underlying voice, so the exact sound depends on installed system voices.
System voice commands require the prefix `röstkommando`: `upprepa`, `avbryt`, `hjälp`, `alternativ`, or `paus`. Without the prefix, the same words remain ordinary dialogue. Speech recognition and synthesis are browser-dependent; release acceptance must record which real iPhone/Safari/VoiceOver and Android/Chrome/TalkBack combinations were actually checked. System voice commands require the prefix `röstkommando`: `upprepa`, `avbryt`, `hjälp`, `alternativ`, or `paus`. Without the prefix, the same words remain ordinary dialogue. Speech recognition and synthesis are browser-dependent; release acceptance must record which real iPhone/Safari/VoiceOver and Android/Chrome/TalkBack combinations were actually checked.
+1 -1
View File
@@ -1 +1 @@
0.1.26 0.1.30
+2 -2
View File
@@ -2,5 +2,5 @@ apiVersion: v2
name: ai-spel-frontend name: ai-spel-frontend
description: Static web frontend for the Swedish life simulator description: Static web frontend for the Swedish life simulator
type: application type: application
version: 0.1.26 version: 0.1.30
appVersion: "0.1.26" appVersion: "0.1.30"
+31 -7
View File
@@ -84,10 +84,12 @@
let submitBusy = false; let submitBusy = false;
let pendingDialogue = null; let pendingDialogue = null;
let latestAssistantText = ''; let latestAssistantText = '';
const voiceSettingsKey = 'ai-spel.voice-settings.v1'; let latestAssistantVoice = {role: 'narrator', voiceIdentity: 'neutral'};
let voiceSettings = window.GameVoice.loadSettings(localStorage, voiceSettingsKey); const voiceSettingsKey = 'ai-spel.voice-settings.v2';
let voiceSettings = window.GameVoice.loadSettings(localStorage, voiceSettingsKey, 'ai-spel.voice-settings.v1');
let voiceController; let voiceController;
let audioContext; let audioContext;
let voiceDisclosureAcknowledged = false;
let adminOffset = 0; let adminOffset = 0;
const adminPageSize = 50; const adminPageSize = 50;
@@ -105,9 +107,10 @@
line.scrollIntoView({block: 'end'}); line.scrollIntoView({block: 'end'});
if (role === 'assistant') { if (role === 'assistant') {
latestAssistantText = content; latestAssistantText = content;
latestAssistantVoice = options.voice || {role: 'narrator', voiceIdentity: 'neutral'};
if (options.speak !== false && !content.trim().endsWith('…') && !content.trim().endsWith('...') if (options.speak !== false && !content.trim().endsWith('…') && !content.trim().endsWith('...')
&& voiceSettings.mode === 'game-voice' && voiceSettings.autoSpeak && !play.hidden) { && voiceSettings.mode === 'game-voice' && voiceSettings.autoSpeak && !play.hidden) {
voiceController?.speak(content, options.voice || {}); voiceController?.speak(content, latestAssistantVoice);
} }
} }
return line; return line;
@@ -198,7 +201,7 @@
signalLabel.append(signals, document.createTextNode(' Ljudsignal vid röstinmatning')); fieldset.append(signalLabel); signalLabel.append(signals, document.createTextNode(' Ljudsignal vid röstinmatning')); fieldset.append(signalLabel);
item.append(fieldset); item.append(fieldset);
const speakLatest = () => { const speakLatest = () => {
if (!voiceController.speak(latestAssistantText)) setVoiceStatus('Talsyntes stöds inte här eller är avstängd. Dialogen finns kvar som text.'); if (!voiceController.speak(latestAssistantText, latestAssistantVoice)) setVoiceStatus('Talsyntes stöds inte här eller är avstängd. Dialogen finns kvar som text.');
}; };
addVoiceButton(item, 'Läs senaste repliken', speakLatest); addVoiceButton(item, 'Läs senaste repliken', speakLatest);
addVoiceButton(item, 'Upprepa', speakLatest); addVoiceButton(item, 'Upprepa', speakLatest);
@@ -211,12 +214,26 @@
addVoiceButton(item, 'Stäng röstinställningar', () => item.remove()); addVoiceButton(item, 'Stäng röstinställningar', () => item.remove());
transcript.append(item); item.scrollIntoView({block: 'end'}); mode.focus(); transcript.append(item); item.scrollIntoView({block: 'end'}); mode.focus();
} }
function requestVoiceDisclosure() {
const item = document.createElement('li'); item.dataset.role = 'voice-controls';
item.setAttribute('aria-label', 'Information om mikrofonen');
const message = document.createElement('p');
message.textContent = 'Innan du startar: webbläsarens taligenkänning kan behandla ljud genom en tjänst som webbläsaren väljer. Spelet tar inte emot eller sparar ljudinspelningen. Den färdiga transkriberingen skickas och sparas som din vanliga dialog. Fortsätt bara om du godkänner webbläsarens hantering av tal.';
item.append(message);
addVoiceButton(item, 'Jag förstår – starta mikrofonen', () => {
voiceDisclosureAcknowledged = true;
item.remove();
voiceController.startListening();
});
transcript.append(item); item.scrollIntoView({block: 'end'});
item.querySelector('button').focus();
}
function handleVoiceCommand(message, source) { function handleVoiceCommand(message, source) {
const parsed = window.GameVoice.parseVoiceCommand(message, {requirePrefix: source === 'voice'}); const parsed = window.GameVoice.parseVoiceCommand(message, {requirePrefix: source === 'voice'});
if (!parsed) return false; if (!parsed) return false;
if (parsed.command === 'settings') appendVoiceSettings(); if (parsed.command === 'settings') appendVoiceSettings();
else if (parsed.command === 'repeat') { else if (parsed.command === 'repeat') {
if (!voiceController.speak(latestAssistantText)) setVoiceStatus('Talsyntes stöds inte här eller är avstängd. Dialogen finns kvar som text.'); if (!voiceController.speak(latestAssistantText, latestAssistantVoice)) setVoiceStatus('Talsyntes stöds inte här eller är avstängd. Dialogen finns kvar som text.');
} else if (parsed.command === 'stop') { } else if (parsed.command === 'stop') {
voiceController.cancelSpeech(); voiceController.stopListening(); setVoiceStatus('Röstinteraktionen är avbruten.'); voiceController.cancelSpeech(); voiceController.stopListening(); setVoiceStatus('Röstinteraktionen är avbruten.');
} else if (parsed.command === 'help') { } else if (parsed.command === 'help') {
@@ -226,6 +243,7 @@
} }
document.querySelector('#microphone').addEventListener('click', () => { document.querySelector('#microphone').addEventListener('click', () => {
if (voiceController.getState() === 'LISTENING') voiceController.stopListening(); if (voiceController.getState() === 'LISTENING') voiceController.stopListening();
else if (!voiceDisclosureAcknowledged && voiceController.supportsRecognition()) requestVoiceDisclosure();
else voiceController.startListening(); else voiceController.startListening();
}); });
document.addEventListener('visibilitychange', () => { if (document.hidden) voiceController.stopAll(); }); document.addEventListener('visibilitychange', () => { if (document.hidden) voiceController.stopAll(); });
@@ -516,10 +534,16 @@
gameState.world.version = result.world_version; gameState.world.version = result.world_version;
gameState.world.world_time = result.world_time; gameState.world.world_time = result.world_time;
pendingDialogue = null; pendingDialogue = null;
if (result.intent === 'move') {
try {
const refreshed = await request('/api/world');
if (refreshed.world) gameState = refreshed;
} catch (_) { /* The committed dialogue stays successful if this optional view refresh fails. */ }
}
const speakingNpc = result.intent === 'speak' ? gameState.world.npc : null; const speakingNpc = result.intent === 'speak' ? gameState.world.npc : null;
appendLine('assistant', result.reply, speakingNpc appendLine('assistant', result.reply, speakingNpc
? {speaker: speakingNpc.name, voice: {characterId: speakingNpc.id}} ? {speaker: speakingNpc.name, voice: {characterId: speakingNpc.id, voiceIdentity: speakingNpc.voice_identity}}
: {speaker: 'Berättelsen'}); : {speaker: 'Berättelsen', voice: {role: 'narrator', voiceIdentity: 'neutral'}});
} catch (error) { } catch (error) {
messageField.value = message; messageField.value = message;
appendLine('assistant', `Meddelandet kunde inte behandlas: ${error.message}. Texten ligger kvar i inmatningen; skicka igen för att försöka på nytt.`); appendLine('assistant', `Meddelandet kunde inte behandlas: ${error.message}. Texten ligger kvar i inmatningen; skicka igen för att försöka på nytt.`);
+5
View File
@@ -11,6 +11,11 @@ grep -q 'id="message" name="message"' index.html
grep -q 'id="microphone" aria-pressed="false"' index.html grep -q 'id="microphone" aria-pressed="false"' index.html
grep -q 'id="voice-status" role="status" aria-live="polite"' index.html grep -q 'id="voice-status" role="status" aria-live="polite"' index.html
grep -q "window.GameVoice.createVoiceController" index.html grep -q "window.GameVoice.createVoiceController" index.html
grep -q 'Jag förstår – starta mikrofonen' index.html
grep -q 'supportsRecognition' voice.js
grep -q 'characterVoiceProfile' voice.js
grep -q "voiceIdentity: speakingNpc.voice_identity" index.html
grep -q "role: 'narrator', voiceIdentity: 'neutral'" index.html
grep -q 'COPY voice.js /usr/share/nginx/html/voice.js' Dockerfile grep -q 'COPY voice.js /usr/share/nginx/html/voice.js' Dockerfile
grep -q "SpeechRecognition || win.webkitSpeechRecognition" voice.js grep -q "SpeechRecognition || win.webkitSpeechRecognition" voice.js
grep -q "submitMessage(text, 'voice')" index.html grep -q "submitMessage(text, 'voice')" index.html
+47 -12
View File
@@ -5,6 +5,9 @@ const test = require('node:test');
const vm = require('node:vm'); const vm = require('node:vm');
const source = fs.readFileSync(path.join(__dirname, '..', 'voice.js'), 'utf8'); const source = fs.readFileSync(path.join(__dirname, '..', 'voice.js'), 'utf8');
const apiWindow = {};
vm.runInNewContext(source, {window: apiWindow, globalThis: apiWindow, Promise, String, Math, Object});
const GameVoice = apiWindow.GameVoice;
function makeHarness({supported = true, tts = true, onTranscript = () => Promise.resolve()} = {}) { function makeHarness({supported = true, tts = true, onTranscript = () => Promise.resolve()} = {}) {
const recognitions = []; const recognitions = [];
@@ -119,6 +122,26 @@ test('TTS selects Swedish fallback, applies rate, and cancellation invalidates c
assert.equal(h.controller.getState(), 'IDLE'); assert.equal(h.controller.getState(), 'IDLE');
}); });
test('character voice identity gives stable distinct masculine, feminine, and neutral timbres', () => {
const profile = GameVoice.characterVoiceProfile;
const masculine = profile('masculine', 'character-1');
const feminine = profile('feminine', 'character-1');
const neutral = profile('neutral', 'character-1');
assert.equal(profile('masculine', 'character-1').pitch, masculine.pitch);
assert.ok(masculine.pitch < neutral.pitch);
assert.ok(neutral.pitch < feminine.pitch);
assert.notEqual(profile('masculine', 'character-2').pitch, masculine.pitch);
});
test('narrator uses neutral pitch while character replies use their saved voice identity', () => {
const h = makeHarness();
h.controller.update({mode: 'game-voice'});
h.controller.speak('Berättarröst', {role: 'narrator', voiceIdentity: 'feminine', characterId: 'narrator'});
h.controller.speak('NPC-replik', {voiceIdentity: 'masculine', characterId: 'npc-1'});
assert.equal(h.utterances[0].pitch, 1);
assert.ok(h.utterances[1].pitch < 1);
});
test('TTS and microphone are mutually exclusive', () => { test('TTS and microphone are mutually exclusive', () => {
const h = makeHarness(); const h = makeHarness();
h.controller.update({mode: 'game-voice'}); h.controller.update({mode: 'game-voice'});
@@ -130,6 +153,7 @@ test('TTS and microphone are mutually exclusive', () => {
test('speech is disabled in screen-reader mode and gracefully degrades without synthesis', () => { test('speech is disabled in screen-reader mode and gracefully degrades without synthesis', () => {
const screenReader = makeHarness(); const screenReader = makeHarness();
screenReader.controller.update({mode: 'screen-reader'});
assert.equal(screenReader.controller.speak('dialog'), false); assert.equal(screenReader.controller.speak('dialog'), false);
const noTts = makeHarness({tts: false}); const noTts = makeHarness({tts: false});
noTts.controller.update({mode: 'game-voice'}); noTts.controller.update({mode: 'game-voice'});
@@ -139,13 +163,13 @@ test('speech is disabled in screen-reader mode and gracefully degrades without s
test('system commands require an explicit prefix; ordinary dialogue words are untouched', () => { test('system commands require an explicit prefix; ordinary dialogue words are untouched', () => {
const global = {}; const global = {};
vm.runInNewContext(source, {window: global, globalThis: global, Promise, String, Math, Object}); vm.runInNewContext(source, {window: global, globalThis: global, Promise, String, Math, Object});
assert.equal(global.GameVoice.parseVoiceCommand('upprepa'), null); assert.equal(GameVoice.parseVoiceCommand('upprepa'), null);
assert.equal(global.GameVoice.parseVoiceCommand('hjälp'), null); assert.equal(GameVoice.parseVoiceCommand('hjälp'), null);
assert.equal(global.GameVoice.parseVoiceCommand('röstkommando upprepa.' ).command, 'repeat'); assert.equal(GameVoice.parseVoiceCommand('röstkommando upprepa.' ).command, 'repeat');
assert.equal(global.GameVoice.parseVoiceCommand('röstkommando alternativ').command, 'settings'); assert.equal(GameVoice.parseVoiceCommand('röstkommando alternativ').command, 'settings');
assert.equal(global.GameVoice.parseVoiceCommand('röstinställningar').command, 'settings'); assert.equal(GameVoice.parseVoiceCommand('röstinställningar').command, 'settings');
assert.equal(global.GameVoice.parseVoiceCommand('röstinställningar', {requirePrefix: true}), null); assert.equal(GameVoice.parseVoiceCommand('röstinställningar', {requirePrefix: true}), null);
assert.equal(global.GameVoice.parseVoiceCommand('röstkommando alternativ', {requirePrefix: true}).command, 'settings'); assert.equal(GameVoice.parseVoiceCommand('röstkommando alternativ', {requirePrefix: true}).command, 'settings');
}); });
test('settings survive reload and invalid storage falls back to accessible defaults', () => { test('settings survive reload and invalid storage falls back to accessible defaults', () => {
@@ -153,14 +177,25 @@ test('settings survive reload and invalid storage falls back to accessible defau
vm.runInNewContext(source, {window: global, globalThis: global, Promise, String, Math, Object}); vm.runInNewContext(source, {window: global, globalThis: global, Promise, String, Math, Object});
const values = new Map(); const values = new Map();
const storage = {getItem: key => values.get(key) || null, setItem: (key, value) => values.set(key, value)}; const storage = {getItem: key => values.get(key) || null, setItem: (key, value) => values.set(key, value)};
const requested = {...global.GameVoice.DEFAULT_SETTINGS, mode: 'game-voice', autoSpeak: true, rate: 1.5, voiceName: 'Svensk'}; const defaults = GameVoice.loadSettings(storage, 'new-player');
assert.equal(global.GameVoice.saveSettings(storage, 'voice', requested), true); assert.equal(defaults.mode, 'game-voice');
const loaded = global.GameVoice.loadSettings(storage, 'voice'); assert.equal(defaults.autoSpeak, true);
values.set('voice-v1', JSON.stringify({mode: 'screen-reader', autoSpeak: false, rate: 1.4, voiceName: 'Svensk', soundSignals: false}));
const migrated = GameVoice.loadSettings(storage, 'voice-v2', 'voice-v1');
assert.equal(migrated.mode, 'game-voice');
assert.equal(migrated.autoSpeak, true);
assert.equal(migrated.rate, 1.4);
assert.equal(migrated.voiceName, 'Svensk');
assert.equal(migrated.soundSignals, false);
const requested = {...GameVoice.DEFAULT_SETTINGS, mode: 'game-voice', autoSpeak: true, rate: 1.5, voiceName: 'Svensk'};
assert.equal(GameVoice.saveSettings(storage, 'voice', requested), true);
const loaded = GameVoice.loadSettings(storage, 'voice');
assert.equal(loaded.mode, 'game-voice'); assert.equal(loaded.mode, 'game-voice');
assert.equal(loaded.autoSpeak, true); assert.equal(loaded.autoSpeak, true);
assert.equal(loaded.rate, 1.5); assert.equal(loaded.rate, 1.5);
assert.equal(loaded.voiceName, 'Svensk'); assert.equal(loaded.voiceName, 'Svensk');
values.set('voice', '{trasig'); values.set('voice', '{trasig');
assert.equal(global.GameVoice.loadSettings(storage, 'voice').mode, 'screen-reader'); assert.equal(GameVoice.loadSettings(storage, 'voice').mode, 'game-voice');
assert.equal(global.GameVoice.saveSettings({setItem() { throw new Error('blocked'); }}, 'voice', requested), false); assert.equal(GameVoice.loadSettings(storage, 'voice').autoSpeak, true);
assert.equal(GameVoice.saveSettings({setItem() { throw new Error('blocked'); }}, 'voice', requested), false);
}); });
+35 -8
View File
@@ -1,8 +1,8 @@
/* Browser voice adapters. Kept independent of the game submission and API layer. */ /* Browser voice adapters. Kept independent of the game submission and API layer. */
(function exposeVoice(root) { (function exposeVoice(root) {
const DEFAULT_SETTINGS = Object.freeze({ const DEFAULT_SETTINGS = Object.freeze({
mode: 'screen-reader', mode: 'game-voice',
autoSpeak: false, autoSpeak: true,
language: 'sv-SE', language: 'sv-SE',
rate: 1, rate: 1,
voiceName: '', voiceName: '',
@@ -25,9 +25,22 @@
return {command: aliases[command] || 'unknown'}; return {command: aliases[command] || 'unknown'};
} }
function loadSettings(storage, key) { function loadSettings(storage, key, legacyKey) {
try { try {
const stored = JSON.parse(storage.getItem(key) || '{}'); const current = storage.getItem(key);
if (!current && legacyKey) {
const legacy = JSON.parse(storage.getItem(legacyKey) || '{}');
const migrated = {
...DEFAULT_SETTINGS,
rate: legacy.rate,
voiceName: legacy.voiceName,
speakerProfiles: legacy.speakerProfiles,
soundSignals: legacy.soundSignals,
};
saveSettings(storage, key, migrated);
return migrated;
}
const stored = JSON.parse(current || '{}');
const settings = {...DEFAULT_SETTINGS, ...stored}; const settings = {...DEFAULT_SETTINGS, ...stored};
if (!['screen-reader', 'game-voice', 'text-only'].includes(settings.mode)) settings.mode = DEFAULT_SETTINGS.mode; if (!['screen-reader', 'game-voice', 'text-only'].includes(settings.mode)) settings.mode = DEFAULT_SETTINGS.mode;
settings.rate = Math.min(2, Math.max(0.5, Number(settings.rate) || 1)); settings.rate = Math.min(2, Math.max(0.5, Number(settings.rate) || 1));
@@ -44,6 +57,16 @@
catch (_) { return false; } catch (_) { return false; }
} }
function characterVoiceProfile(voiceIdentity, characterId = '') {
const identity = ['masculine', 'feminine', 'neutral'].includes(voiceIdentity) ? voiceIdentity : 'neutral';
let hash = 2166136261;
for (const char of String(characterId)) hash = Math.imul(hash ^ char.charCodeAt(0), 16777619) >>> 0;
const variation = (hash % 1000) / 1000;
if (identity === 'masculine') return {pitch: 0.88 + variation * 0.08, rate: 0.96 + variation * 0.04};
if (identity === 'feminine') return {pitch: 1.06 + variation * 0.08, rate: 0.98 + variation * 0.04};
return {pitch: 0.98 + variation * 0.04, rate: 1};
}
function createVoiceController(options = {}) { function createVoiceController(options = {}) {
const win = options.window || root; const win = options.window || root;
const onState = options.onState || (() => {}); const onState = options.onState || (() => {});
@@ -163,8 +186,11 @@
catch (_) { setState('IDLE', 'Talsyntesen kunde inte startas. Dialogen finns kvar som text.'); return false; } catch (_) { setState('IDLE', 'Talsyntesen kunde inte startas. Dialogen finns kvar som text.'); return false; }
utterance.lang = settings.language || 'sv-SE'; utterance.lang = settings.language || 'sv-SE';
const profile = voiceOptions.characterId ? settings.speakerProfiles?.[voiceOptions.characterId] || {} : {}; const profile = voiceOptions.characterId ? settings.speakerProfiles?.[voiceOptions.characterId] || {} : {};
utterance.rate = Math.min(2, Math.max(0.5, Number(voiceOptions.rate ?? profile.rate ?? settings.rate) || 1)); const identityProfile = characterVoiceProfile(voiceOptions.voiceIdentity, voiceOptions.characterId);
utterance.pitch = Math.min(2, Math.max(0, Number(voiceOptions.pitch ?? profile.pitch ?? 1) || 1)); const isNarrator = voiceOptions.role === 'narrator';
const configuredRate = Number(voiceOptions.rate ?? profile.rate ?? settings.rate) || 1;
utterance.rate = Math.min(2, Math.max(0.5, configuredRate * (isNarrator || voiceOptions.rate != null || profile.rate != null ? 1 : identityProfile.rate)));
utterance.pitch = isNarrator ? 1 : Math.min(2, Math.max(0, Number(voiceOptions.pitch ?? profile.pitch ?? identityProfile.pitch) || 1));
const requestedName = voiceOptions.voiceName || profile.voiceName || settings.voiceName; const requestedName = voiceOptions.voiceName || profile.voiceName || settings.voiceName;
const voices = availableVoices(); const voices = availableVoices();
utterance.voice = voices.find(voice => voice.name === requestedName) utterance.voice = voices.find(voice => voice.name === requestedName)
@@ -201,8 +227,9 @@
function getState() { return state; } function getState() { return state; }
function getSettings() { return {...settings}; } function getSettings() { return {...settings}; }
function getVoices() { return availableVoices(); } function getVoices() { return availableVoices(); }
return {startListening, stopListening, speak, cancelSpeech, stopAll, update, getState, getSettings, getVoices}; function supportsRecognition() { return Boolean(win.SpeechRecognition || win.webkitSpeechRecognition); }
return {startListening, stopListening, speak, cancelSpeech, stopAll, update, getState, getSettings, getVoices, supportsRecognition};
} }
root.GameVoice = {createVoiceController, DEFAULT_SETTINGS, parseVoiceCommand, loadSettings, saveSettings}; root.GameVoice = {createVoiceController, DEFAULT_SETTINGS, parseVoiceCommand, loadSettings, saveSettings, characterVoiceProfile};
})(typeof window !== 'undefined' ? window : globalThis); })(typeof window !== 'undefined' ? window : globalThis);