1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
| window.addEventListener("DOMContentLoaded", () => { const canvas = document.getElementById("live2d-canvas"); const messagesEl = document.getElementById("messages"); const inputEl = document.getElementById("user-input"); const sendBtn = document.getElementById("send-btn");
// 全域 addMessage(chat 用) window.addMessage = (text, type = "bot") => { const div = document.createElement("div"); div.textContent = text; div.className = type === "user" ? "msg-user" : "msg-bot"; messagesEl.appendChild(div); messagesEl.scrollTop = messagesEl.scrollHeight; };
window.PIXI = PIXI;
const app = new PIXI.Application({ view: canvas, transparent: true, autoStart: true, resizeTo: window });
let model = null; // === Web Audio 分析器 === let audioContext = null; let analyser = null; let dataArray = null;
function initAudioAnalyzer() { audioContext = new (window.AudioContext || window.webkitAudioContext)(); analyser = audioContext.createAnalyser(); analyser.fftSize = 2048;
const bufferLength = analyser.frequencyBinCount; dataArray = new Uint8Array(bufferLength); } // === 真正的語音嘴型同步 === function startLipSync(audio) { if (!model || !model.internalModel.coreModel) return; if (!audioContext) initAudioAnalyzer();
const coreModel = model.internalModel.coreModel;
// 將 audio 元件接到分析器 const source = audioContext.createMediaElementSource(audio); source.connect(analyser); analyser.connect(audioContext.destination);
function animate() { // 如果音訊停止就結束同步 if (audio.paused || audio.ended) { coreModel.setParameterValueById("ParamMouthOpenY", 0); return; }
// 取得頻率資料 analyser.getByteFrequencyData(dataArray);
// 計算平均音量 let sum = 0; for (let i = 0; i < dataArray.length; i++) sum += dataArray[i]; const volume = sum / dataArray.length;
// 映射到嘴型 (0~1) const mouthValue = Math.min(1, volume / 120); // 值越低嘴巴越靈敏
// 套用到 Live2D 嘴巴參數 coreModel.setParameterValueById("ParamMouthOpenY", mouthValue);
requestAnimationFrame(animate); }
animate(); }
(async () => { try { console.log("PIXI.live2d 存在?", !!PIXI.live2d.Live2DModel); // 會印 true
const modelUrl = "./assets/ellot/ellot.model3.json"; model = await PIXI.live2d.Live2DModel.from(modelUrl); // 官方載入方式
console.log("Ellot 模型載入成功!", model);
model.scale.set(0.4); // 調小一點,避免太大 model.anchor.set(0.5, 1); model.position.set(app.renderer.width * 0.5, app.renderer.height);
// 拖拽事件(修復簡化) model.interactive = true; model.on("pointerdown", (e) => { model.dragging = true; const pos = e.data.getLocalPosition(model.parent); model._dragOffset = { x: pos.x - model.x, y: pos.y - model.y }; }); model.on("pointermove", (e) => { if (model.dragging) { const pos = e.data.getLocalPosition(model.parent); model.position.set(pos.x - model._dragOffset.x, pos.y - model._dragOffset.y); } }); model.on("pointerup", () => model.dragging = false); model.on("pointerupoutside", () => model.dragging = false);
app.stage.addChild(model);
model.internalModel.motionManager.startRandomMotion("Idle");
} catch (err) { console.error("載入細節錯誤:", err); addMessage("模型載入失敗:" + err.message, "bot"); } })();
window.addEventListener("resize", () => { if (model) model.position.set(app.screen.width / 2, app.screen.height); });
function startFakeLipSync(audio) { if (!model || !model.internalModel.coreModel) return; const coreModel = model.internalModel.coreModel; let active = true; const timer = setInterval(() => { if (!active) return; const v = Math.random(); coreModel.setParameterValueById("ParamMouthOpenY", v); }, 80); audio.addEventListener("ended", () => { active = false; clearInterval(timer); coreModel.setParameterValueById("ParamMouthOpenY", 0); }); }
// 聊天功能 const sendToMiniLoy = async (text) => { window.addMessage(text, "user"); sendBtn.disabled = true; inputEl.value = "";
try { const resp = await fetch("http://localhost:4001/api/chat", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ text }) }); const data = await resp.json(); window.addMessage(data.reply || "(no reply)", "bot"); if (data.audio) { const audio = new Audio("http://localhost:4001" + data.audio); audio.play(); startLipSync(audio); // window.startFakeLipSync(audio); } } catch (err) { window.addMessage("後端連線失敗", "bot"); } finally { sendBtn.disabled = false; } };
sendBtn.onclick = () => { const text = inputEl.value.trim(); if (text) sendToMiniLoy(text); }; inputEl.onkeydown = e => { if (e.key === "Enter") { const text = inputEl.value.trim(); if (text) sendToMiniLoy(text); } }; });
|