🔊 텍스트 리더: 현재 조각을 재생하는 동안 다음 조각을 미리 합성 요청(문장 사이 합성 시간만큼 침묵이 생기던 문제)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
kimandClaude Sonnet 5.5 committed 2026-10-20 17:56:04 +09:00
1 parent 92cf490ccd
commit 4597575e4e
1 file changed
+28 -13
+28 -13
View File
@@ -68,6 +68,7 @@ var _ttsEnabled = localStorage.getItem('ttsEnabled') !== 'false'; // default on
var _ttsAudio = null;
var _ttsBtnActive = null;
var _ttsAbort = null;
var _ttsAborts = []; // 미리 받기(prefetch) 요청들의 중단 컨트롤러
var _ttsSeqResolve = null; // resolves the currently-awaited piece's completion, so _ttsStop() can unblock the playback loop
var _appSendFn = null;
@@ -78,6 +79,7 @@ function initAppVoice(sendFn) {
// Stops whatever is currently loading/playing (abort in-flight fetch, pause audio, reset button).
function _ttsStop() {
if (_ttsAbort) { _ttsAbort.abort(); _ttsAbort = null; }
while (_ttsAborts.length) { try { _ttsAborts.pop().abort(); } catch (e) {} }
if (_ttsAudio) { _ttsAudio.pause(); _ttsAudio = null; }
if (_ttsSeqResolve) { var r = _ttsSeqResolve; _ttsSeqResolve = null; r(); }
if (_ttsBtnActive) { _ttsBtnActive.textContent = '🔊'; _ttsBtnActive.classList.remove('playing'); _ttsBtnActive = null; }
@@ -172,24 +174,37 @@ function _splitForSpeech(text) {
return out.length ? out : [text];
}
// 조각 N을 재생하는 동안 조각 N+1의 합성 요청을 미리 보낸다. 예전에는 재생이 끝난 뒤에야 다음 조각을 요청해서
// 문장마다 합성 시간(1~3초)이 그대로 문장 사이 침묵이 됐다(2026-10-20 "마침표 뒤 간격이 길다").
async function _ttsPlaySequence(btn, pieces) {
var cleaned = pieces.map(function(p) { return _cleanForSpeech(p); });
var fetches = {};
function prefetch(i) {
if (i >= cleaned.length || fetches[i] || !cleaned[i]) return;
var ac = new AbortController();
_ttsAborts.push(ac);
var pr = fetch('/api/voice/tts', {
method: 'POST',
headers: Object.assign({ 'Content-Type': 'application/json' }, authHeaders()),
credentials: 'include',
body: JSON.stringify({ text: cleaned[i].slice(0, 2000) }),
signal: ac.signal,
}).then(function(r) {
if (!r.ok) throw new Error('TTS 오류 ' + r.status);
return r.blob();
});
pr.catch(function() {}); // 중단된 미리 받기가 처리되지 않은 거부로 남지 않게
fetches[i] = pr;
}
for (var idx = 0; idx < pieces.length; idx++) {
if (_ttsBtnActive !== btn) return; // stopped/superseded before this piece started
var cleaned = _cleanForSpeech(pieces[idx]);
if (!cleaned) continue;
var ac = new AbortController();
_ttsAbort = ac;
if (!cleaned[idx]) continue;
prefetch(idx);
// 현재 조각 뒤의 다음 비어 있지 않은 조각도 바로 요청한다
for (var nx = idx + 1; nx < cleaned.length; nx++) { if (cleaned[nx]) { prefetch(nx); break; } }
var blob;
try {
var r = await fetch('/api/voice/tts', {
method: 'POST',
headers: Object.assign({ 'Content-Type': 'application/json' }, authHeaders()),
credentials: 'include',
body: JSON.stringify({ text: cleaned.slice(0, 2000) }),
signal: ac.signal,
});
if (!r.ok) throw new Error('TTS 오류 ' + r.status);
blob = await r.blob();
blob = await fetches[idx];
} catch (e) {
if (e.name === 'AbortError' || _ttsBtnActive !== btn) return;
_ttsStop();