Update Yek.html
Browse files
Yek.html
CHANGED
@@ -8,7 +8,7 @@
|
|
8 |
@import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;600;700;800;900&display=swap');
|
9 |
|
10 |
:root {
|
11 |
-
/* ---
|
12 |
--app-font: 'Vazirmatn', sans-serif;
|
13 |
--app-bg: #F8F9FC;
|
14 |
--panel-bg: #FFFFFF;
|
@@ -303,7 +303,38 @@
|
|
303 |
const FILE_URL_BASE = `${HF_SPACE_URL}/gradio_api/file=`;
|
304 |
const FN_INDEX = 1;
|
305 |
|
306 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
307 |
|
308 |
// --- DOM Elements ---
|
309 |
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');
|
@@ -315,147 +346,207 @@
|
|
315 |
textInput.addEventListener('input', () => { const currentLength = textInput.value.length; charCountSpan.textContent = currentLength.toLocaleString('fa-IR'); charCountSpan.style.color = currentLength > MAX_CHARS ? 'red' : 'var(--accent-primary)'; });
|
316 |
|
317 |
// --- Speaker Logic ---
|
318 |
-
const getSpeakerById = (id) => speakers.find(s => s.id === id) || speakers[0];
|
319 |
-
const
|
|
|
|
|
|
|
320 |
|
321 |
// --- Modal Management ---
|
322 |
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; });
|
323 |
|
324 |
-
// --- Original Audio Player Logic ---
|
325 |
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}`; };
|
326 |
|
327 |
function drawWaveform(progressRatio = 0) {
|
328 |
-
|
329 |
-
|
330 |
-
|
331 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
332 |
|
333 |
-
|
334 |
-
const height = audioWaveformCanvas.offsetHeight;
|
335 |
|
336 |
-
|
337 |
-
|
338 |
-
|
339 |
-
|
340 |
-
|
341 |
-
|
342 |
-
|
343 |
-
|
344 |
-
|
345 |
-
|
346 |
-
|
347 |
-
|
348 |
-
|
349 |
-
|
350 |
-
|
351 |
-
|
352 |
-
|
353 |
-
|
354 |
-
|
355 |
-
}
|
356 |
}
|
357 |
|
358 |
-
const updatePlayerUI = () => {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
359 |
|
360 |
async function processAudioForWaveform(audioBuffer) {
|
361 |
if (!audioBuffer) { audioPeaks = []; return; }
|
362 |
const channelData = audioBuffer.getChannelData(0);
|
|
|
363 |
const numBars = Math.floor(audioWaveformCanvas.offsetWidth / 5); // 5 = barWidth(3) + barGap(2)
|
364 |
const samplesPerBar = Math.floor(channelData.length / numBars);
|
365 |
const peaks = [];
|
366 |
for (let i = 0; i < numBars; i++) {
|
367 |
let maxPeak = 0;
|
368 |
const start = i * samplesPerBar;
|
369 |
-
|
370 |
-
|
|
|
|
|
371 |
if (value > maxPeak) maxPeak = value;
|
372 |
}
|
373 |
-
peaks.push(Math.min(1, Math.max(0, maxPeak * 1.5)));
|
374 |
}
|
375 |
audioPeaks = peaks;
|
376 |
-
|
|
|
377 |
}
|
378 |
|
379 |
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));
|
380 |
volumeBtn.addEventListener('click', () => { hiddenAudioPlayer.muted = !hiddenAudioPlayer.muted; volumeHighIcon.style.display = hiddenAudioPlayer.muted ? 'none' : 'block'; volumeMuteIcon.style.display = hiddenAudioPlayer.muted ? 'block' : 'none'; });
|
381 |
speedBtn.addEventListener('click', () => { currentPlaybackSpeedIndex = (currentPlaybackSpeedIndex + 1) % playbackSpeeds.length; const newSpeed = playbackSpeeds[currentPlaybackSpeedIndex]; hiddenAudioPlayer.playbackRate = newSpeed; speedBtn.textContent = `${newSpeed}x`; });
|
382 |
hiddenAudioPlayer.addEventListener('timeupdate', updatePlayerUI); hiddenAudioPlayer.addEventListener('play', updatePlayerUI); hiddenAudioPlayer.addEventListener('pause', updatePlayerUI); hiddenAudioPlayer.addEventListener('ended', () => { hiddenAudioPlayer.currentTime = 0; updatePlayerUI(); });
|
383 |
-
|
384 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
385 |
|
386 |
// --- State Management Functions ---
|
387 |
-
const showLoadingState = () => {
|
388 |
-
|
389 |
-
|
390 |
-
|
391 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
392 |
};
|
393 |
-
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 = []; drawWaveform(0); } generateBtn.disabled = false; generateBtn.innerHTML = '✨ خلق صدا با آلفا'; };
|
394 |
|
395 |
// --- API Call ---
|
396 |
async function generateAudio(event) {
|
397 |
-
event.preventDefault();
|
398 |
-
showLoadingState();
|
399 |
-
|
400 |
const text = textInput.value;
|
401 |
if (!text.trim()) { showResultState(false, 'خطا: متن ورودی نمیتواند خالی باشد.'); return; }
|
402 |
if (text.length > MAX_CHARS) { showResultState(false, `خطا: طول متن بیش از ${MAX_CHARS.toLocaleString('fa-IR')} نویسه است.`); return; }
|
403 |
-
|
404 |
-
const payload = {
|
405 |
-
fn_index: FN_INDEX,
|
406 |
-
data: [false, null, text, promptInput.value, selectedSpeakerIdStorage.value, parseFloat(tempSlider.value)],
|
407 |
-
event_data: null,
|
408 |
-
session_hash: Math.random().toString(36).substring(2)
|
409 |
-
};
|
410 |
-
|
411 |
try {
|
412 |
const joinQueueResponse = await fetch(JOIN_QUEUE_URL, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) });
|
413 |
if (!joinQueueResponse.ok) { throw new Error(`خطا در برقراری ارتباط با سرویس آلفا (کد: ${joinQueueResponse.status}).`); }
|
414 |
-
|
415 |
-
let finalFilePath = null;
|
416 |
-
const startTime = Date.now();
|
417 |
-
const timeoutDuration = 90000;
|
418 |
-
|
419 |
while (Date.now() - startTime < timeoutDuration) {
|
420 |
const dataResponse = await fetch(`${GET_DATA_URL_BASE}?session_hash=${payload.session_hash}`);
|
421 |
if (!dataResponse.ok) { throw new Error(`خطا در دریافت داده از سرویس (کد: ${dataResponse.status})`); }
|
422 |
-
const responseText = await dataResponse.text();
|
423 |
-
const lines = responseText.trim().split('\n');
|
424 |
-
|
425 |
for (const line of lines) {
|
426 |
if (!line.startsWith('data:')) continue;
|
427 |
try {
|
428 |
const data = JSON.parse(line.substring(5));
|
429 |
if (data.msg === 'process_completed') {
|
430 |
-
if (data.success && data.output?.data?.[0] && (data.output.data[0].name || data.output.data[0].path)) {
|
431 |
-
finalFilePath = data.output.data[0].name || data.output.data[0].path;
|
432 |
-
} else { throw new Error(data.output?.error || 'خطای ناشناخته در پردازش سرور.'); }
|
433 |
break;
|
434 |
-
} else if (data.msg === 'queue_full') {
|
435 |
-
throw new Error('صف پردازش پر است. لطفا کمی بعد تلاش کنید.');
|
436 |
-
}
|
437 |
} catch (e) { console.warn("Error parsing JSON from stream:", e, "Line:", line); }
|
438 |
}
|
439 |
if (finalFilePath) break;
|
440 |
await new Promise(resolve => setTimeout(resolve, 1000));
|
441 |
}
|
442 |
-
|
443 |
if (finalFilePath) {
|
444 |
-
|
|
|
|
|
|
|
|
|
445 |
showResultState(true);
|
446 |
} else if (Date.now() - startTime >= timeoutDuration) {
|
447 |
throw new Error('پردازش بیش از حد طول کشید و متوقف شد.');
|
448 |
} else {
|
449 |
throw new Error('فایل صوتی از سرور دریافت نشد یا پردازش ناموفق بود.');
|
450 |
}
|
451 |
-
} catch (error) {
|
452 |
-
console.error('خطا در فرآیند تولید صدا:', error);
|
453 |
-
showResultState(false, error.message);
|
454 |
-
}
|
455 |
}
|
456 |
|
457 |
// --- Initial Setup ---
|
458 |
-
|
|
|
459 |
form.addEventListener('submit', generateAudio);
|
460 |
statusMessage.style.display = 'block'; loadingAnimationWrapper.style.display = 'none';
|
461 |
audioPlayerContent.style.display = 'none'; outputSection.classList.remove('has-content');
|
|
|
8 |
@import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;600;700;800;900&display=swap');
|
9 |
|
10 |
:root {
|
11 |
+
/* --- Light Theme Palette --- */
|
12 |
--app-font: 'Vazirmatn', sans-serif;
|
13 |
--app-bg: #F8F9FC;
|
14 |
--panel-bg: #FFFFFF;
|
|
|
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');
|
|
|
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 |
+
const dpr = window.devicePixelRatio || 1;
|
363 |
+
audioWaveformCanvas.width = audioWaveformCanvas.offsetWidth * dpr;
|
364 |
+
audioWaveformCanvas.height = audioWaveformCanvas.offsetHeight * dpr;
|
365 |
+
waveformCtx.scale(dpr, dpr);
|
366 |
+
|
367 |
+
const width = audioWaveformCanvas.offsetWidth;
|
368 |
+
const height = audioWaveformCanvas.offsetHeight;
|
369 |
+
|
370 |
+
if (width === 0 || height === 0) return; // Extra safety check: Don't draw if canvas has no dimensions
|
371 |
+
|
372 |
+
waveformCtx.clearRect(0, 0, width, height);
|
373 |
+
|
374 |
+
const barWidth = 3; const barGap = 2; const totalBarAndGap = barWidth + barGap;
|
375 |
+
const numBars = Math.floor(width / totalBarAndGap);
|
376 |
+
const offset = (width - (numBars * totalBarAndGap)) / 2;
|
377 |
+
|
378 |
+
const activeColor = getComputedStyle(document.documentElement).getPropertyValue('--waveform-color-active').trim();
|
379 |
+
const inactiveColor = getComputedStyle(document.documentElement).getPropertyValue('--waveform-color-inactive').trim();
|
380 |
+
|
381 |
+
// 1. Draw the entire waveform with the inactive color (as the base)
|
382 |
+
waveformCtx.fillStyle = inactiveColor;
|
383 |
+
for (let i = 0; i < numBars; i++) {
|
384 |
+
const peak = audioPeaks[i] || 0;
|
385 |
+
const barHeight = peak * height;
|
386 |
+
const x = offset + i * totalBarAndGap;
|
387 |
+
const y = (height - barHeight) / 2;
|
388 |
+
waveformCtx.fillRect(x, y, barWidth, barHeight);
|
389 |
+
}
|
390 |
+
|
391 |
+
// 2. Create a linear gradient for the active part
|
392 |
+
const activeFillEnd = progressRatio * width; // The absolute pixel position of the playback head
|
393 |
+
const gradientFadeWidth = 80; // The width of the smooth transition zone in pixels
|
394 |
+
const gradientSolidStart = Math.max(0, activeFillEnd - gradientFadeWidth); // Where active color is fully solid
|
395 |
|
396 |
+
const activeGradient = waveformCtx.createLinearGradient(0, 0, width, 0);
|
|
|
397 |
|
398 |
+
// Solid active color from left to gradientSolidStart
|
399 |
+
activeGradient.addColorStop(0, activeColor);
|
400 |
+
activeGradient.addColorStop(gradientSolidStart / width, activeColor);
|
401 |
+
|
402 |
+
// Transition from active color to inactive color, ending at activeFillEnd
|
403 |
+
activeGradient.addColorStop(activeFillEnd / width, inactiveColor);
|
404 |
+
|
405 |
+
// 3. Apply this gradient as the fillStyle
|
406 |
+
waveformCtx.fillStyle = activeGradient;
|
407 |
+
|
408 |
+
// 4. Draw the waveform again on top. The gradient will automatically apply
|
409 |
+
// to each bar based on its X position on the canvas, creating a smooth sweep effect.
|
410 |
+
for (let i = 0; i < numBars; i++) {
|
411 |
+
const peak = audioPeaks[i] || 0;
|
412 |
+
const barHeight = peak * height;
|
413 |
+
const x = offset + i * totalBarAndGap;
|
414 |
+
const y = (height - barHeight) / 2;
|
415 |
+
waveformCtx.fillRect(x, y, barWidth, barHeight);
|
416 |
+
}
|
|
|
417 |
}
|
418 |
|
419 |
+
const updatePlayerUI = () => {
|
420 |
+
playIcon.style.display = hiddenAudioPlayer.paused || hiddenAudioPlayer.ended ? 'block' : 'none';
|
421 |
+
pauseIcon.style.display = !(hiddenAudioPlayer.paused || hiddenAudioPlayer.ended) ? 'block' : 'none';
|
422 |
+
const currentTime = hiddenAudioPlayer.currentTime;
|
423 |
+
const duration = hiddenAudioPlayer.duration;
|
424 |
+
audioCurrentTimeSpan.textContent = formatTime(currentTime);
|
425 |
+
if (isFinite(duration) && duration > 0) {
|
426 |
+
audioTotalTimeSpan.textContent = formatTime(duration);
|
427 |
+
// Schedule waveform redraw on the next animation frame
|
428 |
+
requestAnimationFrame(() => drawWaveform(currentTime / duration));
|
429 |
+
} else {
|
430 |
+
audioTotalTimeSpan.textContent = '0:00';
|
431 |
+
requestAnimationFrame(() => drawWaveform(0));
|
432 |
+
}
|
433 |
+
};
|
434 |
|
435 |
async function processAudioForWaveform(audioBuffer) {
|
436 |
if (!audioBuffer) { audioPeaks = []; return; }
|
437 |
const channelData = audioBuffer.getChannelData(0);
|
438 |
+
// Calculate numBars based on current visual width of the canvas
|
439 |
const numBars = Math.floor(audioWaveformCanvas.offsetWidth / 5); // 5 = barWidth(3) + barGap(2)
|
440 |
const samplesPerBar = Math.floor(channelData.length / numBars);
|
441 |
const peaks = [];
|
442 |
for (let i = 0; i < numBars; i++) {
|
443 |
let maxPeak = 0;
|
444 |
const start = i * samplesPerBar;
|
445 |
+
// Ensure we don't read beyond the array bounds
|
446 |
+
const end = Math.min(start + samplesPerBar, channelData.length);
|
447 |
+
for (let j = start; j < end; j++) {
|
448 |
+
const value = Math.abs(channelData[j]);
|
449 |
if (value > maxPeak) maxPeak = value;
|
450 |
}
|
451 |
+
peaks.push(Math.min(1, Math.max(0, maxPeak * 1.5))); // Amplify for better visuals
|
452 |
}
|
453 |
audioPeaks = peaks;
|
454 |
+
// Draw initial waveform on the next available frame to ensure canvas is ready
|
455 |
+
requestAnimationFrame(() => drawWaveform(0));
|
456 |
}
|
457 |
|
458 |
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));
|
459 |
volumeBtn.addEventListener('click', () => { hiddenAudioPlayer.muted = !hiddenAudioPlayer.muted; volumeHighIcon.style.display = hiddenAudioPlayer.muted ? 'none' : 'block'; volumeMuteIcon.style.display = hiddenAudioPlayer.muted ? 'block' : 'none'; });
|
460 |
speedBtn.addEventListener('click', () => { currentPlaybackSpeedIndex = (currentPlaybackSpeedIndex + 1) % playbackSpeeds.length; const newSpeed = playbackSpeeds[currentPlaybackSpeedIndex]; hiddenAudioPlayer.playbackRate = newSpeed; speedBtn.textContent = `${newSpeed}x`; });
|
461 |
hiddenAudioPlayer.addEventListener('timeupdate', updatePlayerUI); hiddenAudioPlayer.addEventListener('play', updatePlayerUI); hiddenAudioPlayer.addEventListener('pause', updatePlayerUI); hiddenAudioPlayer.addEventListener('ended', () => { hiddenAudioPlayer.currentTime = 0; updatePlayerUI(); });
|
462 |
+
|
463 |
+
// IMPORTANT: Modified loadedmetadata listener for robust waveform display
|
464 |
+
hiddenAudioPlayer.addEventListener('loadedmetadata', async () => {
|
465 |
+
if (!audioContext) audioContext = new (window.AudioContext || window.webkitAudioContext)();
|
466 |
+
if (!hiddenAudioPlayer.src) { // If src is empty, clear waveform
|
467 |
+
audioPeaks = [];
|
468 |
+
requestAnimationFrame(() => drawWaveform(0));
|
469 |
+
updatePlayerUI();
|
470 |
+
return;
|
471 |
+
}
|
472 |
+
try {
|
473 |
+
const response = await fetch(hiddenAudioPlayer.src);
|
474 |
+
const arrayBuffer = await response.arrayBuffer();
|
475 |
+
const decodedBuffer = await audioContext.decodeAudioData(arrayBuffer);
|
476 |
+
await processAudioForWaveform(decodedBuffer);
|
477 |
+
} catch (e) {
|
478 |
+
console.error("Error decoding audio for waveform:", e);
|
479 |
+
audioPeaks = [];
|
480 |
+
requestAnimationFrame(() => drawWaveform(0)); // Ensure canvas is cleared on error
|
481 |
+
}
|
482 |
+
updatePlayerUI();
|
483 |
+
});
|
484 |
+
|
485 |
+
let resizeTimeout; window.addEventListener('resize', () => { clearTimeout(resizeTimeout); resizeTimeout = setTimeout(() => { if (outputSection.classList.contains('has-content') && hiddenAudioPlayer.src) { requestAnimationFrame(() => drawWaveform(hiddenAudioPlayer.currentTime / hiddenAudioPlayer.duration)); } }, 250); });
|
486 |
|
487 |
// --- State Management Functions ---
|
488 |
+
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> در حال پردازش... `; };
|
489 |
+
const showResultState = (isSuccess, message = '') => {
|
490 |
+
loadingAnimationWrapper.style.display = 'none';
|
491 |
+
if (isSuccess) {
|
492 |
+
statusMessage.style.display = 'none'; audioPlayerContent.style.display = 'flex';
|
493 |
+
outputSection.classList.add('has-content');
|
494 |
+
} else {
|
495 |
+
statusMessage.textContent = message || 'خطایی رخ داد. لطفاً دوباره تلاش کنید.';
|
496 |
+
statusMessage.style.display = 'block'; audioPlayerContent.style.display = 'none';
|
497 |
+
outputSection.classList.remove('has-content');
|
498 |
+
hiddenAudioPlayer.src = ''; // Clear src on error
|
499 |
+
audioPeaks = []; requestAnimationFrame(() => drawWaveform(0)); // Clear waveform
|
500 |
+
}
|
501 |
+
generateBtn.disabled = false; generateBtn.innerHTML = '✨ خلق صدا با آلفا';
|
502 |
};
|
|
|
503 |
|
504 |
// --- API Call ---
|
505 |
async function generateAudio(event) {
|
506 |
+
event.preventDefault(); showLoadingState();
|
|
|
|
|
507 |
const text = textInput.value;
|
508 |
if (!text.trim()) { showResultState(false, 'خطا: متن ورودی نمیتواند خالی باشد.'); return; }
|
509 |
if (text.length > MAX_CHARS) { showResultState(false, `خطا: طول متن بیش از ${MAX_CHARS.toLocaleString('fa-IR')} نویسه است.`); return; }
|
510 |
+
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) };
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
511 |
try {
|
512 |
const joinQueueResponse = await fetch(JOIN_QUEUE_URL, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) });
|
513 |
if (!joinQueueResponse.ok) { throw new Error(`خطا در برقراری ارتباط با سرویس آلفا (کد: ${joinQueueResponse.status}).`); }
|
514 |
+
let finalFilePath = null; const startTime = Date.now(); const timeoutDuration = 90000;
|
|
|
|
|
|
|
|
|
515 |
while (Date.now() - startTime < timeoutDuration) {
|
516 |
const dataResponse = await fetch(`${GET_DATA_URL_BASE}?session_hash=${payload.session_hash}`);
|
517 |
if (!dataResponse.ok) { throw new Error(`خطا در دریافت داده از سرویس (کد: ${dataResponse.status})`); }
|
518 |
+
const responseText = await dataResponse.text(); const lines = responseText.trim().split('\n');
|
|
|
|
|
519 |
for (const line of lines) {
|
520 |
if (!line.startsWith('data:')) continue;
|
521 |
try {
|
522 |
const data = JSON.parse(line.substring(5));
|
523 |
if (data.msg === 'process_completed') {
|
524 |
+
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 || 'خطای ناشناخته در پردازش سرور.'); }
|
|
|
|
|
525 |
break;
|
526 |
+
} else if (data.msg === 'queue_full') { throw new Error('صف پردازش پر است. لطفا کمی بعد تلاش کنید.'); }
|
|
|
|
|
527 |
} catch (e) { console.warn("Error parsing JSON from stream:", e, "Line:", line); }
|
528 |
}
|
529 |
if (finalFilePath) break;
|
530 |
await new Promise(resolve => setTimeout(resolve, 1000));
|
531 |
}
|
|
|
532 |
if (finalFilePath) {
|
533 |
+
// Force reload for robust waveform generation
|
534 |
+
hiddenAudioPlayer.src = ''; // Clear current source
|
535 |
+
hiddenAudioPlayer.load(); // Request browser to load it
|
536 |
+
hiddenAudioPlayer.src = `${FILE_URL_BASE}${finalFilePath}`; // Set new source
|
537 |
+
// loadedmetadata event listener will now handle processing and drawing
|
538 |
showResultState(true);
|
539 |
} else if (Date.now() - startTime >= timeoutDuration) {
|
540 |
throw new Error('پردازش بیش از حد طول کشید و متوقف شد.');
|
541 |
} else {
|
542 |
throw new Error('فایل صوتی از سرور دریافت نشد یا پردازش ناموفق بود.');
|
543 |
}
|
544 |
+
} catch (error) { console.error('خطا در فرآیند تولید صدا:', error); showResultState(false, error.message); }
|
|
|
|
|
|
|
545 |
}
|
546 |
|
547 |
// --- Initial Setup ---
|
548 |
+
const defaultSpeakerId = speakers.length > 0 ? speakers[0].id : "Charon";
|
549 |
+
updateSelectedSpeakerDisplay(selectedSpeakerIdStorage.value || defaultSpeakerId);
|
550 |
form.addEventListener('submit', generateAudio);
|
551 |
statusMessage.style.display = 'block'; loadingAnimationWrapper.style.display = 'none';
|
552 |
audioPlayerContent.style.display = 'none'; outputSection.classList.remove('has-content');
|