Hamed744 commited on
Commit
b79e35f
·
verified ·
1 Parent(s): 6b41f29

Update index.html

Browse files
Files changed (1) hide show
  1. index.html +92 -139
index.html CHANGED
@@ -191,12 +191,10 @@
191
  <span id="char-count">0</span> / <span id="char-max">50000</span> نویسه
192
  </div>
193
  </div>
194
-
195
  <div class="form-group">
196
  <label for="prompt-input">🗣️ توصیف لحن و احساس (اختیاری)</label>
197
  <input type="text" id="prompt-input" placeholder="مثال: با لحنی آرام و قصه‌گو، یا صدای یک گوینده خبر حرفه‌ای">
198
  </div>
199
-
200
  <div class="form-group">
201
  <label>🎤 گوینده منتخب</label>
202
  <div id="selected-speaker-display">
@@ -210,7 +208,6 @@
210
  <button type="button" id="change-speaker-btn">تغییر گوینده</button>
211
  </div>
212
  </div>
213
-
214
  <div class="form-group">
215
  <div class="label-with-info">
216
  <label for="temperature-slider">🌡️ خلاقیت و پویایی صدا</label>
@@ -221,10 +218,8 @@
221
  <span id="temperature-value">0.9</span>
222
  </div>
223
  </div>
224
-
225
  <button type="submit" id="generate-btn">✨ خلق صدا با آلفا</button>
226
  </form>
227
-
228
  <div id="output-section">
229
  <div id="status-message">صدای تولید شده در اینجا ظاهر خواهد شد.</div>
230
  <div id="loading-animation-wrapper">
@@ -235,7 +230,6 @@
235
  </div>
236
  <p id="loading-text">در حال پردازش هوشمند و تولید صدا...</p>
237
  </div>
238
-
239
  <div id="audio-player-content">
240
  <div class="audio-waveform-container">
241
  <span class="audio-time audio-current-time">0:00</span>
@@ -246,16 +240,12 @@
246
  <span class="audio-time audio-total-time">0:00</span>
247
  </div>
248
  <div class="audio-controls-group">
249
- <button class="audio-skip-btn backward">
250
- <svg viewBox="0 0 24 24"><path d="M11 16V8l-4 4 4 4zm4-12v16l7-8-7-8z"></path></svg>
251
- </button>
252
  <button class="audio-play-pause-btn-large">
253
  <svg viewBox="0 0 24 24" class="play-icon"><path d="M8 5v14l11-7z"></path></svg>
254
  <svg viewBox="0 0 24 24" class="pause-icon" style="display:none;"><path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z"></path></svg>
255
  </button>
256
- <button class="audio-skip-btn forward">
257
- <svg viewBox="0 0 24 24"><path d="M13 16V8l4 4-4 4zM9 4v16L2 12l7-8z"></path></svg>
258
- </button>
259
  </div>
260
  <div class="audio-utility-controls">
261
  <button class="audio-volume-btn">
@@ -271,28 +261,8 @@
271
  </div>
272
 
273
  <!-- Modals -->
274
- <div id="speaker-modal" class="modal-overlay">
275
- <div class="modal-dialog">
276
- <div class="modal-header">
277
- <h2>گالری گویندگان آلفا</h2>
278
- <button type="button" class="close-modal-btn" data-modal-id="speaker-modal">×</button>
279
- </div>
280
- <div id="speaker-grid"></div>
281
- </div>
282
- </div>
283
- <div id="info-modal" class="modal-overlay">
284
- <div class="modal-dialog" style="max-width: 520px;">
285
- <div class="modal-header">
286
- <h2>🌡️ خلاقیت و پویایی صدا</h2>
287
- <button type="button" class="close-modal-btn" data-modal-id="info-modal">×</button>
288
- </div>
289
- <div>
290
- <p style="color: var(--text-secondary); line-height: 1.9;">این پارامتر، میزان "غیرقابل پیش‌بینی بودن" و تنوع در صدای خروجی را کنترل می‌کند.</p>
291
- <p><strong>مقادیر بالاتر (نزدیک به ۱.۵):</strong> صدایی بسیار متنوع، احساسی و پویا ایجاد می‌کند. ایده‌آل برای محتوای خلاقانه و هنری.</p>
292
- <p><strong>مقادیر پایین‌تر (نزدیک به ۰.۱):</strong> صدایی پایدار، یکنواخت و قابل پیش‌بینی‌تر تولید می‌کند. مناسب برای خوانش متون رسمی و خبری.</p>
293
- </div>
294
- </div>
295
- </div>
296
  <input type="hidden" id="selected_speaker_id_storage" value="Charon">
297
 
298
  <script>
@@ -303,164 +273,147 @@
303
  const FILE_URL_BASE = `${HF_SPACE_URL}/gradio_api/file=`;
304
  const FN_INDEX = 1;
305
 
306
- // UPDATED SPEAKERS ARRAY WITH NEW NAMES, GENDERS, AND IMAGE URLs
307
  const speakers = [
308
  { id: "Charon", name: "شهاب (مرد)", desc: "صدایی قدرتمند و رسا", imgUrl: "https://uploadkon.ir/uploads/a18705_25IMG-۲۰۲۵۰۷۰۵-۱۱۰۵۴۹.jpg" },
309
  { id: "Zephyr", name: "آوا (زن)", desc: "لطیف و دلنشین", imgUrl: "https://uploadkon.ir/uploads/029605_25IMG-۲۰۲۵۰۷۰۵-۱۱۱۲۵۲.jpg" },
310
  { id: "Achird", name: "نوید (مرد)", desc: "جوان و پرانرژی", imgUrl: "https://uploadkon.ir/uploads/697e05_25IMG-۲۰۲۵۰۶۰۹-۰۶۴۶۳۷.jpg" },
311
- { id: "Zubenelgenubi", name: "آرمان (مرد)", desc: "گرم و صمیمی", imgUrl: "https://uploadkon.ir/uploads/a8a705_25IMG-۲۰۲۵۰۷۰۵-۱۱۱۶۲۹.jpg" }, // Changed to male
312
- { id: "Vindemiatrix", name: "مهسا (زن)", desc: "باوقار و رسمی", imgUrl: "https://uploadkon.ir/uploads/d74d05_25IMG-۲۰۲۵۰۷۰۵-۱۱۱۸۳۸.jpg" }, // Changed to female
313
- { id: "Sadachbia", name: "سامان (مرد)", desc: "شاداب و پویا", imgUrl: "https://uploadkon.ir/uploads/580205_25IMG-۲۰۲۵۰۷۰۵-۱۱۳۳۳۰.jpg" }, // Changed to male
314
  { id: "Sadaltager", name: "آرش (مرد)", desc: "مطمئن و تاثیرگذار", imgUrl: "https://uploadkon.ir/uploads/c4db05_25IMG-۲۰۲۵۰۷۰۵-۱۱۳۵۰۰.jpg" },
315
  { id: "Sulafat", name: "شبنم (زن)", desc: "آرام و متین", imgUrl: "https://uploadkon.ir/uploads/995005_25IMG-۲۰۲۵۰۷۰۵-۱۱۳۶۱۱.jpg" },
316
- { id: "Laomedeia", name: "سحر (زن)", desc: "دوستانه و گیرا", imgUrl: "https://uploadkon.ir/uploads/660705_25IMG-۲۰۲۵۰۷۰۵-۱۱۳۷۵۴.jpg" }, // Changed to female
317
  { id: "Achernar", name: "مریم (زن)", desc: "حرفه‌ای و واضح", imgUrl: "https://uploadkon.ir/uploads/4c2905_25IMG-۲۰۲۵۰۷۰۵-۱۱۴۰۳۶.jpg" },
318
  { id: "Alnilam", name: "بهرام (مرد)", desc: "حماسی و نافذ", imgUrl: "https://uploadkon.ir/uploads/f0c205_25IMG-۲۰۲۵۰۷۰۵-۱۱۴۲۲۰.jpg" },
319
- { id: "Schedar", name: "نیکان (مرد)", desc: "مهربان و شیرین", imgUrl: "https://uploadkon.ir/uploads/d37a05_25IMG-۲۰۲۵۰۷۰۵-۱۱۴۳۲۵.jpg" }, // Changed to male
320
- { id: "Gacrux", name: "فرناز (زن)", desc: "پخته و قابل اعتماد", imgUrl: "https://uploadkon.ir/uploads/cff705_25IMG-۲۰۲۵۰۷۰۵-۱۱۴۶۰۵.jpg" }, // Changed to female
321
  { id: "Pulcherrima", name: "سارا (زن)", desc: "جذاب و مدرن", imgUrl: "https://uploadkon.ir/uploads/acb105_25IMG-۲۰۲۵۰۷۰۵-۱۱۴۷۴۳.jpg" },
322
  { id: "Umbriel", name: "مانی (مرد)", desc: "خلاق و متفاوت", imgUrl: "https://uploadkon.ir/uploads/68b505_25IMG-۲۰۲۵۰۷۰۵-۱۱۴۹۱۴.jpg" },
323
- { id: "Algieba", name: "آرتین (مرد)", desc: "با اصالت و شیک", imgUrl: "https://uploadkon.ir/uploads/571005_25IMG-۲۰۲۵۰۷۰۵-۱۱۵۰۳۹.jpg" }, // Changed to male
324
  { id: "Despina", name: "دلنواز (زن)", desc: "هنری و احساسی", imgUrl: "https://uploadkon.ir/uploads/5d7805_25IMG-۲۰۲۵۰۷۰۵-۱۱۵۲۲۲.jpg" },
325
- { id: "Erinome", name: "روژان (زن)", desc: "شفاف و گویا", imgUrl: "https://uploadkon.ir/uploads/aa8805_25IMG-۲۰۲۵۰۷۰۵-۱۱۵۳۴۹.jpg" }, // Changed to female
326
  { id: "Algenib", name: "امید (مرد)", desc: "انگیزه بخش و مثبت", imgUrl: "https://uploadkon.ir/uploads/a63c05_25IMG-۲۰۲۵۰۷۰۵-۱۱۵۹۲۱.jpg" },
327
  { id: "Orus", name: "بردیا (مرد)", desc: "ورزشی و پرهیجان", imgUrl: "https://uploadkon.ir/uploads/8bc405_25IMG-۲۰۲۵۰۷۰۵-۱۲۱۴۳۳.jpg" },
328
  { id: "Aoede", name: "ترانه (زن)", desc: "موزیکال و خوش‌آهنگ", imgUrl: "https://uploadkon.ir/uploads/9cb405_25IMG-۲۰۲۵۰۷۰۵-۱۲۱۸۵۰.jpg" },
329
- { id: "Callirrhoe", name: "نیکو (زن)", desc: "روایتگر و قصه‌گو", imgUrl: "https://uploadkon.ir/uploads/ee5f05_25IMG-۲۰۲۵۰۷۰۵-۱۲۲۰۴۷.jpg" }, // Changed to female
330
  { id: "Autonoe", name: "هستی (زن)", desc: "طبیعی و خودمانی", imgUrl: "https://uploadkon.ir/uploads/9b0505_25IMG-۲۰۲۵۰۷۰۵-۱۲۲۲۲۲.jpg" },
331
  { id: "Enceladus", name: "کامیار (مرد)", desc: "مصمم و جدی", imgUrl: "https://uploadkon.ir/uploads/127805_25IMG-۲۰۲۵۰۷۰۵-۱۲۲۴۱۴.jpg" },
332
- { id: "Iapetus", name: "کیانوش (مرد)", desc: "درخشان و گیرا", imgUrl: "https://uploadkon.ir/uploads/c98b05_25IMG-۲۰۲۵۰۷۰۵-۱۲۲۶۰۵.jpg" }, // Changed to male
333
  { id: "Puck", name: "پویا (مرد)", desc: "بازیگوش و سرزنده", imgUrl: "https://uploadkon.ir/uploads/ca3605_25IMG-۲۰۲۵۰۷۰۵-۱۲۲۸۳۹.jpg" },
334
  { id: "Kore", name: "مهتاب (زن)", desc: "نجواگر و آرامش‌بخش", imgUrl: "https://uploadkon.ir/uploads/b66605_25IMG-۲۰۲۵۰۷۰۵-۱۲۳۰۳۵.jpg" },
335
  { id: "Fenrir", name: "سام (مرد)", desc: "جسور و بی‌باک", imgUrl: "https://uploadkon.ir/uploads/03c005_25IMG-۲۰۲۵۰۷۰۵-۱۲۳۴۱۳.jpg" },
336
  { id: "Leda", name: "لیدا (زن)", desc: "کلاسیک و باوقار", imgUrl: "https://uploadkon.ir/uploads/710305_25IMG-۲۰۲۵۰۷۰۵-۱۲۳۷۳۱.jpg" }
337
  ];
338
 
339
- // --- DOM Elements ---
340
- const form = document.getElementById('tts-form'); const textInput = document.getElementById('text-input'); const promptInput = document.getElementById('prompt-input'); const tempSlider = document.getElementById('temperature-slider'); const tempValueSpan = document.getElementById('temperature-value'); const generateBtn = document.getElementById('generate-btn'); const outputSection = document.getElementById('output-section'); const statusMessage = document.getElementById('status-message'); const loadingAnimationWrapper = document.getElementById('loading-animation-wrapper'); const selectedSpeakerIdStorage = document.getElementById('selected_speaker_id_storage'); const changeSpeakerBtn = document.getElementById('change-speaker-btn'); const selectedSpeakerCard = document.getElementById('selected-speaker-card'); const speakerGridInModal = document.getElementById('speaker-grid'); const selectedSpeakerImgDisplay = document.getElementById('selected-speaker-img'); const selectedSpeakerNameDisplay = document.getElementById('selected-speaker-name'); const selectedSpeakerDescDisplay = document.getElementById('selected-speaker-desc'); const speakerModal = document.getElementById('speaker-modal'); const infoModal = document.getElementById('info-modal'); const tempInfoIcon = document.getElementById('temp-info-icon'); const hiddenAudioPlayer = document.getElementById('hidden-audio-player'); const audioPlayerContent = document.getElementById('audio-player-content'); const audioCurrentTimeSpan = audioPlayerContent.querySelector('.audio-current-time'); const audioTotalTimeSpan = audioPlayerContent.querySelector('.audio-total-time'); const audioWaveformCanvas = document.getElementById('audio-waveform-canvas'); const waveformCtx = audioWaveformCanvas.getContext('2d'); const playPauseBtn = audioPlayerContent.querySelector('.audio-play-pause-btn-large'); const playIcon = playPauseBtn.querySelector('.play-icon'); const pauseIcon = playPauseBtn.querySelector('.pause-icon'); const skipBackwardBtn = audioPlayerContent.querySelector('.audio-skip-btn.backward'); const skipForwardBtn = audioPlayerContent.querySelector('.audio-skip-btn.forward'); const volumeBtn = audioPlayerContent.querySelector('.audio-volume-btn'); const volumeHighIcon = volumeBtn.querySelector('.volume-high-icon'); const volumeMuteIcon = volumeBtn.querySelector('.volume-mute-icon'); const speedBtn = audioPlayerContent.querySelector('.audio-speed-btn');
341
  let currentPlaybackSpeedIndex = 0; const playbackSpeeds = [1.0, 1.25, 1.5, 0.75]; let audioPeaks = []; let audioContext = null;
342
 
343
- // --- Character Counter ---
344
  const charCountSpan = document.getElementById('char-count'); const charMaxSpan = document.getElementById('char-max'); const MAX_CHARS = 50000;
345
  charMaxSpan.textContent = MAX_CHARS.toLocaleString('fa-IR');
346
- textInput.addEventListener('input', () => { const currentLength = textInput.value.length; charCountSpan.textContent = currentLength.toLocaleString('fa-IR'); charCountSpan.style.color = currentLength > MAX_CHARS ? 'red' : 'var(--accent-primary)'; });
347
 
348
- // --- Speaker Logic ---
349
  const getSpeakerById = (id) => speakers.find(s => s.id === id) || speakers[0];
350
  const getImageUrl = (speaker) => speaker.imgUrl;
351
 
352
- const updateSelectedSpeakerDisplay = (speakerId) => { const speaker = getSpeakerById(speakerId); selectedSpeakerImgDisplay.src = getImageUrl(speaker); selectedSpeakerNameDisplay.textContent = speaker.name; selectedSpeakerDescDisplay.textContent = speaker.desc; selectedSpeakerIdStorage.value = speaker.id; };
353
- const createSpeakerCardsInModal = () => { speakerGridInModal.innerHTML = ''; speakers.forEach((speaker) => { const cardLabel = document.createElement('label'); cardLabel.className = 'speaker-card'; cardLabel.setAttribute('for', `modal-speaker-${speaker.id}`); const isChecked = speaker.id === selectedSpeakerIdStorage.value ? 'checked' : ''; cardLabel.innerHTML = ` <input type="radio" name="modal_speaker_selection" value="${speaker.id}" id="modal-speaker-${speaker.id}" ${isChecked}> <div class="speaker-visual"> <img src="${getImageUrl(speaker)}" alt="${speaker.name}" loading="lazy"> </div> <div class="speaker-name">${speaker.name}</div> `; cardLabel.addEventListener('click', () => { updateSelectedSpeakerDisplay(speaker.id); hideModal(speakerModal); }); speakerGridInModal.appendChild(cardLabel); }); };
354
-
355
- // --- Modal Management ---
356
- const showModal = (modalElement) => { modalElement.classList.add('visible'); setTimeout(() => modalElement.querySelector('button')?.focus(), 50); }; const hideModal = (modalElement) => modalElement.classList.remove('visible'); changeSpeakerBtn.addEventListener('click', () => { createSpeakerCardsInModal(); showModal(speakerModal); }); selectedSpeakerCard.addEventListener('click', () => { createSpeakerCardsInModal(); showModal(speakerModal); }); tempInfoIcon.addEventListener('click', () => showModal(infoModal)); document.querySelectorAll('.modal-overlay').forEach(o => o.addEventListener('click', (e) => (e.target === o) && hideModal(o))); document.querySelectorAll('.close-modal-btn').forEach(b => b.addEventListener('click', () => hideModal(document.getElementById(b.dataset.modalId)))); document.addEventListener('keydown', (e) => (e.key === 'Escape') && document.querySelectorAll('.modal-overlay.visible').forEach(hideModal)); tempSlider.addEventListener('input', () => { tempValueSpan.textContent = tempSlider.value; });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
357
 
358
- // --- Original Audio Player Logic (with Waveform Fix) ---
359
- const formatTime = (seconds) => { if (isNaN(seconds) || seconds < 0) return '0:00'; const minutes = Math.floor(seconds / 60); const remainingSeconds = Math.floor(seconds % 60); return `${minutes}:${remainingSeconds < 10 ? '0' : ''}${remainingSeconds}`; };
360
 
361
- function drawWaveform(progressRatio = 0) {
362
- // This function is now robust because it's called inside requestAnimationFrame
363
- const dpr = window.devicePixelRatio || 1;
364
- audioWaveformCanvas.width = audioWaveformCanvas.offsetWidth * dpr;
365
- audioWaveformCanvas.height = audioWaveformCanvas.offsetHeight * dpr;
366
- waveformCtx.scale(dpr, dpr);
367
-
368
- const width = audioWaveformCanvas.offsetWidth;
369
- const height = audioWaveformCanvas.offsetHeight;
370
-
371
- if (width === 0 || height === 0) return; // Extra safety check
372
-
373
- waveformCtx.clearRect(0, 0, width, height);
374
-
375
- const barWidth = 3; const barGap = 2; const totalBarAndGap = barWidth + barGap;
376
- const numBars = Math.floor(width / totalBarAndGap);
377
- const offset = (width - (numBars * totalBarAndGap)) / 2;
378
- const activeBars = Math.floor(progressRatio * numBars);
379
-
380
- const activeColor = getComputedStyle(document.documentElement).getPropertyValue('--waveform-color-active').trim();
381
- const inactiveColor = getComputedStyle(document.documentElement).getPropertyValue('--waveform-color-inactive').trim();
382
-
383
- for (let i = 0; i < numBars; i++) {
384
- const peak = audioPeaks[i] || 0;
385
- const barHeight = peak * height;
386
- waveformCtx.fillStyle = i < activeBars ? activeColor : inactiveColor;
387
- const x = offset + i * totalBarAndGap;
388
- const y = (height - barHeight) / 2;
389
- waveformCtx.fillRect(x, y, barWidth, barHeight);
390
- }
391
- }
392
 
393
- const updatePlayerUI = () => { playIcon.style.display = hiddenAudioPlayer.paused || hiddenAudioPlayer.ended ? 'block' : 'none'; pauseIcon.style.display = !(hiddenAudioPlayer.paused || hiddenAudioPlayer.ended) ? 'block' : 'none'; const currentTime = hiddenAudioPlayer.currentTime; const duration = hiddenAudioPlayer.duration; audioCurrentTimeSpan.textContent = formatTime(currentTime); if (isFinite(duration) && duration > 0) { audioTotalTimeSpan.textContent = formatTime(duration); requestAnimationFrame(() => drawWaveform(currentTime / duration)); } else { requestAnimationFrame(() => drawWaveform(0)); } };
394
 
395
- async function processAudioForWaveform(audioBuffer) {
396
- if (!audioBuffer) { audioPeaks = []; return; }
397
- const channelData = audioBuffer.getChannelData(0);
398
- const numBars = Math.floor(audioWaveformCanvas.offsetWidth / 5);
399
- const samplesPerBar = Math.floor(channelData.length / numBars);
400
- const peaks = [];
401
- for (let i = 0; i < numBars; i++) {
402
- let maxPeak = 0;
403
- const start = i * samplesPerBar;
404
- for (let j = 0; j < samplesPerBar; j++) {
405
- const value = Math.abs(channelData[start + j]);
406
- if (value > maxPeak) maxPeak = value;
407
- }
408
- peaks.push(Math.min(1, Math.max(0, maxPeak * 1.5)));
409
- }
410
- audioPeaks = peaks;
411
- // Draw initial waveform on the next available frame to ensure canvas is ready
412
  requestAnimationFrame(() => drawWaveform(0));
413
  }
414
 
415
- playPauseBtn.addEventListener('click', () => hiddenAudioPlayer.paused ? hiddenAudioPlayer.play() : hiddenAudioPlayer.pause()); skipBackwardBtn.addEventListener('click', () => hiddenAudioPlayer.currentTime = Math.max(0, hiddenAudioPlayer.currentTime - 5)); skipForwardBtn.addEventListener('click', () => hiddenAudioPlayer.currentTime = Math.min(hiddenAudioPlayer.duration, hiddenAudioPlayer.currentTime + 5));
416
- volumeBtn.addEventListener('click', () => { hiddenAudioPlayer.muted = !hiddenAudioPlayer.muted; volumeHighIcon.style.display = hiddenAudioPlayer.muted ? 'none' : 'block'; volumeMuteIcon.style.display = hiddenAudioPlayer.muted ? 'block' : 'none'; });
417
- speedBtn.addEventListener('click', () => { currentPlaybackSpeedIndex = (currentPlaybackSpeedIndex + 1) % playbackSpeeds.length; const newSpeed = playbackSpeeds[currentPlaybackSpeedIndex]; hiddenAudioPlayer.playbackRate = newSpeed; speedBtn.textContent = `${newSpeed}x`; });
418
- hiddenAudioPlayer.addEventListener('timeupdate', updatePlayerUI); hiddenAudioPlayer.addEventListener('play', updatePlayerUI); hiddenAudioPlayer.addEventListener('pause', updatePlayerUI); hiddenAudioPlayer.addEventListener('ended', () => { hiddenAudioPlayer.currentTime = 0; updatePlayerUI(); });
419
- hiddenAudioPlayer.addEventListener('loadedmetadata', async () => { if (!audioContext) audioContext = new (window.AudioContext || window.webkitAudioContext)(); try { const response = await fetch(hiddenAudioPlayer.src); const arrayBuffer = await response.arrayBuffer(); const decodedBuffer = await audioContext.decodeAudioData(arrayBuffer); await processAudioForWaveform(decodedBuffer); } catch (e) { console.error("Error decoding audio for waveform:", e); audioPeaks = []; requestAnimationFrame(() => drawWaveform(0)); } updatePlayerUI(); });
420
- let resizeTimeout; window.addEventListener('resize', () => { clearTimeout(resizeTimeout); resizeTimeout = setTimeout(() => { if (outputSection.classList.contains('has-content') && hiddenAudioPlayer.src) { requestAnimationFrame(() => drawWaveform(hiddenAudioPlayer.currentTime / hiddenAudioPlayer.duration)); } }, 250); });
 
421
 
422
- // --- State Management Functions ---
423
- const showLoadingState = () => { audioPlayerContent.style.display = 'none'; outputSection.classList.remove('has-content'); statusMessage.style.display = 'none'; loadingAnimationWrapper.style.display = 'flex'; generateBtn.disabled = true; generateBtn.innerHTML = ` <svg aria-hidden="true" role="status" fill="currentColor" viewBox="0 0 100 101" style="animation: spin 1s linear infinite;"> <path d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z" fill="#E5E7EB"/> <path d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0492C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z" fill="currentColor"/> </svg> در حال پردازش... `; };
424
- const showResultState = (isSuccess, message = '') => { loadingAnimationWrapper.style.display = 'none'; if (isSuccess) { statusMessage.style.display = 'none'; audioPlayerContent.style.display = 'flex'; outputSection.classList.add('has-content'); } else { statusMessage.textContent = message || 'خطایی رخ داد. لطفاً دوباره تلاش کنید.'; statusMessage.style.display = 'block'; audioPlayerContent.style.display = 'none'; outputSection.classList.remove('has-content'); hiddenAudioPlayer.src = ''; audioPeaks = []; requestAnimationFrame(() => drawWaveform(0)); } generateBtn.disabled = false; generateBtn.innerHTML = '✨ خلق صدا با آلفا'; };
425
 
426
- // --- API Call ---
427
  async function generateAudio(event) {
428
- event.preventDefault(); showLoadingState();
429
- const text = textInput.value;
 
 
430
  if (!text.trim()) { showResultState(false, 'خطا: متن ورودی نمی‌تواند خالی باشد.'); return; }
431
  if (text.length > MAX_CHARS) { showResultState(false, `خطا: طول متن بیش از ${MAX_CHARS.toLocaleString('fa-IR')} نویسه است.`); return; }
432
- const payload = { fn_index: FN_INDEX, data: [false, null, text, promptInput.value, selectedSpeakerIdStorage.value, parseFloat(tempSlider.value)], event_data: null, session_hash: Math.random().toString(36).substring(2) };
433
  try {
434
- const joinQueueResponse = await fetch(JOIN_QUEUE_URL, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) });
435
- if (!joinQueueResponse.ok) { throw new Error(`خطا در برقراری ارتباط با سرویس آلفا (کد: ${joinQueueResponse.status}).`); }
436
- let finalFilePath = null; const startTime = Date.now(); const timeoutDuration = 90000;
437
- while (Date.now() - startTime < timeoutDuration) {
438
- const dataResponse = await fetch(`${GET_DATA_URL_BASE}?session_hash=${payload.session_hash}`);
439
- if (!dataResponse.ok) { throw new Error(`خطا در دریافت داده از س��ویس (کد: ${dataResponse.status})`); }
440
- const responseText = await dataResponse.text(); const lines = responseText.trim().split('\n');
441
  for (const line of lines) {
442
  if (!line.startsWith('data:')) continue;
443
  try {
444
  const data = JSON.parse(line.substring(5));
445
  if (data.msg === 'process_completed') {
446
- if (data.success && data.output?.data?.[0] && (data.output.data[0].name || data.output.data[0].path)) { finalFilePath = data.output.data[0].name || data.output.data[0].path; } else { throw new Error(data.output?.error || 'خطای ناشناخته در پردازش سرور.'); }
447
  break;
448
- } else if (data.msg === 'queue_full') { throw new Error('صف پردازش پر است. لطفا کمی بعد تلاش کنید.'); }
449
- } catch (e) { console.warn("Error parsing JSON from stream:", e, "Line:", line); }
450
  }
451
- if (finalFilePath) break;
452
- await new Promise(resolve => setTimeout(resolve, 1000));
453
  }
454
- if (finalFilePath) { hiddenAudioPlayer.src = `${FILE_URL_BASE}${finalFilePath}`; showResultState(true); } else if (Date.now() - startTime >= timeoutDuration) { throw new Error('پردازش بیش از حد طول کشید و متوقف شد.'); } else { throw new Error('فایل صوتی از سرور دریافت نشد یا پردازش ناموفق بود.'); }
455
- } catch (error) { console.error('خطا در فرآیند تولید صدا:', error); showResultState(false, error.message); }
456
  }
457
 
458
- // --- Initial Setup ---
459
- const defaultSpeakerId = speakers.length > 0 ? speakers[0].id : "Charon";
460
- updateSelectedSpeakerDisplay(selectedSpeakerIdStorage.value || defaultSpeakerId);
461
- form.addEventListener('submit', generateAudio);
462
- statusMessage.style.display = 'block'; loadingAnimationWrapper.style.display = 'none';
463
- audioPlayerContent.style.display = 'none'; outputSection.classList.remove('has-content');
464
  });
465
  </script>
466
  </body>
 
191
  <span id="char-count">0</span> / <span id="char-max">50000</span> نویسه
192
  </div>
193
  </div>
 
194
  <div class="form-group">
195
  <label for="prompt-input">🗣️ توصیف لحن و احساس (اختیاری)</label>
196
  <input type="text" id="prompt-input" placeholder="مثال: با لحنی آرام و قصه‌گو، یا صدای یک گوینده خبر حرفه‌ای">
197
  </div>
 
198
  <div class="form-group">
199
  <label>🎤 گوینده منتخب</label>
200
  <div id="selected-speaker-display">
 
208
  <button type="button" id="change-speaker-btn">تغییر گوینده</button>
209
  </div>
210
  </div>
 
211
  <div class="form-group">
212
  <div class="label-with-info">
213
  <label for="temperature-slider">🌡️ خلاقیت و پویایی صدا</label>
 
218
  <span id="temperature-value">0.9</span>
219
  </div>
220
  </div>
 
221
  <button type="submit" id="generate-btn">✨ خلق صدا با آلفا</button>
222
  </form>
 
223
  <div id="output-section">
224
  <div id="status-message">صدای تولید شده در اینجا ظاهر خواهد شد.</div>
225
  <div id="loading-animation-wrapper">
 
230
  </div>
231
  <p id="loading-text">در حال پردازش هوشمند و تولید صدا...</p>
232
  </div>
 
233
  <div id="audio-player-content">
234
  <div class="audio-waveform-container">
235
  <span class="audio-time audio-current-time">0:00</span>
 
240
  <span class="audio-time audio-total-time">0:00</span>
241
  </div>
242
  <div class="audio-controls-group">
243
+ <button class="audio-skip-btn backward"><svg viewBox="0 0 24 24"><path d="M11 16V8l-4 4 4 4zm4-12v16l7-8-7-8z"></path></svg></button>
 
 
244
  <button class="audio-play-pause-btn-large">
245
  <svg viewBox="0 0 24 24" class="play-icon"><path d="M8 5v14l11-7z"></path></svg>
246
  <svg viewBox="0 0 24 24" class="pause-icon" style="display:none;"><path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z"></path></svg>
247
  </button>
248
+ <button class="audio-skip-btn forward"><svg viewBox="0 0 24 24"><path d="M13 16V8l4 4-4 4zM9 4v16L2 12l7-8z"></path></svg></button>
 
 
249
  </div>
250
  <div class="audio-utility-controls">
251
  <button class="audio-volume-btn">
 
261
  </div>
262
 
263
  <!-- Modals -->
264
+ <div id="speaker-modal" class="modal-overlay"><div class="modal-dialog"><div class="modal-header"><h2>گالری گویندگان آلفا</h2><button type="button" class="close-modal-btn" data-modal-id="speaker-modal">×</button></div><div id="speaker-grid"></div></div></div>
265
+ <div id="info-modal" class="modal-overlay"><div class="modal-dialog" style="max-width: 520px;"><div class="modal-header"><h2>🌡️ خلاقیت و پویایی صدا</h2><button type="button" class="close-modal-btn" data-modal-id="info-modal">×</button></div><div><p style="color: var(--text-secondary); line-height: 1.9;">این پارامتر، میزان "غیرقابل پیش‌بینی بودن" و تنوع در صدای خروجی را کنترل می‌کند.</p><p><strong>مقادیر بالاتر (نزدیک به ۱.۵):</strong> صدایی بسیار متنوع، احساسی و پویا ایجاد می‌کند. ایده‌آل برای محتوای خلاقانه و هنری.</p><p><strong>مقادیر پایین‌تر (نزدیک به ۰.۱):</strong> صدایی پایدار، یکنواخت و قابل پیش‌بینی‌تر تولید می‌کند. مناسب برای خوانش متون رسمی و خبری.</p></div></div></div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
266
  <input type="hidden" id="selected_speaker_id_storage" value="Charon">
267
 
268
  <script>
 
273
  const FILE_URL_BASE = `${HF_SPACE_URL}/gradio_api/file=`;
274
  const FN_INDEX = 1;
275
 
 
276
  const speakers = [
277
  { id: "Charon", name: "شهاب (مرد)", desc: "صدایی قدرتمند و رسا", imgUrl: "https://uploadkon.ir/uploads/a18705_25IMG-۲۰۲۵۰۷۰۵-۱۱۰۵۴۹.jpg" },
278
  { id: "Zephyr", name: "آوا (زن)", desc: "لطیف و دلنشین", imgUrl: "https://uploadkon.ir/uploads/029605_25IMG-۲۰۲۵۰۷۰۵-۱۱۱۲۵۲.jpg" },
279
  { id: "Achird", name: "نوید (مرد)", desc: "جوان و پرانرژی", imgUrl: "https://uploadkon.ir/uploads/697e05_25IMG-۲۰۲۵۰۶۰۹-۰۶۴۶۳۷.jpg" },
280
+ { id: "Zubenelgenubi", name: "آرمان (مرد)", desc: "گرم و صمیمی", imgUrl: "https://uploadkon.ir/uploads/a8a705_25IMG-۲۰۲۵۰۷۰۵-۱۱۱۶۲۹.jpg" },
281
+ { id: "Vindemiatrix", name: "مهسا (زن)", desc: "باوقار و رسمی", imgUrl: "https://uploadkon.ir/uploads/d74d05_25IMG-۲۰۲۵۰۷۰۵-۱۱۱۸۳۸.jpg" },
282
+ { id: "Sadachbia", name: "سامان (مرد)", desc: "شاداب و پویا", imgUrl: "https://uploadkon.ir/uploads/580205_25IMG-۲۰۲۵۰۷۰۵-۱۱۳۳۳۰.jpg" },
283
  { id: "Sadaltager", name: "آرش (مرد)", desc: "مطمئن و تاثیرگذار", imgUrl: "https://uploadkon.ir/uploads/c4db05_25IMG-۲۰۲۵۰۷۰۵-۱۱۳۵۰۰.jpg" },
284
  { id: "Sulafat", name: "شبنم (زن)", desc: "آرام و متین", imgUrl: "https://uploadkon.ir/uploads/995005_25IMG-۲۰۲۵۰۷۰۵-۱۱۳۶۱۱.jpg" },
285
+ { id: "Laomedeia", name: "سحر (زن)", desc: "دوستانه و گیرا", imgUrl: "https://uploadkon.ir/uploads/660705_25IMG-۲۰۲۵۰۷۰۵-۱۱۳۷۵۴.jpg" },
286
  { id: "Achernar", name: "مریم (زن)", desc: "حرفه‌ای و واضح", imgUrl: "https://uploadkon.ir/uploads/4c2905_25IMG-۲۰۲۵۰۷۰۵-۱۱۴۰۳۶.jpg" },
287
  { id: "Alnilam", name: "بهرام (مرد)", desc: "حماسی و نافذ", imgUrl: "https://uploadkon.ir/uploads/f0c205_25IMG-۲۰۲۵۰۷۰۵-۱۱۴۲۲۰.jpg" },
288
+ { id: "Schedar", name: "نیکان (مرد)", desc: "مهربان و شیرین", imgUrl: "https://uploadkon.ir/uploads/d37a05_25IMG-۲۰۲۵۰۷۰۵-۱۱۴۳۲۵.jpg" },
289
+ { id: "Gacrux", name: "فرناز (زن)", desc: "پخته و قابل اعتماد", imgUrl: "https://uploadkon.ir/uploads/cff705_25IMG-۲۰۲۵۰۷۰۵-۱۱۴۶۰۵.jpg" },
290
  { id: "Pulcherrima", name: "سارا (زن)", desc: "جذاب و مدرن", imgUrl: "https://uploadkon.ir/uploads/acb105_25IMG-۲۰۲۵۰۷۰۵-۱۱۴۷۴۳.jpg" },
291
  { id: "Umbriel", name: "مانی (مرد)", desc: "خلاق و متفاوت", imgUrl: "https://uploadkon.ir/uploads/68b505_25IMG-۲۰۲۵۰۷۰۵-۱۱۴۹۱۴.jpg" },
292
+ { id: "Algieba", name: "آرتین (مرد)", desc: "با اصالت و شیک", imgUrl: "https://uploadkon.ir/uploads/571005_25IMG-۲۰۲۵۰۷۰۵-۱۱۵۰۳۹.jpg" },
293
  { id: "Despina", name: "دلنواز (زن)", desc: "هنری و احساسی", imgUrl: "https://uploadkon.ir/uploads/5d7805_25IMG-۲۰۲۵۰۷۰۵-۱۱۵۲۲۲.jpg" },
294
+ { id: "Erinome", name: "روژان (زن)", desc: "شفاف و گویا", imgUrl: "https://uploadkon.ir/uploads/aa8805_25IMG-۲۰۲۵۰۷۰۵-۱۱۵۳۴۹.jpg" },
295
  { id: "Algenib", name: "امید (مرد)", desc: "انگیزه بخش و مثبت", imgUrl: "https://uploadkon.ir/uploads/a63c05_25IMG-۲۰۲۵۰۷۰۵-۱۱۵۹۲۱.jpg" },
296
  { id: "Orus", name: "بردیا (مرد)", desc: "ورزشی و پرهیجان", imgUrl: "https://uploadkon.ir/uploads/8bc405_25IMG-۲۰۲۵۰۷۰۵-۱۲۱۴۳۳.jpg" },
297
  { id: "Aoede", name: "ترانه (زن)", desc: "موزیکال و خوش‌آهنگ", imgUrl: "https://uploadkon.ir/uploads/9cb405_25IMG-۲۰۲۵۰۷۰۵-۱۲۱۸۵۰.jpg" },
298
+ { id: "Callirrhoe", name: "نیکو (زن)", desc: "روایتگر و قصه‌گو", imgUrl: "https://uploadkon.ir/uploads/ee5f05_25IMG-۲۰۲۵۰۷۰۵-۱۲۲۰۴۷.jpg" },
299
  { id: "Autonoe", name: "هستی (زن)", desc: "طبیعی و خودمانی", imgUrl: "https://uploadkon.ir/uploads/9b0505_25IMG-۲۰۲۵۰۷۰۵-۱۲۲۲۲۲.jpg" },
300
  { id: "Enceladus", name: "کامیار (مرد)", desc: "مصمم و جدی", imgUrl: "https://uploadkon.ir/uploads/127805_25IMG-۲۰۲۵۰۷۰۵-۱۲۲۴۱۴.jpg" },
301
+ { id: "Iapetus", name: "کیانوش (مرد)", desc: "درخشان و گیرا", imgUrl: "https://uploadkon.ir/uploads/c98b05_25IMG-۲۰۲۵۰۷۰۵-۱۲۲۶۰۵.jpg" },
302
  { id: "Puck", name: "پویا (مرد)", desc: "بازیگوش و سرزنده", imgUrl: "https://uploadkon.ir/uploads/ca3605_25IMG-۲۰۲۵۰۷۰۵-۱۲۲۸۳۹.jpg" },
303
  { id: "Kore", name: "مهتاب (زن)", desc: "نجواگر و آرامش‌بخش", imgUrl: "https://uploadkon.ir/uploads/b66605_25IMG-۲۰۲۵۰۷۰۵-۱۲۳۰۳۵.jpg" },
304
  { id: "Fenrir", name: "سام (مرد)", desc: "جسور و بی‌باک", imgUrl: "https://uploadkon.ir/uploads/03c005_25IMG-۲۰۲۵۰۷۰۵-۱۲۳۴۱۳.jpg" },
305
  { id: "Leda", name: "لیدا (زن)", desc: "کلاسیک و باوقار", imgUrl: "https://uploadkon.ir/uploads/710305_25IMG-۲۰۲۵۰۷۰۵-۱۲۳۷۳۱.jpg" }
306
  ];
307
 
308
+ const dom = {form: document.getElementById('tts-form'), textInput: document.getElementById('text-input'), promptInput: document.getElementById('prompt-input'), tempSlider: document.getElementById('temperature-slider'), tempValueSpan: document.getElementById('temperature-value'), generateBtn: document.getElementById('generate-btn'), outputSection: document.getElementById('output-section'), statusMessage: document.getElementById('status-message'), loadingAnimationWrapper: document.getElementById('loading-animation-wrapper'), selectedSpeakerIdStorage: document.getElementById('selected_speaker_id_storage'), changeSpeakerBtn: document.getElementById('change-speaker-btn'), selectedSpeakerCard: document.getElementById('selected-speaker-card'), speakerGridInModal: document.getElementById('speaker-grid'), selectedSpeakerImgDisplay: document.getElementById('selected-speaker-img'), selectedSpeakerNameDisplay: document.getElementById('selected-speaker-name'), selectedSpeakerDescDisplay: document.getElementById('selected-speaker-desc'), speakerModal: document.getElementById('speaker-modal'), infoModal: document.getElementById('info-modal'), tempInfoIcon: document.getElementById('temp-info-icon'), hiddenAudioPlayer: document.getElementById('hidden-audio-player'), audioPlayerContent: document.getElementById('audio-player-content'), audioCurrentTimeSpan: document.querySelector('.audio-current-time'), audioTotalTimeSpan: document.querySelector('.audio-total-time'), audioWaveformCanvas: document.getElementById('audio-waveform-canvas'), playPauseBtn: document.querySelector('.audio-play-pause-btn-large'), playIcon: document.querySelector('.play-icon'), pauseIcon: document.querySelector('.pause-icon'), skipBackwardBtn: document.querySelector('.audio-skip-btn.backward'), skipForwardBtn: document.querySelector('.audio-skip-btn.forward'), volumeBtn: document.querySelector('.audio-volume-btn'), volumeHighIcon: document.querySelector('.volume-high-icon'), volumeMuteIcon: document.querySelector('.volume-mute-icon'), speedBtn: document.querySelector('.audio-speed-btn')};
309
+ const waveformCtx = dom.audioWaveformCanvas.getContext('2d');
310
  let currentPlaybackSpeedIndex = 0; const playbackSpeeds = [1.0, 1.25, 1.5, 0.75]; let audioPeaks = []; let audioContext = null;
311
 
 
312
  const charCountSpan = document.getElementById('char-count'); const charMaxSpan = document.getElementById('char-max'); const MAX_CHARS = 50000;
313
  charMaxSpan.textContent = MAX_CHARS.toLocaleString('fa-IR');
314
+ dom.textInput.addEventListener('input', () => { const len = dom.textInput.value.length; charCountSpan.textContent = len.toLocaleString('fa-IR'); charCountSpan.style.color = len > MAX_CHARS ? 'red' : 'var(--accent-primary)'; });
315
 
 
316
  const getSpeakerById = (id) => speakers.find(s => s.id === id) || speakers[0];
317
  const getImageUrl = (speaker) => speaker.imgUrl;
318
 
319
+ const updateSelectedSpeakerDisplay = (id) => { const s = getSpeakerById(id); dom.selectedSpeakerImgDisplay.src = getImageUrl(s); dom.selectedSpeakerNameDisplay.textContent = s.name; dom.selectedSpeakerDescDisplay.textContent = s.desc; dom.selectedSpeakerIdStorage.value = s.id; };
320
+ const createSpeakerCardsInModal = () => { dom.speakerGridInModal.innerHTML = ''; speakers.forEach((s) => { const l = document.createElement('label'); l.className = 'speaker-card'; l.htmlFor = `modal-speaker-${s.id}`; l.innerHTML = `<input type="radio" name="modal_speaker_selection" value="${s.id}" id="modal-speaker-${s.id}" ${s.id === dom.selectedSpeakerIdStorage.value ? 'checked' : ''}><div class="speaker-visual"><img src="${getImageUrl(s)}" alt="${s.name}" loading="lazy"></div><div class="speaker-name">${s.name}</div>`; l.addEventListener('click', () => { updateSelectedSpeakerDisplay(s.id); hideModal(dom.speakerModal); }); dom.speakerGridInModal.appendChild(l); }); };
321
+
322
+ const showModal = (el) => { el.classList.add('visible'); setTimeout(() => el.querySelector('button')?.focus(), 50); }; const hideModal = (el) => el.classList.remove('visible');
323
+ dom.changeSpeakerBtn.addEventListener('click', () => { createSpeakerCardsInModal(); showModal(dom.speakerModal); });
324
+ dom.selectedSpeakerCard.addEventListener('click', () => { createSpeakerCardsInModal(); showModal(dom.speakerModal); });
325
+ dom.tempInfoIcon.addEventListener('click', () => showModal(dom.infoModal));
326
+ document.querySelectorAll('.modal-overlay').forEach(o => o.addEventListener('click', (e) => (e.target === o) && hideModal(o)));
327
+ document.querySelectorAll('.close-modal-btn').forEach(b => b.addEventListener('click', () => hideModal(document.getElementById(b.dataset.modalId))));
328
+ document.addEventListener('keydown', (e) => (e.key === 'Escape') && document.querySelectorAll('.modal-overlay.visible').forEach(hideModal));
329
+ dom.tempSlider.addEventListener('input', () => { dom.tempValueSpan.textContent = dom.tempSlider.value; });
330
+
331
+ // --- THE FIX: State Reset Function ---
332
+ function resetAudioPlayerState() {
333
+ dom.hiddenAudioPlayer.pause();
334
+ dom.hiddenAudioPlayer.removeAttribute("src"); // More definitive than src=''
335
+ audioPeaks = [];
336
+ dom.audioCurrentTimeSpan.textContent = "0:00";
337
+ dom.audioTotalTimeSpan.textContent = "0:00";
338
+ dom.playIcon.style.display = 'block';
339
+ dom.pauseIcon.style.display = 'none';
340
+ // Clear the canvas on the next animation frame
341
+ requestAnimationFrame(() => {
342
+ waveformCtx.clearRect(0, 0, dom.audioWaveformCanvas.width, dom.audioWaveformCanvas.height);
343
+ });
344
+ }
345
 
346
+ const formatTime = (s) => { if (isNaN(s) || s < 0) return '0:00'; const m = Math.floor(s / 60); const rs = Math.floor(s % 60); return `${m}:${rs < 10 ? '0' : ''}${rs}`; };
 
347
 
348
+ function drawWaveform(progress) {
349
+ const dpr = window.devicePixelRatio || 1; const canvas = dom.audioWaveformCanvas; canvas.width = canvas.offsetWidth * dpr; canvas.height = canvas.offsetHeight * dpr; waveformCtx.scale(dpr, dpr);
350
+ const w = canvas.offsetWidth, h = canvas.offsetHeight;
351
+ if (w === 0) return;
352
+ waveformCtx.clearRect(0, 0, w, h);
353
+ const barW = 3, barG = 2, total = barW + barG, numBars = Math.floor(w / total), offset = (w - (numBars * total)) / 2, activeBars = Math.floor(progress * numBars);
354
+ const activeColor = getComputedStyle(document.documentElement).getPropertyValue('--waveform-color-active').trim(); const inactiveColor = getComputedStyle(document.documentElement).getPropertyValue('--waveform-color-inactive').trim();
355
+ for (let i = 0; i < numBars; i++) { const peak = audioPeaks[i] || 0; const barH = peak * h; waveformCtx.fillStyle = i < activeBars ? activeColor : inactiveColor; const x = offset + i * total, y = (h - barH) / 2; waveformCtx.fillRect(x, y, barW, barH); }
356
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
357
 
358
+ const updatePlayerUI = () => { const p = dom.hiddenAudioPlayer; p.paused || p.ended ? (dom.playIcon.style.display = 'block', dom.pauseIcon.style.display = 'none') : (dom.playIcon.style.display = 'none', dom.pauseIcon.style.display = 'block'); const dur = p.duration; dom.audioCurrentTimeSpan.textContent = formatTime(p.currentTime); if (isFinite(dur) && dur > 0) { dom.audioTotalTimeSpan.textContent = formatTime(dur); requestAnimationFrame(() => drawWaveform(p.currentTime / dur)); } else { requestAnimationFrame(() => drawWaveform(0)); } };
359
 
360
+ async function processAudioForWaveform(buffer) {
361
+ if (!buffer) { audioPeaks = []; return; }
362
+ const channelData = buffer.getChannelData(0); const numBars = Math.floor(dom.audioWaveformCanvas.offsetWidth / 5); const samplesPerBar = Math.floor(channelData.length / numBars); const pks = [];
363
+ for (let i = 0; i < numBars; i++) { let max = 0; const start = i * samplesPerBar; for (let j = 0; j < samplesPerBar; j++) { const v = Math.abs(channelData[start + j]); if (v > max) max = v; } pks.push(Math.min(1, max * 1.5)); }
364
+ audioPeaks = pks;
 
 
 
 
 
 
 
 
 
 
 
 
365
  requestAnimationFrame(() => drawWaveform(0));
366
  }
367
 
368
+ dom.playPauseBtn.addEventListener('click', () => dom.hiddenAudioPlayer.paused ? dom.hiddenAudioPlayer.play() : dom.hiddenAudioPlayer.pause());
369
+ dom.skipBackwardBtn.addEventListener('click', () => dom.hiddenAudioPlayer.currentTime = Math.max(0, dom.hiddenAudioPlayer.currentTime - 5));
370
+ dom.skipForwardBtn.addEventListener('click', () => dom.hiddenAudioPlayer.currentTime = Math.min(dom.hiddenAudioPlayer.duration, dom.hiddenAudioPlayer.currentTime + 5));
371
+ dom.volumeBtn.addEventListener('click', () => { dom.hiddenAudioPlayer.muted = !dom.hiddenAudioPlayer.muted; dom.volumeHighIcon.style.display = dom.hiddenAudioPlayer.muted ? 'none' : 'block'; dom.volumeMuteIcon.style.display = dom.hiddenAudioPlayer.muted ? 'block' : 'none'; });
372
+ dom.speedBtn.addEventListener('click', () => { currentPlaybackSpeedIndex = (currentPlaybackSpeedIndex + 1) % playbackSpeeds.length; const newSpeed = playbackSpeeds[currentPlaybackSpeedIndex]; dom.hiddenAudioPlayer.playbackRate = newSpeed; dom.speedBtn.textContent = `${newSpeed}x`; });
373
+ dom.hiddenAudioPlayer.addEventListener('timeupdate', updatePlayerUI); dom.hiddenAudioPlayer.addEventListener('play', updatePlayerUI); dom.hiddenAudioPlayer.addEventListener('pause', updatePlayerUI); dom.hiddenAudioPlayer.addEventListener('ended', () => { dom.hiddenAudioPlayer.currentTime = 0; updatePlayerUI(); });
374
+ dom.hiddenAudioPlayer.addEventListener('loadedmetadata', async () => { if (!audioContext) audioContext = new (window.AudioContext || window.webkitAudioContext)(); try { const res = await fetch(dom.hiddenAudioPlayer.src); const buffer = await res.arrayBuffer(); const decoded = await audioContext.decodeAudioData(buffer); await processAudioForWaveform(decoded); } catch (e) { console.error("Waveform Error:", e); audioPeaks = []; } updatePlayerUI(); });
375
 
376
+ const showLoadingState = () => { dom.audioPlayerContent.style.display = 'none'; dom.outputSection.classList.remove('has-content'); dom.statusMessage.style.display = 'none'; dom.loadingAnimationWrapper.style.display = 'flex'; dom.generateBtn.disabled = true; dom.generateBtn.innerHTML = `<svg aria-hidden="true" role="status" fill="currentColor" viewBox="0 0 100 101" style="animation: spin 1s linear infinite;"><path d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z" fill="#E5E7EB"/><path d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0492C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z" fill="currentColor"/></svg> در حال پردازش...`; };
377
+ const showResultState = (success, msg = '') => { dom.loadingAnimationWrapper.style.display = 'none'; if (success) { dom.statusMessage.style.display = 'none'; dom.audioPlayerContent.style.display = 'flex'; dom.outputSection.classList.add('has-content'); } else { dom.statusMessage.textContent = msg || 'خطایی رخ داد. لطفاً دوباره تلاش کنید.'; dom.statusMessage.style.display = 'block'; dom.audioPlayerContent.style.display = 'none'; dom.outputSection.classList.remove('has-content'); resetAudioPlayerState(); } dom.generateBtn.disabled = false; dom.generateBtn.innerHTML = '✨ خلق صدا با آلفا'; };
 
378
 
 
379
  async function generateAudio(event) {
380
+ event.preventDefault();
381
+ resetAudioPlayerState(); // <-- THE FIX IS CALLED HERE!
382
+ showLoadingState();
383
+ const text = dom.textInput.value;
384
  if (!text.trim()) { showResultState(false, 'خطا: متن ورودی نمی‌تواند خالی باشد.'); return; }
385
  if (text.length > MAX_CHARS) { showResultState(false, `خطا: طول متن بیش از ${MAX_CHARS.toLocaleString('fa-IR')} نویسه است.`); return; }
386
+ const payload = { fn_index: FN_INDEX, data: [false, null, text, dom.promptInput.value, dom.selectedSpeakerIdStorage.value, parseFloat(dom.tempSlider.value)], event_data: null, session_hash: Math.random().toString(36).substring(2) };
387
  try {
388
+ const joinRes = await fetch(JOIN_QUEUE_URL, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) });
389
+ if (!joinRes.ok) throw new Error(`خطای ارتباط با سرور (${joinRes.status})`);
390
+ let filePath = null; const start = Date.now();
391
+ while (Date.now() - start < 90000) {
392
+ const dataRes = await fetch(`${GET_DATA_URL_BASE}?session_hash=${payload.session_hash}`);
393
+ if (!dataRes.ok) throw new Error(`خطای دریافت داده (${dataRes.status})`);
394
+ const lines = (await dataRes.text()).trim().split('\n');
395
  for (const line of lines) {
396
  if (!line.startsWith('data:')) continue;
397
  try {
398
  const data = JSON.parse(line.substring(5));
399
  if (data.msg === 'process_completed') {
400
+ if (data.success && data.output?.data?.[0]?.name) { filePath = data.output.data[0].name; } else { throw new Error(data.output?.error || 'خطای پردازش در سرور.'); }
401
  break;
402
+ } else if (data.msg === 'queue_full') { throw new Error('صف پردازش پر است، لطفا بعدا تلاش کنید.'); }
403
+ } catch (e) { console.warn("JSON Parse Error:", e, line); }
404
  }
405
+ if (filePath) break;
406
+ await new Promise(r => setTimeout(r, 1000));
407
  }
408
+ if (filePath) { dom.hiddenAudioPlayer.src = `${FILE_URL_BASE}${filePath}`; showResultState(true); } else { throw new Error('زمان پردازش تمام شد یا فایلی دریافت نشد.'); }
409
+ } catch (error) { console.error('Audio Generation Error:', error); showResultState(false, error.message); }
410
  }
411
 
412
+ const defaultId = speakers.length > 0 ? speakers[0].id : "Charon";
413
+ updateSelectedSpeakerDisplay(dom.selectedSpeakerIdStorage.value || defaultId);
414
+ dom.form.addEventListener('submit', generateAudio);
415
+ dom.statusMessage.style.display = 'block'; dom.loadingAnimationWrapper.style.display = 'none';
416
+ dom.audioPlayerContent.style.display = 'none'; dom.outputSection.classList.remove('has-content');
 
417
  });
418
  </script>
419
  </body>