1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
| <!doctype html> <html lang="zh-CN">
<head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width,initial-scale=1" /> <title>流式 TTS 播放器 (POST JSON)</title> <style> body { font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, "Helvetica Neue", Arial; margin: 20px; background: #0f172a; color: #e6eef8 }
.card { background: #111827; padding: 18px; border-radius: 10px; box-shadow: 0 6px 18px rgba(2, 6, 23, .6); max-width: 820px; margin: auto }
textarea, input, select, button { width: 100%; margin-top: 8px; padding: 8px; border-radius: 8px; border: 1px solid #23303b; background: #071022; color: #e6eef8 }
button { cursor: pointer; background: #1e293b }
.row { display: flex; gap: 8px; margin-top: 10px; flex-wrap: wrap }
.log { margin-top: 12px; background: #04101a; padding: 10px; border-radius: 6px; height: 120px; overflow: auto; font-size: 13px } </style> </head>
<body> <div class="card"> <h2>流式 TTS 播放器 (POST JSON)</h2>
<label>TTS 接口 URL</label> <input id="ttsUrl" value="http://127.0.0.1:9880" />
<label>Refer WAV 路径</label> <input id="referWav" value="/home/ubuntu/hou/GPT-SoVITS/data/gpt/ref.wav" />
<label>Prompt 文本</label> <textarea id="promptText">我还有些事要研究,你们先转换一下心情吧。</textarea>
<label>Prompt 语言</label> <input id="promptLang" value="zh" />
<label>合成文本</label> <textarea id="text">欢迎使用我们的语音合成服务。</textarea>
<label>文本语言</label> <input id="textLang" value="zh" />
<label>切分标点</label> <input id="cutPunc" value=",。!?" />
<div class="row"> <select id="mediaType"> <option value="ogg">ogg</option> <option value="aac">aac</option> <option value="wav">wav</option> </select> <button id="startBtn">开始播放</button> <button id="stopBtn" disabled>停止</button> </div>
<audio id="player" controls style="width:100%;margin-top:10px"></audio> <div class="log" id="log"></div> </div>
<script> const logEl = document.getElementById('log'); function log(...args) { console.log(...args); logEl.innerText += args.join(' ') + '\n'; logEl.scrollTop = logEl.scrollHeight; }
let controller = null; let reader = null; let mediaSource = null; let sourceBuffer = null; let queue = []; let audioUrl = null; let playingBlobParts = [];
const startBtn = document.getElementById('startBtn'); const stopBtn = document.getElementById('stopBtn'); const player = document.getElementById('player');
startBtn.addEventListener('click', startStreaming); stopBtn.addEventListener('click', stopStreaming);
async function startStreaming() { stopStreaming(); const baseUrl = document.getElementById('ttsUrl').value.trim(); const mediaType = document.getElementById('mediaType').value;
const bodyData = { refer_wav_path: document.getElementById('referWav').value.trim(), prompt_text: document.getElementById('promptText').value, prompt_language: document.getElementById('promptLang').value.trim(), text: document.getElementById('text').value, text_language: document.getElementById('textLang').value.trim(), cut_punc: document.getElementById('cutPunc').value };
log('POST 请求:', baseUrl, bodyData); controller = new AbortController(); queue = []; playingBlobParts = [];
if ('MediaSource' in window && mediaType === 'ogg') { setupMediaSource('audio/ogg; codecs="opus"'); fetchAndStreamPOST(baseUrl, bodyData, controller.signal, true); } else if ('MediaSource' in window && mediaType === 'aac') { setupMediaSource('audio/aac'); fetchAndStreamPOST(baseUrl, bodyData, controller.signal, true); } else { fetchAndPlayAsBlobPOST(baseUrl, bodyData, controller.signal); } }
function setupMediaSource(mime) { cleanupMediaSource(); mediaSource = new MediaSource(); audioUrl = URL.createObjectURL(mediaSource); player.src = audioUrl; mediaSource.addEventListener('sourceopen', () => { try { sourceBuffer = mediaSource.addSourceBuffer(mime); } catch (e) { log('addSourceBuffer 失败:', e); return; } sourceBuffer.mode = 'sequence'; sourceBuffer.addEventListener('updateend', () => { if (queue.length > 0 && !sourceBuffer.updating) { const chunk = queue.shift(); sourceBuffer.appendBuffer(chunk); } else if (queue.length === 0 && mediaSource.readyState === 'open' && !reader) { mediaSource.endOfStream(); } }); if (queue.length > 0 && !sourceBuffer.updating) { const chunk = queue.shift(); sourceBuffer.appendBuffer(chunk); } player.play().catch(() => { }); }); }
function cleanupMediaSource() { if (sourceBuffer) { try { if (mediaSource && mediaSource.readyState === 'open') mediaSource.removeSourceBuffer(sourceBuffer); } catch (e) { } sourceBuffer = null; } if (mediaSource) { try { URL.revokeObjectURL(audioUrl); } catch (e) { } mediaSource = null; } }
async function fetchAndStreamPOST(url, body, signal, useMediaSource) { const resp = await fetch(url, { method: 'POST', signal, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }); if (!resp.ok) throw new Error('HTTP ' + resp.status); const ct = resp.headers.get('content-type') || ''; if (ct.includes('application/json')) { throw new Error('Server error: ' + JSON.stringify(await resp.json())); }
reader = resp.body.getReader(); stopBtn.disabled = false; startBtn.disabled = true;
while (true) { const { done, value } = await reader.read(); if (done) break; if (!value) continue; const chunk = value.buffer.slice(value.byteOffset, value.byteOffset + value.byteLength); playingBlobParts.push(chunk); if (useMediaSource && sourceBuffer) { if (sourceBuffer.updating || queue.length > 0) { queue.push(chunk); } else { try { sourceBuffer.appendBuffer(chunk); } catch (e) { queue.push(chunk); } } } } log('流读取结束'); reader = null; stopBtn.disabled = true; startBtn.disabled = false;
if (!useMediaSource) { const mime = resp.headers.get('content-type') || 'audio/ogg'; const blob = new Blob(playingBlobParts, { type: mime }); player.src = URL.createObjectURL(blob); player.play().catch(() => { }); } }
async function fetchAndPlayAsBlobPOST(url, body, signal) { log('fallback -> blob 下载'); const resp = await fetch(url, { method: 'POST', signal, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }); if (!resp.ok) { log('HTTP error', resp.status); return; } const ct = resp.headers.get('content-type') || 'audio/ogg'; const ab = await resp.arrayBuffer(); const blob = new Blob([ab], { type: ct }); player.src = URL.createObjectURL(blob); player.play().catch(() => { }); stopBtn.disabled = false; startBtn.disabled = true; }
function stopStreaming() { try { if (controller) controller.abort(); } catch (e) { } controller = null; if (reader) { try { reader.cancel(); } catch (e) { } reader = null; } cleanupMediaSource(); try { if (player.src && player.src.startsWith('blob:')) URL.revokeObjectURL(player.src); } catch (e) { } player.pause(); stopBtn.disabled = true; startBtn.disabled = false; log('已停止'); } </script> </body>
</html>
|