Text to vertical video in 100+ styles: AI codes each scene (HTML/SVG/WebGL), renders a 9:16 MP4 with music and English/Vietnamese voice. MCP, CLI and REST for AI agents.
// Khối "Âm thanh": (1) trong form dựng — chọn nhạc nền, giọng đọc, tiếng động (có nút nghe thử);
// (2) trong mỗi video đã dựng — đổi nhạc/giọng/tiếng động rồi trộn bản tiếng mới (không dựng lại hình), xem/tải các bản.
// Tự chứa: tự nạp CSS, tự gắn vào #audioPanel và các thẻ .job trong #jobs. app.js chỉ đọc window.LumAudio.value().
(() => {
const $ = (s, el = document) => el.querySelector(s);
const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
const I = window.I18N;
const t = (k, v) => I.t(k, v);
const srv = (s) => I.srv(s);
const css = document.createElement('link');
css.rel = 'stylesheet'; css.href = '/audio-panel.css';
document.head.appendChild(css);
let opts = null;
const loadOpts = () => fetch('/api/audio/options').then((r) => r.json()).then((o) => (opts = o)).catch(() => null);
const optsP = loadOpts();
// ---------- nghe thử (1 trình phát chung) ----------
const player = new Audio();
let playingBtn = null;
const ICON_PLAY = '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M7 4v16l13-8z"/></svg>';
const ICON_STOP = '<svg viewBox="0 0 24 24" aria-hidden="true"><rect x="6" y="6" width="12" height="12" rx="2"/></svg>';
function setBtn(btn, state) {
if (!btn) return;
btn.dataset.state = state;
btn.innerHTML = state === 'play' ? ICON_STOP : state === 'load' ? '<span class="ap-spin" aria-hidden="true"></span>' : ICON_PLAY;
btn.setAttribute('aria-label', state === 'play' ? t('ap.stop') : state === 'load' ? t('ap.making') : t(btn.dataset.label));
}
player.addEventListener('ended', () => { setBtn(playingBtn, 'idle'); playingBtn = null; });
async function preview(btn, url, note) {
if (playingBtn === btn) { player.pause(); setBtn(btn, 'idle'); playingBtn = null; return; }
if (playingBtn) { player.pause(); setBtn(playingBtn, 'idle'); }
playingBtn = btn; setBtn(btn, 'load');
if (note) note.textContent = url.includes('voice=') ? t('ap.voiceLoading') : '';
try {
const r = await fetch(url);
if (!r.ok) throw new Error((await r.json().catch(() => ({}))).error || t('ap.prevFail'));
const blob = await r.blob();
if (playingBtn !== btn) return;
player.src = URL.createObjectURL(blob);
await player.play();
setBtn(btn, 'play');
if (note) note.textContent = '';
} catch (e) {
setBtn(btn, 'idle'); playingBtn = null;
if (note) note.textContent = t('ap.prevErr') + e.message;
}
}
// ---------- 3 điều khiển dùng chung ----------
let uid = 0;
function controlsHtml(cur = {}, { keepLabel = false } = {}) {
const id = 'ap' + (++uid);
const keep = keepLabel ? `<option value="">${esc(t('ap.keep'))}</option>` : '';
const music = (opts?.music || [{ id: 'auto', name: 'Tự chọn theo mẫu' }]).map((m) =>
`<option value="${esc(m.id)}" ${cur.music === m.id ? 'selected' : ''}>${esc(m.id === 'auto' || m.id === 'none' ? srv(m.name) : m.id + ' — ' + srv(m.desc || ''))}</option>`).join('');
// giọng nhóm theo ngôn ngữ (<optgroup> Tiếng Việt / English); auto/none đứng đầu, không nhóm.
// Giọng Anh đã có vùng + giới trong tên ("Heart (US, nữ)") nên chỉ thêm kiểu giọng.
const vOpt = (v) => `<option value="${esc(v.id)}" ${cur.voice === v.id ? 'selected' : ''}>${esc(!v.engine ? srv(v.name)
: v.lang === 'en' ? `${srv(v.name)} · ${srv(v.style)}` : `${v.name} · ${srv(v.gender)}, ${srv(v.region)} · ${srv(v.style)}`)}</option>`;
const allV = opts?.voices || [{ id: 'auto', name: 'Theo mẫu (chỉ đọc khi mẫu có lời)' }];
const langs = opts?.langs || [{ id: 'vi', name: 'Tiếng Việt' }, { id: 'en', name: 'English' }];
// "Giọng của tôi" (giọng nhân bản, v.mine) đứng nhóm riêng, trước các nhóm ngôn ngữ
const mine = allV.filter((v) => v.mine);
const mineOpt = (v) => `<option value="${esc(v.id)}" ${cur.voice === v.id ? 'selected' : ''}>${esc(v.name)} · ${esc(t('vc.optTag'))}</option>`;
const voices = allV.filter((v) => !v.engine).map(vOpt).join('')
+ (mine.length ? `<optgroup label="${esc(t('vc.title'))}">${mine.map(mineOpt).join('')}</optgroup>` : '') + langs.map((l) => {
const vs = allV.filter((v) => v.engine && !v.mine && (v.lang || 'vi') === l.id);
return vs.length ? `<optgroup label="${esc(srv(l.name))}">${vs.map(vOpt).join('')}</optgroup>` : '';
}).join('');
return `
<label class="field" for="${id}m">${esc(t('ap.music'))}</label>
<div class="ap-row"><select id="${id}m" data-ap="music">${keep}${music}</select>
<button type="button" class="ap-play" data-prev="music" data-label="ap.musicPrev" aria-label="${esc(t('ap.musicPrev'))}">${ICON_PLAY}</button></div>
<label class="field" for="${id}v">${esc(t('ap.voice'))}</label>
<div class="ap-row"><select id="${id}v" data-ap="voice">${keep}${voices}</select>
<button type="button" class="ap-play" data-prev="voice" data-label="ap.voicePrev" aria-label="${esc(t('ap.voicePrev'))}">${ICON_PLAY}</button></div>
<label class="ap-switch"><input type="checkbox" data-ap="sfx" ${cur.sfx === false ? '' : 'checked'} /><span class="ap-knob" aria-hidden="true"></span> ${esc(t('ap.sfx'))}</label>
${(opts?.hints || (opts?.hint ? [opts.hint] : [])).map((h) => `<div class="hint ap-hint">${esc(srv(h))}</div>`).join('')}
<div class="hint ap-note" aria-live="polite"></div>`;
}
function readControls(box) {
const m = $('[data-ap="music"]', box).value, v = $('[data-ap="voice"]', box).value;
return { music: m || undefined, voice: v || undefined, sfx: $('[data-ap="sfx"]', box).checked };
}
function wirePreview(box) {
box.addEventListener('click', (e) => {
const b = e.target.closest('.ap-play'); if (!b) return;
const note = $('.ap-note', box);
if (b.dataset.prev === 'music') {
const s = $('[data-ap="music"]', box).value;
if (!s || s === 'auto' || s === 'none') { note.textContent = t('ap.pickMusic'); return; }
preview(b, '/api/audio/preview?style=' + encodeURIComponent(s), note);
} else {
const v = $('[data-ap="voice"]', box).value;
if (!v || v === 'auto' || v === 'none') { note.textContent = t('ap.pickVoice'); return; }
preview(b, '/api/audio/preview?voice=' + encodeURIComponent(v), note);
}
});
}
// ---------- (1) form dựng ----------
const mount = document.getElementById('audioPanel');
/** Vẽ lại form dựng với lựa chọn cur; gắn lại khối "Giọng của tôi" (voice-clone.js) ngay dưới ô giọng đọc. */
function renderMount(cur) {
mount.innerHTML = `<div class="ap-title">${esc(t('ap.title'))}</div>` + controlsHtml(cur);
attachVoices();
}
function attachVoices() {
const vc = window.LumVoices?.el;
if (!mount || !vc) return;
const row = $('[data-ap="voice"]', mount)?.closest('.ap-row');
if (row) row.after(vc);
}
if (mount) {
mount.classList.add('ap');
mount.innerHTML = `<div class="ap-title">${esc(t('ap.title'))}</div><div class="hint">${esc(t('ap.loadingOpts'))}</div>`;
optsP.then(() => renderMount({ music: 'auto', voice: 'auto', sfx: true }));
wirePreview(mount);
}
window.LumAudio = {
/** Giá trị cho POST /api/jobs: { music, voice, sfx }. */
value: () => (mount && $('[data-ap="music"]', mount) ? readControls(mount) : undefined),
/** Tải lại danh sách giọng (sau khi thêm/xoá/đổi tên giọng nhân bản). selectVoice: chọn luôn giọng này. */
reload: async (selectVoice) => {
await loadOpts();
if (mount && $('[data-ap="music"]', mount)) {
const cur = readControls(mount);
if (selectVoice) cur.voice = selectVoice;
renderMount(cur);
}
},
attachVoices,
};
// ---------- (2) mỗi video đã dựng ----------
const VOICE_NAME = (id) => (id === 'auto' ? t('ap.vAuto') : id === 'none' ? t('ap.vNone') : srv((opts?.voices || []).find((v) => v.id === id)?.name || id));
function versionsHtml(j) {
const vs = j.versions || [];
if (vs.length < 2) return '';
return `<div class="ap-vers"><div class="ap-sub">${esc(t('ap.versions', { n: vs.length }))}</div>${vs.map((v) => `
<div class="ap-ver ${v.current ? 'cur' : ''}"><span>${esc(t('ap.ver', { n: v.n }))}${v.current ? esc(t('ap.latest')) : ''}${v.audio ? ` · ${esc(v.audio.music)} · ${esc(VOICE_NAME(v.audio.voice))}${v.audio.sfx === false ? esc(t('ap.noSfx')) : ''}` : ''}</span>
<button type="button" class="mini" data-ver="${esc(v.url)}">${esc(t('ap.view'))}</button><a class="mini" href="${esc(v.url)}" download>${esc(t('ap.dl'))}</a></div>`).join('')}</div>`;
}
// cur: giữ lựa chọn đang có trên form (khi đổi ngôn ngữ), không thì lấy theo job.
async function fillJob(details, id, cur) {
await optsP;
const j = await (await fetch('/api/jobs/' + id)).json();
const body = $('.ap-body', details);
body.innerHTML = controlsHtml(cur || (j.audio && typeof j.audio === 'object' ? j.audio : {}), { keepLabel: false })
+ `<button type="button" class="ap-go" data-mix>${esc(t('ap.mix'))}</button>
<div class="hint">${esc(t('ap.mixNote'))}</div>`
+ (j.audioStatus === 'error' && j.audioError ? `<div class="errmsg">${esc(t('ap.lastErr'))}${esc(j.audioError)}</div>` : '')
+ `<div class="ap-verbox">${versionsHtml(j)}</div>`;
body.dataset.ready = '1';
if (j.audioBusy || j.audioStatus === 'mixing') watch(details, id);
}
function watch(details, id) {
const btn = $('[data-mix]', details), note = $('.ap-note', details);
if (btn) { btn.disabled = true; btn.textContent = t('ap.mixing'); }
if (note) note.textContent = t('ap.mixingNote');
const tick = async () => {
const j = await (await fetch('/api/jobs/' + id)).json().catch(() => null);
if (j && (j.audioBusy || j.audioStatus === 'mixing')) return setTimeout(tick, 3000);
if (btn) { btn.disabled = false; btn.textContent = t('ap.mix'); }
if (!j) return;
if (j.audioStatus === 'error') { if (note) note.textContent = t('ap.err') + (j.audioError || t('ap.unknown')); return; }
if (note) note.textContent = t('ap.done');
const card = document.getElementById('job-' + id), vid = card && $('.media video', card);
if (vid) { vid.src = `/jobs/${id}/out.mp4?v=${Date.now()}`; vid.load(); }
const vb = $('.ap-verbox', details); if (vb) vb.innerHTML = versionsHtml(j);
};
setTimeout(tick, 2000);
}
function enhance(card) {
if (card.querySelector('.ap-job')) return;
const id = card.id.replace(/^job-/, '');
const hasVideo = card.querySelector('.media video');
if (!hasVideo) return;
const d = document.createElement('details');
d.className = 'ap-job';
d.innerHTML = `<summary>${esc(t('ap.summary'))}</summary><div class="ap-body"><div class="hint">${esc(t('ap.loading'))}</div></div>`;
d.addEventListener('toggle', () => { if (d.open && !$('.ap-body', d).dataset.ready) fillJob(d, id); });
wirePreview(d);
d.addEventListener('click', async (e) => {
const ver = e.target.closest('[data-ver]');
if (ver) { const vid = $('.media video', card); if (vid) { vid.src = ver.dataset.ver + '?v=' + Date.now(); vid.play().catch(() => {}); } return; }
if (!e.target.closest('[data-mix]')) return;
const note = $('.ap-note', d);
try {
const r = await fetch(`/api/jobs/${id}/audio`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(readControls(d)) });
const j = await r.json();
if (!r.ok) throw new Error(j.error || t('ap.errShort'));
watch(d, id);
} catch (err) { note.textContent = t('ap.mixFail') + err.message; }
});
const host = card.querySelector('.links') || card.lastElementChild;
host.insertAdjacentElement('afterend', d);
}
const jobs = document.getElementById('jobs');
if (jobs) {
const scan = () => jobs.querySelectorAll('article.job').forEach(enhance);
new MutationObserver(scan).observe(jobs, { childList: true });
scan();
}
// Đổi VI/EN: vẽ lại khối âm thanh, giữ lựa chọn đang chọn.
window.addEventListener('lumreels:lang', () => {
if (mount) {
const title = `<div class="ap-title">${esc(t('ap.title'))}</div>`;
if ($('[data-ap="music"]', mount)) renderMount(readControls(mount)); else mount.innerHTML = title + `<div class="hint">${esc(t('ap.loadingOpts'))}</div>`;
}
document.querySelectorAll('details.ap-job').forEach((d) => {
const sum = $('summary', d); if (sum) sum.textContent = t('ap.summary');
const body = $('.ap-body', d);
const card = d.closest('article.job');
if (body?.dataset.ready && card && $('[data-ap="music"]', d)) fillJob(d, card.id.replace(/^job-/, ''), readControls(d));
else if (body && !body.dataset.ready) body.innerHTML = `<div class="hint">${esc(t('ap.loading'))}</div>`;
});
});
})();