Skip to content

Local AI BGM and sound effects for Claude Code and any MCP client. Stable Audio 3 on Apple Silicon (MLX) and Windows NVIDIA GPUs (PyTorch). No cloud, no API key.

Web UI: waveform editor (variation / inpaint / extend, export presets) and a friendlier generate page (GAME-224)

Kanaa0c3348b19d8
diff --git a/src/audio_studio_mcp/static/app.css b/src/audio_studio_mcp/static/app.css
index d02f684..d66baae 100644
--- a/src/audio_studio_mcp/static/app.css
+++ b/src/audio_studio_mcp/static/app.css
@@ -18,6 +18,11 @@
--danger-soft: #fdecea;
--shadow: 0 1px 2px rgba(16, 24, 40, .06);
--radius: 8px;
+ --wave: #7b8591; /* graphics: >= 3:1 on --surface */
+ --wave-played: #1d5fd6;
+ --wave-axis: #d5d9de;
+ --sel-bg: rgba(29, 95, 214, .13);
+ --track-bg: #f6f7f9;
color-scheme: light;
}
@media (prefers-color-scheme: dark) {
@@ -26,6 +31,7 @@
--text: #e7e9ec; --muted: #a4acb5; --accent: #79a8ff; --accent-bg: #2563eb; --accent-text: #ffffff;
--accent-soft: #1d2a42; --ok: #5cc37a; --warn: #e0b04f; --danger: #ff8f84; --danger-soft: #3a1f1d;
--shadow: none; color-scheme: dark;
+ --wave: #7f8a96; --wave-played: #79a8ff; --wave-axis: #343a41; --sel-bg: rgba(121, 168, 255, .16); --track-bg: #181b1f;
}
}
:root[data-theme="dark"] {
@@ -33,6 +39,7 @@
--text: #e7e9ec; --muted: #a4acb5; --accent: #79a8ff; --accent-bg: #2563eb; --accent-text: #ffffff;
--accent-soft: #1d2a42; --ok: #5cc37a; --warn: #e0b04f; --danger: #ff8f84; --danger-soft: #3a1f1d;
--shadow: none; color-scheme: dark;
+ --wave: #7f8a96; --wave-played: #79a8ff; --wave-axis: #343a41; --sel-bg: rgba(121, 168, 255, .16); --track-bg: #181b1f;
}
* { box-sizing: border-box; }
@@ -69,7 +76,7 @@ h1, h2 { margin: 0; font-weight: 600; }
padding: 7px 12px; border-radius: 6px; cursor: pointer;
}
.tabs button:hover { color: var(--text); background: var(--surface-2); }
-.tabs button[aria-selected="true"] { color: var(--accent); background: var(--accent-soft); }
+.tabs button[aria-selected="true"], .subtabs button[aria-selected="true"] { color: var(--accent); background: var(--accent-soft); }
.status { margin-left: auto; display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
.model-state { display: inline-flex; align-items: center; gap: 6px; color: var(--muted); font-size: 12.5px; padding-right: 4px; }
.model-state .dot { width: 8px; height: 8px; border-radius: 50%; background: var(--border-strong); }
@@ -97,7 +104,8 @@ input:focus, textarea:focus, select:focus { outline: 2px solid var(--accent); ou
.btn-primary { background: var(--accent-bg); border-color: var(--accent-bg); color: var(--accent-text); }
.btn-primary:hover { background: var(--accent-bg); filter: brightness(1.08); }
.btn-quiet { background: transparent; }
-.btn-sm { padding: 4px 9px; font-size: 12.5px; }
+.btn-sm { padding: 4px 10px; font-size: 12.5px; min-height: 28px; }
+.btn-lg { padding: 9px 18px; font-size: 14.5px; }
.link-btn { appearance: none; text-decoration: none; border: 0; background: none; color: var(--accent); font: inherit; font-size: 12.5px; padding: 2px 0; cursor: pointer; }
.link-btn:hover { text-decoration: underline; }
.link-btn:disabled { color: var(--muted); cursor: not-allowed; text-decoration: none; }
@@ -113,7 +121,6 @@ main { max-width: 1280px; margin: 0 auto; padding: 20px; }
.field > label, .field > legend { font-weight: 550; font-size: 13px; padding: 0; }
.hint { margin: 0; color: var(--muted); font-size: 12.5px; }
.row { display: grid; grid-template-columns: repeat(auto-fit, minmax(110px, 1fr)); gap: 10px; align-items: start; }
-.sfx-fields { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
.segmented { display: flex; border: 1px solid var(--border-strong); border-radius: 6px; overflow: hidden; }
.segmented label { flex: 1; position: relative; }
.segmented input { position: absolute; opacity: 0; inset: 0; margin: 0; cursor: pointer; }
@@ -127,13 +134,44 @@ main { max-width: 1280px; margin: 0 auto; padding: 20px; }
.advanced[open] summary { margin-bottom: 10px; color: var(--text); }
.advanced > .field { margin-top: 10px; }
.form-error { margin: 0; padding: 8px 10px; border-radius: 6px; background: var(--danger-soft); color: var(--danger); white-space: pre-wrap; word-break: break-word; }
-.actions { display: flex; gap: 8px; }
+.actions { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
+.kbd-hint { margin-left: auto; }
+.inline { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
+input.num { width: 96px; flex: none; }
+.chips { display: flex; gap: 6px; flex-wrap: wrap; align-items: center; }
+.chips-label { margin-right: 2px; }
+.chip {
+ appearance: none; font: inherit; font-size: 12.5px; line-height: 1.2; cursor: pointer; white-space: nowrap;
+ padding: 5px 10px; border-radius: 999px; border: 1px solid var(--border-strong); background: var(--surface); color: var(--text);
+}
+.chip:hover { border-color: var(--accent); color: var(--accent); }
+.chip[aria-pressed="true"] { background: var(--accent-soft); border-color: var(--accent); color: var(--accent); }
+.sfx-fields { border: 1px solid var(--border); border-radius: 6px; padding: 8px 10px; }
+.sfx-fields summary { cursor: pointer; font-weight: 550; font-size: 13px; color: var(--muted); }
+.sfx-fields[open] summary { margin-bottom: 8px; color: var(--text); }
+.sfx-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
+.mod-dot { display: inline-block; width: 7px; height: 7px; border-radius: 50%; background: var(--accent); margin-left: 6px; vertical-align: middle; }
+.advanced .link-btn { margin-top: 8px; }
/* results */
.results-head { display: flex; align-items: baseline; gap: 12px; margin-bottom: 10px; }
.results-head h2 { font-size: 15px; }
.jobs { display: flex; flex-direction: column; gap: 12px; }
-.empty { color: var(--muted); padding: 28px; text-align: center; border: 1px dashed var(--border-strong); border-radius: var(--radius); margin: 0; }
+.empty-state { color: var(--muted); padding: 24px; text-align: center; border: 1px dashed var(--border-strong); border-radius: var(--radius); margin: 0;
+ display: flex; flex-direction: column; align-items: center; gap: 10px; }
+.empty-state p { margin: 0; max-width: 560px; }
+.empty-title { color: var(--text); font-weight: 600; font-size: 15px; }
+.starter { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 10px; width: 100%; margin-top: 6px; }
+.starter-card, .recent-item {
+ appearance: none; font: inherit; text-align: left; cursor: pointer; color: var(--text);
+ display: flex; flex-direction: column; gap: 6px; align-items: flex-start;
+ padding: 12px; border-radius: var(--radius); border: 1px solid var(--border); background: var(--surface);
+}
+.starter-card:hover, .recent-item:hover { border-color: var(--accent); }
+.starter-name, .recent-name { font-weight: 600; }
+.recent { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 8px; width: 100%; max-width: 900px; }
+.recent-head { grid-column: 1 / -1; text-align: left; }
+.recent-name { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.job { padding: 14px; display: flex; flex-direction: column; gap: 10px; }
.job-head { display: flex; gap: 10px; align-items: flex-start; }
.job-prompt { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; }
@@ -145,14 +183,50 @@ main { max-width: 1280px; margin: 0 auto; padding: 20px; }
@media (prefers-reduced-motion: reduce) { .spinner { animation: none; } }
.progress { height: 3px; background: var(--surface-2); border-radius: 2px; overflow: hidden; }
.progress > div { height: 100%; width: 30%; background: var(--accent); animation: slide 1.4s ease-in-out infinite; }
+.progress.determinate > div { animation: none; transition: width .8s linear; }
+@media (prefers-reduced-motion: reduce) { .progress > div { animation: none; } }
@keyframes slide { from { transform: translateX(-100%); } to { transform: translateX(340%); } }
.job-error { margin: 0; color: var(--danger); background: var(--danger-soft); padding: 8px 10px; border-radius: 6px; white-space: pre-wrap; word-break: break-word; font-size: 13px; }
.candidates { display: grid; grid-template-columns: repeat(auto-fit, minmax(230px, 1fr)); gap: 10px; }
.cand { border: 1px solid var(--border); border-radius: 6px; padding: 10px; display: flex; flex-direction: column; gap: 8px; background: var(--surface-2); }
.cand-head { display: flex; justify-content: space-between; gap: 8px; font-size: 12.5px; }
.cand-head strong { font-weight: 600; }
-audio { width: 100%; height: 36px; }
-.cand-actions, .item-actions { display: flex; gap: 2px 12px; flex-wrap: wrap; }
+.cand-actions, .item-actions { display: flex; gap: 6px; flex-wrap: wrap; align-items: center; }
+.job-foot { display: flex; gap: 12px; align-items: center; justify-content: space-between; flex-wrap: wrap; }
+.job-steps { margin: 0; }
+
+/* compact player: button + waveform thumbnail + time */
+.mini-wave { display: flex; align-items: center; gap: 8px; min-width: 0; }
+.play-btn {
+ flex: none; width: 32px; height: 32px; border-radius: 50%; border: 1px solid var(--accent-bg); cursor: pointer;
+ background: var(--accent-bg); position: relative;
+}
+.play-btn::before, .icon-play { /* triangle */
+ content: ""; position: absolute; left: 50%; top: 50%; transform: translate(-35%, -50%);
+ border-style: solid; border-width: 6px 0 6px 10px; border-color: transparent transparent transparent var(--accent-text);
+}
+.play-btn.playing::before, .play-main.playing .icon-play { /* pause bars */
+ transform: translate(-50%, -50%); width: 10px; height: 12px; border: 0;
+ background: linear-gradient(90deg, var(--accent-text) 0 35%, transparent 35% 65%, var(--accent-text) 65%);
+}
+.play-btn:hover { filter: brightness(1.08); }
+.mini-wave-track { flex: 1; min-width: 60px; height: 36px; cursor: pointer; border-radius: 4px; background: var(--track-bg); }
+.mini-wave-canvas { width: 100%; height: 100%; display: block; }
+.mini-time { flex: none; font-size: 12px; color: var(--muted); font-variant-numeric: tabular-nums; min-width: 3.2em; text-align: right; }
+
+/* ⋯ menu */
+.menu { position: relative; }
+.menu summary { list-style: none; }
+.menu summary::-webkit-details-marker { display: none; }
+.menu-btn { cursor: pointer; padding: 3px 10px; border-radius: 6px; color: var(--muted); font-weight: 700; border: 1px solid transparent; }
+.menu-btn:hover, .menu[open] .menu-btn { background: var(--surface-2); color: var(--text); }
+.menu-list {
+ position: absolute; right: 0; top: calc(100% + 4px); z-index: 20; min-width: 180px; padding: 4px;
+ background: var(--surface); border: 1px solid var(--border-strong); border-radius: 8px; box-shadow: 0 6px 20px rgba(0,0,0,.16);
+ display: flex; flex-direction: column;
+}
+.menu-list button { appearance: none; font: inherit; font-size: 13px; text-align: left; border: 0; background: none; color: var(--text); padding: 7px 10px; border-radius: 5px; cursor: pointer; white-space: nowrap; }
+.menu-list button:hover, .menu-list button:focus-visible { background: var(--surface-2); }
.badge { display: inline-block; font-size: 11.5px; font-weight: 600; padding: 1px 7px; border-radius: 10px; background: var(--surface-2); color: var(--muted); border: 1px solid var(--border); white-space: nowrap; }
/* library */
@@ -160,7 +234,7 @@ audio { width: 100%; height: 36px; }
.library-bar input { max-width: 440px; }
.folder { margin: 8px 0 14px; word-break: break-all; }
.library { display: flex; flex-direction: column; gap: 8px; }
-.item { padding: 12px 14px; display: grid; grid-template-columns: minmax(0, 1fr) minmax(220px, 320px); gap: 6px 16px; align-items: center; }
+.item { padding: 12px 14px; display: grid; grid-template-columns: minmax(0, 1fr) minmax(260px, 400px); gap: 6px 16px; align-items: center; }
@media (max-width: 760px) { .item { grid-template-columns: 1fr; } }
.item-main { min-width: 0; display: flex; flex-direction: column; gap: 3px; }
.item-title { font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
@@ -174,6 +248,81 @@ audio { width: 100%; height: 36px; }
mark { background: var(--accent-soft); color: inherit; border-radius: 2px; }
.toast {
- position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%);
+ position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%); z-index: 50;
+ display: flex; gap: 14px; align-items: center;
background: var(--text); color: var(--bg); padding: 8px 14px; border-radius: 6px; font-size: 13px; box-shadow: 0 4px 14px rgba(0,0,0,.2);
}
+.toast .toast-act { color: var(--bg); font-weight: 600; text-decoration: underline; font-size: 13px; }
+
+/* edit page */
+.edit-head { display: flex; align-items: baseline; justify-content: space-between; gap: 6px 16px; flex-wrap: wrap; margin-bottom: 12px; }
+.edit-title { display: flex; align-items: baseline; gap: 12px; flex-wrap: wrap; min-width: 0; }
+.edit-title h1 { font-size: 18px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 100%; }
+.edit-source { display: flex; gap: 4px; align-items: baseline; }
+.wave-panel { padding: 12px 14px; display: flex; flex-direction: column; gap: 6px; }
+.wave-toolbar { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
+.play-main { position: relative; padding-left: 34px; min-width: 110px; }
+.play-main .icon-play { left: 18px; }
+.clock { font-variant-numeric: tabular-nums; font-size: 13px; }
+.spacer { flex: 1; }
+.zoom { display: flex; gap: 4px; flex-wrap: wrap; }
+.zoom .btn:disabled { opacity: .55; }
+.toggle { display: inline-flex; align-items: center; gap: 6px; font-size: 13px; cursor: pointer; }
+.toggle input, .check input { width: 16px; height: 16px; accent-color: var(--accent-bg); margin: 0; }
+.ruler { width: 100%; height: 20px; display: block; }
+.wave {
+ position: relative; height: 180px; background: var(--track-bg); border: 1px solid var(--border); border-radius: 6px;
+ cursor: text; touch-action: none; user-select: none; overflow: hidden;
+}
+.wave:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+.wave canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }
+.wave-loading { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; }
+.sel { position: absolute; top: 0; bottom: 0; background: var(--sel-bg); border-left: 2px solid var(--accent); border-right: 2px solid var(--accent); pointer-events: none; }
+.handle { position: absolute; top: 0; bottom: 0; width: 14px; cursor: ew-resize; pointer-events: auto; }
+.handle::after { content: ""; position: absolute; top: 50%; width: 8px; height: 28px; margin-top: -14px; border-radius: 3px; background: var(--accent); }
+.handle.start { left: -8px; } .handle.start::after { left: 2px; }
+.handle.end { right: -8px; } .handle.end::after { right: 2px; }
+.handle:focus-visible { outline: 2px solid var(--text); outline-offset: -2px; }
+.playhead { position: absolute; top: 0; bottom: 0; width: 2px; margin-left: -1px; background: var(--text); pointer-events: none; }
+.overview { position: relative; height: 34px; background: var(--track-bg); border: 1px solid var(--border); border-radius: 4px; cursor: pointer; touch-action: none; }
+.overview canvas { width: 100%; height: 100%; display: block; }
+.view-box { position: absolute; top: -1px; bottom: -1px; border: 2px solid var(--accent); border-radius: 3px; background: var(--sel-bg); pointer-events: none; }
+.sel-bar { display: flex; align-items: center; gap: 8px 14px; flex-wrap: wrap; font-size: 13px; padding-top: 4px; }
+.sel-label { font-weight: 600; }
+.sel-field { display: inline-flex; align-items: center; gap: 6px; }
+.sel-field input { width: 92px; padding: 4px 7px; }
+.sel-len { color: var(--muted); font-variant-numeric: tabular-nums; }
+.wave-help { text-align: right; }
+.edit-body { display: grid; grid-template-columns: minmax(340px, 480px) 1fr; gap: 20px; align-items: start; margin-top: 16px; }
+@media (max-width: 900px) { .edit-body { grid-template-columns: 1fr; } }
+.edit-tools { overflow: visible; }
+.subtabs { display: flex; gap: 2px; padding: 8px 8px 0; border-bottom: 1px solid var(--border); }
+.subtabs button {
+ appearance: none; border: 0; background: none; color: var(--muted); font: inherit; font-weight: 600;
+ padding: 8px 14px; border-radius: 6px 6px 0 0; cursor: pointer;
+}
+.subtabs button:hover { color: var(--text); background: var(--surface-2); }
+.form-body { padding: 16px 18px 18px; display: flex; flex-direction: column; gap: 14px; }
+.mode-cards { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; }
+.mode-card, .preset {
+ position: relative; display: flex; flex-direction: column; gap: 3px; padding: 10px; cursor: pointer;
+ border: 1px solid var(--border-strong); border-radius: 6px; background: var(--surface);
+}
+.mode-card input, .preset input { position: absolute; opacity: 0; inset: 0; margin: 0; cursor: pointer; }
+.mode-card:hover, .preset:hover { border-color: var(--accent); }
+.mode-card.checked, .preset.checked { border-color: var(--accent); background: var(--accent-soft); box-shadow: inset 0 0 0 1px var(--accent); }
+.mode-card:focus-within, .preset:focus-within { outline: 2px solid var(--accent); outline-offset: 2px; }
+.mode-name, .preset-name { font-weight: 600; font-size: 13px; }
+.mode-card.checked .mode-name, .preset.checked .preset-name { color: var(--accent); }
+.mode-desc { font-size: 12px; color: var(--muted); }
+.preset-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(130px, 1fr)); gap: 8px; }
+input[type="range"] { width: 100%; accent-color: var(--accent-bg); }
+.range-labels { display: flex; justify-content: space-between; }
+.note { margin: 0; padding: 8px 10px; border-radius: 6px; background: var(--accent-soft); color: var(--text); font-size: 13px; }
+.note.warn { background: var(--surface-2); border: 1px dashed var(--border-strong); }
+.check { display: flex; gap: 8px; align-items: center; cursor: pointer; font-size: 13px; }
+.check.disabled { color: var(--muted); cursor: not-allowed; }
+.checks { display: flex; flex-direction: column; gap: 8px; margin-bottom: 12px; }
+.summary { margin: 0; color: var(--muted); }
+#x-custom .row { margin-bottom: 10px; }
+@media (max-width: 560px) { .mode-cards { grid-template-columns: 1fr; } .wave-help { display: none; } }
diff --git a/src/audio_studio_mcp/static/app.js b/src/audio_studio_mcp/static/app.js
index a48d79b..df855d6 100644
--- a/src/audio_studio_mcp/static/app.js
+++ b/src/audio_studio_mcp/static/app.js
@@ -1,16 +1,49 @@
// Audio Studio web UI. Plain JS, no build step. Talks to /api (see web.py).
+// Load order: i18n.js, wave.js, editor.js, app.js (this file boots the page).
"use strict";
const $ = (sel, root = document) => root.querySelector(sel);
const state = {
lang: "en",
status: null,
+ loaded: false, // model loaded (from /api/jobs while polling)
jobs: new Map(), // id -> job view from the server
+ expect: new Map(), // id -> audio seconds the job will produce (for the estimate)
polling: false,
- lib: { items: [], total: 0, offset: 0, query: "" },
+ lib: { items: [], total: 0, query: "" },
};
const PAGE = 50;
const RESTORE_JOBS = 8;
+const TYPES = ["music", "instrument", "sfx"];
+
+// Example prompts per type: a click fills the form. Prompts stay English (the
+// model's language); the chip label is translated.
+const EXAMPLES = {
+ music: [
+ { key: "lofi", prompt: "Lo-fi hip-hop chill track with mellow electric piano, soft vinyl crackle, low-pass filtered drums and soft plucked bass for a relaxed, dreamy vibe.", seconds: 60, bpm: 80 },
+ { key: "chiptune", prompt: "Upbeat 8-bit chiptune adventure theme with bright square-wave lead, bubbly arpeggios and punchy noise drums, cheerful and energetic.", seconds: 45, bpm: 140 },
+ { key: "epic", prompt: "Epic orchestral battle music with driving staccato strings, powerful brass fanfares, thundering taiko drums and a heroic, urgent mood.", seconds: 90, bpm: 120 },
+ { key: "ambient", prompt: "Calm ambient soundscape with warm evolving synth pads, gentle felt piano notes and distant shimmering textures, peaceful and spacious.", seconds: 120 },
+ ],
+ instrument: [
+ { key: "guitar", prompt: "Fingerpicked nylon-string acoustic guitar loop, warm and intimate, close-mic recording with soft room tone.", seconds: 12, bpm: 90 },
+ { key: "drums", prompt: "Tight funk drum loop with crisp snare, punchy kick and swung closed hi-hats, dry studio recording.", seconds: 8, bpm: 100 },
+ { key: "pad", prompt: "Lush analog synth pad sustaining a minor chord, slow filter sweep, wide stereo and soft reverb.", seconds: 16 },
+ ],
+ sfx: [
+ { key: "glass", prompt: "", source: "glass bottle", action: "shattering on impact, fragments scattering", material: "thick green glass, sharp bright transient", space: "concrete floor, close-up, dry", seconds: 3 },
+ { key: "footsteps", prompt: "", source: "footsteps", action: "slow walking, steady pace", material: "leather boots on gravel", space: "outdoors, close-up", seconds: 5 },
+ { key: "rain", prompt: "Steady rain on a window with occasional distant thunder rumbles.", source: "", action: "", material: "", space: "indoors, cozy room", seconds: 12 },
+ { key: "ui", prompt: "", source: "soft UI confirm chime", action: "short bright two-note rise", material: "clean synthetic bell tone", space: "dry, close", seconds: 1.5 },
+ { key: "door", prompt: "", source: "old wooden door", action: "slowly creaking open then closing with a thud", material: "worn wood, rusty metal hinges", space: "small stone room, slight reverb", seconds: 4 },
+ ],
+};
+// Length presets per type (seconds).
+const DURATIONS = {
+ music: [30, 60, 120, 180],
+ instrument: [8, 12, 20, 30],
+ sfx: [1.5, 3, 5, 10],
+};
// ── i18n ───────────────────────────────────────────────────────────────────
function pickLang(pref) {
@@ -31,10 +64,13 @@ function applyI18n() {
document.querySelectorAll("[data-i18n]").forEach((n) => { n.textContent = t(n.dataset.i18n); });
document.querySelectorAll("[data-i18n-placeholder]").forEach((n) => { n.placeholder = t(n.dataset.i18nPlaceholder); });
document.querySelectorAll("[data-i18n-title]").forEach((n) => { n.title = t(n.dataset.i18nTitle); });
+ document.querySelectorAll("[data-i18n-aria-label]").forEach((n) => { n.setAttribute("aria-label", t(n.dataset.i18nAriaLabel)); });
updateTypeUI();
renderStatus();
renderJobs();
renderLibrary();
+ renderStarters();
+ Editor.applyI18n();
}
// ── helpers ────────────────────────────────────────────────────────────────
@@ -68,13 +104,19 @@ function audioUrl(file, download) {
return `/api/audio/${encodeURIComponent(file)}${download ? "?download=1" : ""}`;
}
function baseName(p) { return String(p).split(/[\\/]/).pop(); }
+function typing(e) {
+ const n = e.target;
+ return n && (n.isContentEditable || ["INPUT", "TEXTAREA", "SELECT"].includes(n.tagName));
+}
let toastTimer;
-function toast(msg) {
+function toast(msg, action) {
const n = $("#toast");
- n.textContent = msg; n.hidden = false;
+ n.replaceChildren(el("span", { text: msg }), action ? el("button", { class: "link-btn toast-act", type: "button", text: action.label,
+ onclick: () => { n.hidden = true; action.run(); } }) : null);
+ n.hidden = false;
clearTimeout(toastTimer);
- toastTimer = setTimeout(() => { n.hidden = true; }, 2200);
+ toastTimer = setTimeout(() => { n.hidden = true; }, action ? 6000 : 2200);
}
async function copyText(text) {
try { await navigator.clipboard.writeText(text); toast(t("toast.copied")); }
@@ -96,6 +138,21 @@ async function api(path, opts = {}) {
return body;
}
+// A small "⋯" menu (details/summary) for secondary actions.
+function moreMenu(items) {
+ const menu = el("details", { class: "menu" },
+ el("summary", { class: "menu-btn", "aria-label": t("act.more"), title: t("act.more") }, "⋯"),
+ el("div", { class: "menu-list", role: "menu" }, items.filter(Boolean).map(([label, run]) =>
+ el("button", { type: "button", role: "menuitem", text: label, onclick: () => { menu.open = false; run(); } }))));
+ return menu;
+}
+document.addEventListener("click", (e) => {
+ document.querySelectorAll("details.menu[open]").forEach((m) => { if (!m.contains(e.target)) m.open = false; });
+});
+document.addEventListener("keydown", (e) => {
+ if (e.key === "Escape") document.querySelectorAll("details.menu[open]").forEach((m) => { m.open = false; m.querySelector("summary").focus(); });
+});
+
// ── theme / language settings ────────────────────────────────────────────────
function initSettings() {
const theme = localStorage.getItem("as.theme") || "system";
@@ -104,6 +161,7 @@ function initSettings() {
const v = e.target.value;
if (v === "system") { delete document.documentElement.dataset.theme; localStorage.removeItem("as.theme"); }
else { document.documentElement.dataset.theme = v; localStorage.setItem("as.theme", v); }
+ window.dispatchEvent(new Event("as:theme"));
});
const lang = localStorage.getItem("as.lang") || "auto";
$("#lang").value = lang;
@@ -116,16 +174,26 @@ function initSettings() {
});
}
-// ── tabs ─────────────────────────────────────────────────────────────────────
+// ── pages ────────────────────────────────────────────────────────────────────
+// Hash routes: #generate, #library, #edit/<file name>
function showPage(name, push = true) {
document.querySelectorAll(".tabs [role=tab]").forEach((b) => b.setAttribute("aria-selected", String(b.dataset.page === name)));
document.querySelectorAll(".page").forEach((p) => { p.hidden = p.id !== `page-${name}`; });
- if (push && location.hash !== `#${name}`) history.replaceState(null, "", `#${name}`);
+ const hash = name === "edit" && Editor.file ? `#edit/${encodeURIComponent(Editor.file)}` : `#${name}`;
+ if (push && location.hash !== hash) history.replaceState(null, "", hash);
if (name === "library") loadLibrary(true);
+ if (name === "edit") Editor.shown();
+ else Editor.hidden();
+}
+function openEditor(file) {
+ Editor.open(file);
+ showPage("edit");
}
function initTabs() {
document.querySelectorAll(".tabs [role=tab]").forEach((b) => b.addEventListener("click", () => showPage(b.dataset.page)));
- showPage(location.hash === "#library" ? "library" : "generate", false);
+ const h = location.hash;
+ if (h.startsWith("#edit/")) openEditor(decodeURIComponent(h.slice(6)));
+ else showPage(h === "#library" ? "library" : h === "#edit" ? "edit" : "generate", false);
}
// ── status bar ───────────────────────────────────────────────────────────────
@@ -134,16 +202,16 @@ function renderStatus() {
if (!s) { box.dataset.state = "error"; text.textContent = t("status.offline"); $("#unload").disabled = true; return; }
const busy = s.jobs.running > 0;
box.dataset.state = busy ? "busy" : s.loaded ? "loaded" : "idle";
- text.textContent = `${busy ? t("status.working") : s.loaded ? t("status.loaded") : t("status.notLoaded")} · ${s.backend}`;
+ text.textContent = busy ? t("status.working") : s.loaded ? t("status.loaded") : t("status.notLoaded");
box.title = `${s.backend} — ${s.model}`;
$("#version").textContent = `v${s.version}`;
$("#unload").disabled = !s.loaded || busy;
$("#queue-info").textContent = (s.jobs.running || s.jobs.queued) ? t("jobs.queueInfo", s.jobs) : "";
$("#lib-folder").textContent = t("lib.folder", { dir: s.output_dir });
- updateDurationPlaceholder();
+ updateDurationUI();
}
async function refreshStatus() {
- try { state.status = await api("/api/status"); }
+ try { state.status = await api("/api/status"); state.loaded = state.status.loaded; }
catch { state.status = null; }
renderStatus();
}
@@ -158,167 +226,340 @@ async function unloadModel() {
// ── generate form ────────────────────────────────────────────────────────────
const form = () => $("#gen-form");
-function currentType() { return form().audio_type.value; }
-function updateDurationPlaceholder() {
- const d = state.status && state.status.default_seconds;
- $("#duration_seconds").placeholder = d ? String(d[currentType()]) : "";
- if (state.status) $("#duration_seconds").max = String(state.status.max_seconds);
+const field = (name) => form().elements.namedItem(name);
+function currentType() { return field("audio_type").value; }
+function defaultSeconds(type) { return state.status ? state.status.default_seconds[type] : null; }
+function updateDurationUI() {
+ const type = currentType(), d = defaultSeconds(type);
+ const input = $("#duration_seconds");
+ input.placeholder = d ? String(d) : "";
+ if (state.status) input.max = String(state.status.max_seconds);
+ const max = state.status ? state.status.max_seconds : 380;
+ $("#duration-hint").textContent = t("gen.durationHint", { def: d ?? "—", max });
+ const cur = input.value.trim() === "" ? d : Number(input.value);
+ $("#durations").replaceChildren(...DURATIONS[type].filter((s) => s <= max).map((s) =>
+ el("button", { type: "button", class: "chip", "aria-pressed": String(cur === s), text: fmtLen(s),
+ onclick: () => { input.value = s; updateDurationUI(); } })));
}
function updateTypeUI() {
const type = currentType(), sfx = type === "sfx";
$("#sfx-fields").hidden = !sfx;
$("#bpm-field").hidden = sfx;
+ $("#type-hint").textContent = t(`type.${type}Hint`);
$("#prompt-label").textContent = t(`gen.prompt.${type}`);
$("#prompt-hint").textContent = t(`gen.promptHint.${type}`);
$("#prompt").placeholder = t(`gen.promptPh.${type}`);
- updateDurationPlaceholder();
+ $("#examples").replaceChildren(el("span", { class: "chips-label muted small", text: t("gen.tryExample") }),
+ ...EXAMPLES[type].map((ex) => el("button", { type: "button", class: "chip", text: t(`ex.${ex.key}`),
+ title: ex.prompt || [ex.source, ex.action, ex.material, ex.space].filter(Boolean).join(", "),
+ onclick: () => applyExample(type, ex) })));
+ updateDurationUI();
+ updateSubmitLabel();
+}
+function applyExample(type, ex) {
+ field("audio_type").value = type;
+ $("#prompt").value = ex.prompt || "";
+ for (const [k, v] of [["sound_source", ex.source], ["sound_action", ex.action], ["sound_material", ex.material], ["sound_space", ex.space]]) field(k).value = v || "";
+ $("#duration_seconds").value = ex.seconds ?? "";
+ $("#bpm").value = ex.bpm ?? "";
+ clearErrors();
+ updateTypeUI();
+ $("#prompt").focus();
+}
+function updateSubmitLabel() {
+ const n = parseInt(field("variations").value, 10) || 1;
+ $("#gen-submit").textContent = n > 1 ? t("gen.submitN", { n }) : t("gen.submit");
+}
+const ADV_FIELDS = ["seed", "cfg", "steps", "peak_ceiling_db", "negative_prompt", "title"];
+function updateAdvancedDot() {
+ $("#adv-dot").hidden = !ADV_FIELDS.some((k) => field(k).value.trim() !== "");
}
// Sent as typed; the server validates (a seed of 1.5 is an error, not 1).
const NUMBER_FIELDS = ["duration_seconds", "bpm", "seed", "cfg", "steps", "peak_ceiling_db"];
function readForm() {
- const f = form(), type = currentType();
- const args = { audio_type: type, prompt: f.prompt.value.trim(), variations: parseInt(f.variations.value, 10) };
+ const type = currentType();
+ const args = { audio_type: type, prompt: field("prompt").value.trim(), variations: parseInt(field("variations").value, 10) };
if (type === "sfx") {
for (const k of ["sound_source", "sound_action", "sound_material", "sound_space"]) {
- const v = f[k].value.trim();
+ const v = field(k).value.trim();
if (v) args[k] = v;
}
}
for (const k of NUMBER_FIELDS) {
if (k === "bpm" && type === "sfx") continue;
- const raw = f[k].value.trim();
+ const raw = field(k).value.trim();
if (raw !== "") args[k] = Number(raw);
}
- const title = f.title.value.trim();
+ const title = field("title").value.trim();
if (title) args.title = title;
- const neg = f.negative_prompt.value.trim();
+ const neg = field("negative_prompt").value.trim();
if (neg) args.negative_prompt = neg;
return args;
}
function fillForm(meta) {
- const f = form();
- f.reset();
- const type = ["music", "instrument", "sfx"].includes(meta.audio_type) ? meta.audio_type : "music";
- f.audio_type.value = type;
- f.prompt.value = meta.prompt || "";
+ form().reset();
+ const type = TYPES.includes(meta.audio_type) ? meta.audio_type : "music";
+ field("audio_type").value = type;
+ field("prompt").value = meta.prompt || "";
const sf = meta.sound_fields || {};
- f.sound_source.value = sf.source || ""; f.sound_action.value = sf.action || "";
- f.sound_material.value = sf.material || ""; f.sound_space.value = sf.space || "";
- f.duration_seconds.value = meta.seconds ?? "";
- f.bpm.value = meta.bpm ?? "";
- f.seed.value = meta.seed ?? "";
- f.cfg.value = meta.cfg != null && meta.cfg !== 1 ? meta.cfg : "";
- f.steps.value = meta.steps != null && meta.steps !== 8 ? meta.steps : "";
- f.negative_prompt.value = meta.negative_prompt || "";
- if (f.cfg.value || f.steps.value || f.negative_prompt.value) $("#advanced").open = true;
+ field("sound_source").value = sf.source || ""; field("sound_action").value = sf.action || "";
+ field("sound_material").value = sf.material || ""; field("sound_space").value = sf.space || "";
+ field("duration_seconds").value = meta.seconds ?? "";
+ field("bpm").value = meta.bpm ?? "";
+ field("seed").value = meta.seed ?? "";
+ field("cfg").value = meta.cfg != null && meta.cfg !== 1 ? meta.cfg : "";
+ field("steps").value = meta.steps != null && meta.steps !== 8 ? meta.steps : "";
+ field("negative_prompt").value = meta.negative_prompt || "";
+ if (field("cfg").value || field("steps").value || field("negative_prompt").value) $("#advanced").open = true;
updateTypeUI();
+ updateAdvancedDot();
}
-function clearErrors() {
- $("#form-error").hidden = true;
- form().querySelectorAll("[aria-invalid]").forEach((n) => n.removeAttribute("aria-invalid"));
+function clearErrors(f = form(), box = $("#form-error")) {
+ box.hidden = true;
+ f.querySelectorAll("[aria-invalid]").forEach((n) => n.removeAttribute("aria-invalid"));
}
-function showFormError(msg, fields) {
- const box = $("#form-error");
+// Show an API error next to the form; mark the fields it names.
+function showFormError(msg, fields, f = form(), box = $("#form-error"), adv = $("#advanced")) {
box.textContent = msg; box.hidden = false;
- for (const f of fields || []) {
- const input = form().elements[f.field];
- if (input && input.setAttribute) {
- input.setAttribute("aria-invalid", "true");
- if (["seed", "cfg", "steps", "peak_ceiling_db", "negative_prompt"].includes(f.field)) $("#advanced").open = true;
+ for (const fe of fields || []) {
+ const input = f.elements.namedItem(fe.field);
+ const node = input && (input.setAttribute ? input : input[0]);
+ if (node && node.setAttribute) {
+ node.setAttribute("aria-invalid", "true");
+ if (adv && adv.contains(node)) adv.open = true;
}
}
}
-async function submitJob(args) {
- clearErrors();
- const hasText = args.prompt || args.sound_source || args.sound_action || args.sound_material || args.sound_space;
- if (!hasText) { showFormError(t("err.emptyPrompt")); $("#prompt").setAttribute("aria-invalid", "true"); return null; }
- $("#gen-submit").disabled = true;
+// Queue a tool call; returns the job or null (the error is shown by onError).
+async function queueJob(tool, args, { onError, expectSeconds } = {}) {
try {
- const job = await api("/api/jobs", { json: { tool: "generate_audio", arguments: args } });
+ const job = await api("/api/jobs", { json: { tool, arguments: args } });
state.jobs.set(job.id, job);
+ if (expectSeconds) state.expect.set(job.id, expectSeconds);
renderJobs();
pollJobs();
refreshStatus();
return job;
} catch (e) {
- showFormError(e.message, e.body && e.body.fields);
+ if (onError) onError(e); else toast(e.message);
return null;
+ }
+}
+async function submitJob(args) {
+ clearErrors();
+ const hasText = args.prompt || args.sound_source || args.sound_action || args.sound_material || args.sound_space;
+ if (!hasText) { showFormError(t("err.emptyPrompt")); $("#prompt").setAttribute("aria-invalid", "true"); $("#prompt").focus(); return null; }
+ $("#gen-submit").disabled = true;
+ try {
+ const secs = args.duration_seconds ?? defaultSeconds(args.audio_type);
+ return await queueJob("generate_audio", args, { expectSeconds: secs * (args.variations || 1),
+ onError: (e) => showFormError(e.message, e.body && e.body.fields) });
} finally {
$("#gen-submit").disabled = false;
}
}
function initForm() {
- form().addEventListener("change", (e) => { if (e.target.name === "audio_type") updateTypeUI(); });
- form().addEventListener("input", (e) => e.target.removeAttribute && e.target.removeAttribute("aria-invalid"));
+ form().addEventListener("change", (e) => {
+ if (e.target.name === "audio_type") updateTypeUI();
+ if (e.target.name === "variations") updateSubmitLabel();
+ });
+ form().addEventListener("input", (e) => {
+ if (e.target.removeAttribute) e.target.removeAttribute("aria-invalid");
+ if (e.target.id === "duration_seconds") updateDurationUI();
+ updateAdvancedDot();
+ });
form().addEventListener("submit", (e) => { e.preventDefault(); submitJob(readForm()); });
form().addEventListener("keydown", (e) => {
if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) { e.preventDefault(); form().requestSubmit(); }
});
- $("#gen-reset").addEventListener("click", () => { form().reset(); clearErrors(); updateTypeUI(); });
+ $("#gen-reset").addEventListener("click", () => { form().reset(); clearErrors(); updateTypeUI(); updateAdvancedDot(); });
+ $("#adv-reset").addEventListener("click", () => {
+ for (const k of ADV_FIELDS) field(k).value = "";
+ updateAdvancedDot();
+ });
$("#unload").addEventListener("click", unloadModel);
}
+// Starter cards in the empty Results area: one click fills the form.
+function renderStarters() {
+ const picks = [["sfx", EXAMPLES.sfx[0]], ["music", EXAMPLES.music[1]], ["instrument", EXAMPLES.instrument[0]]];
+ $("#starters").replaceChildren(...picks.map(([type, ex]) => el("button", { type: "button", class: "starter-card",
+ onclick: () => applyExample(type, ex) },
+ el("span", { class: "badge", text: t(`type.${type}`) }),
+ el("span", { class: "starter-name", text: t(`ex.${ex.key}`) }),
+ el("span", { class: "muted small", text: fmtLen(ex.seconds) }))));
+}
+
// ── jobs ─────────────────────────────────────────────────────────────────────
+function rates() { try { return JSON.parse(localStorage.getItem("as.rates") || "{}"); } catch { return {}; } }
+function rateKey(job) { return `${job.tool}:${job.arguments.mode || ""}`; }
+// Learn seconds of wall time per second of audio from finished jobs (without model load).
+function learnRate(job) {
+ const r = job.result;
+ if (!r || r.included_model_load || !r.wall_seconds || !r.seconds) return;
+ const n = (r.candidates || []).length || 1;
+ const all = rates();
+ all[rateKey(job)] = r.wall_seconds / (r.seconds * n);
+ localStorage.setItem("as.rates", JSON.stringify(all));
+}
+function estimate(job) {
+ const secs = state.expect.get(job.id), rate = rates()[rateKey(job)];
+ return secs && rate ? Math.max(1, rate * secs) : null;
+}
function jobStateText(job) {
if (job.status === "queued") return t("jobs.queued", { n: job.position ?? 1 });
- if (job.status === "running") return t("jobs.running", { t: fmtTime(job.elapsed) });
+ if (job.status === "running") {
+ if (job.tool !== "process_audio" && !state.loaded) return t("jobs.loading", { t: fmtTime(job.elapsed) });
+ const est = estimate(job);
+ return est ? t("jobs.runningEst", { t: fmtTime(job.elapsed), e: fmtTime(est) }) : t("jobs.running", { t: fmtTime(job.elapsed) });
+ }
if (job.status === "done") return t("jobs.done", { t: fmtTime(job.elapsed) });
+ if (job.status === "cancelled") return t("jobs.cancelled");
return t("jobs.error");
}
function promptLabel(a) {
const parts = [a.prompt, a.sound_source, a.sound_action, a.sound_material, a.sound_space].filter(Boolean);
- return parts.join(", ") || "—";
+ return parts.join(", ");
}
-function candidateCard(c, i) {
- const file = baseName(c.path);
- return el("div", { class: "cand" },
+function jobTitle(job) {
+ const a = job.arguments || {};
+ if (job.tool === "process_audio") return t("jobs.exportOf", { file: baseName(a.input_audio || "") });
+ if (job.tool === "edit_audio") return `${t(`mode.${a.mode}`)} · ${promptLabel(a) || baseName(a.input_audio || "")}`;
+ return promptLabel(a) || "—";
+}
+function jobBadge(job) {
+ if (job.tool === "process_audio") return t("kind.process");
+ return t(`type.${(job.arguments || {}).audio_type || "music"}`);
+}
+const LETTERS = "ABCD";
+function candidateCard(c, i, job) {
+ const file = baseName(c.path), mini = new MiniWave(file, c.seconds);
+ const many = job.result.candidates.length > 1;
+ return el("div", { class: "cand", dataset: { index: i } },
el("div", { class: "cand-head" },
- el("strong", { text: t("cand.label", { n: i + 1 }) }),
- el("span", { class: "muted", text: t("cand.seed", { seed: c.seed }) })),
- el("audio", { controls: true, preload: "metadata", src: audioUrl(file) }),
+ el("strong", { text: many ? t("cand.label", { n: LETTERS[i] || i + 1 }) : t("cand.single") }),
+ c.seed != null ? el("span", { class: "muted", text: t("cand.seed", { seed: c.seed }) }) : null),
+ mini.node,
el("div", { class: "cand-actions" },
- el("a", { class: "link-btn", href: audioUrl(file, true), download: file, text: t("act.download") }),
- el("button", { class: "link-btn", type: "button", text: t("act.copyPath"), onclick: () => copyText(c.path) }),
- el("button", { class: "link-btn", type: "button", text: t("act.useSeed"),
- onclick: () => { form().seed.value = c.seed; $("#advanced").open = true; toast(t("toast.seedSet", { seed: c.seed })); } })));
+ el("button", { class: "btn btn-sm", type: "button", text: t("act.edit"), onclick: () => openEditor(file) }),
+ el("a", { class: "btn btn-sm btn-quiet", href: audioUrl(file, true), download: file, text: t("act.download") }),
+ moreMenu([
+ [t("act.copyPath"), () => copyText(c.path)],
+ job.tool === "generate_audio" && c.seed != null ? [t("act.useSeed"), () => {
+ field("seed").value = c.seed; $("#advanced").open = true; updateAdvancedDot(); showPage("generate");
+ toast(t("toast.seedSet", { seed: c.seed }));
+ }] : null,
+ ])));
+}
+function resultCandidates(job) {
+ const r = job.result || {};
+ if (Array.isArray(r.candidates)) return r.candidates;
+ if (r.path) return [{ path: r.path, seconds: r.seconds }]; // process_audio: one file
+ return [];
}
function jobCard(job) {
- const a = job.arguments || {};
const active = job.status === "queued" || job.status === "running";
- const card = el("article", { class: "panel job", dataset: { status: job.status, id: job.id } },
- el("div", { class: "job-head" },
- el("span", { class: "badge", text: t(`type.${a.audio_type || "music"}`) }),
- el("span", { class: "job-prompt", title: promptLabel(a), text: promptLabel(a) }),
- el("span", { class: "job-state" }, active ? el("span", { class: "spinner", "aria-hidden": "true" }) : null,
- el("span", { class: "job-state-text", text: jobStateText(job) }))));
+ const head = el("div", { class: "job-head" },
+ el("span", { class: "badge", text: jobBadge(job) }),
+ el("span", { class: "job-prompt", title: jobTitle(job), text: jobTitle(job) }),
+ el("span", { class: "job-state" }, active ? el("span", { class: "spinner", "aria-hidden": "true" }) : null,
+ el("span", { class: "job-state-text", text: jobStateText(job) })));
+ const card = el("article", { class: "panel job", dataset: { status: job.status, id: job.id, tool: job.tool }, onkeydown: (e) => abKeys(e, card) }, head);
+ if (job.status === "queued") {
+ head.append(el("button", { class: "btn btn-sm btn-quiet", type: "button", text: t("act.cancel"), onclick: () => cancelJob(job) }));
+ }
if (job.status === "running") card.append(el("div", { class: "progress", "aria-hidden": "true" }, el("div")));
if (job.status === "error") card.append(el("p", { class: "job-error", text: job.error || "" }));
- if (job.status === "done" && job.result && Array.isArray(job.result.candidates)) {
- card.append(el("div", { class: "candidates" }, job.result.candidates.map(candidateCard)));
+ if (job.status === "done") {
+ const cands = resultCandidates(job);
+ if (job.result && job.result.candidates) {
+ card.append(el("div", { class: "candidates" }, cands.map((c, i) => candidateCard(c, i, job))));
+ } else {
+ card.append(el("div", { class: "candidates" }, cands.map((c) => candidateCard(c, 0, { ...job, result: { candidates: [c] } }))));
+ if (job.result && job.result.steps) card.append(el("p", { class: "muted small job-steps", text: job.result.steps.join(" → ") }));
+ }
+ const foot = el("div", { class: "job-foot" });
+ if (cands.length > 1) foot.append(el("span", { class: "muted small", text: t("cand.abHint") }));
+ if (job.tool === "generate_audio") {
+ foot.append(el("button", { class: "link-btn", type: "button", text: t("act.moreLike"), onclick: () => moreLikeThis(job) }));
+ }
+ if (foot.children.length) card.append(foot);
}
return card;
}
-function renderJobs() {
- const box = $("#jobs");
- const list = [...state.jobs.values()].sort((x, y) => y.created - x.created);
- $("#jobs-empty").hidden = list.length > 0;
- // Keep finished cards (their <audio> may be playing); rebuild only cards whose status changed.
+function updateProgress(card, job) {
+ const bar = card.querySelector(".progress > div"), est = estimate(job);
+ if (!bar) return;
+ if (est && state.loaded) {
+ bar.parentElement.classList.add("determinate");
+ bar.style.width = `${Math.min(95, (job.elapsed / est) * 100)}%`;
+ } else {
+ bar.parentElement.classList.remove("determinate");
+ bar.style.width = "";
+ }
+}
+// 1–4 (or A–D) play candidate N of this card from the same position; ←/→ step.
+function abKeys(e, card) {
+ if (typing(e) || e.metaKey || e.ctrlKey || e.altKey) return;
+ const minis = [...card.querySelectorAll(".mini-wave")].map((n) => n.mini);
+ if (minis.length < 2) return;
+ let i = "1234".indexOf(e.key);
+ if (i < 0) i = "abcd".indexOf(e.key.toLowerCase());
+ const cur = minis.indexOf(Player.owner);
+ if (e.key === "ArrowDown" || e.key === "ArrowUp") {
+ i = ((cur < 0 ? 0 : cur) + (e.key === "ArrowDown" ? 1 : minis.length - 1)) % minis.length;
+ }
+ if (i < 0 || i >= minis.length) return;
+ e.preventDefault();
+ const at = cur >= 0 ? Player.audio.currentTime : 0;
+ Player.play(minis[i], at);
+ minis[i].track.focus();
+}
+async function cancelJob(job) {
+ try { state.jobs.set(job.id, await api(`/api/jobs/${job.id}/cancel`, { json: {} })); }
+ catch (e) { toast(e.message); }
+ renderJobs();
+}
+function moreLikeThis(job) {
+ const args = { ...job.arguments };
+ delete args.seed; // new random seeds
+ delete args.title;
+ submitJob(args).then((j) => { if (j) toast(t("toast.moreQueued")); });
+}
+// Generate-page jobs go to Results; edit/process jobs to the editor of their input.
+function renderJobList(box, list) {
const existing = new Map([...box.children].map((n) => [n.dataset.id, n]));
const nodes = list.map((job) => {
const old = existing.get(job.id);
if (old && old.dataset.status === job.status && old.dataset.lang === state.lang) {
const st = old.querySelector(".job-state-text");
if (st) st.textContent = jobStateText(job);
+ updateProgress(old, job);
return old;
}
const card = jobCard(job);
card.dataset.lang = state.lang;
+ updateProgress(card, job);
return card;
});
nodes.forEach((n, i) => { if (box.children[i] !== n) box.insertBefore(n, box.children[i] || null); });
while (box.children.length > nodes.length) box.lastChild.remove();
}
+function renderJobs() {
+ const list = [...state.jobs.values()].sort((x, y) => y.created - x.created);
+ const gen = list.filter((j) => j.tool === "generate_audio");
+ renderJobList($("#jobs"), gen);
+ $("#jobs-empty").hidden = gen.length > 0;
+ Editor.renderJobs(list.filter((j) => j.tool !== "generate_audio"));
+}
+let unseen = 0;
+function noteFinished() {
+ if (!document.hidden) return;
+ unseen++;
+ document.title = `(${unseen}) ✓ Audio Studio`;
+}
+document.addEventListener("visibilitychange", () => { if (!document.hidden) { unseen = 0; document.title = "Audio Studio"; } });
async function pollJobs() {
if (state.polling) return;
state.polling = true;
@@ -327,11 +568,16 @@ async function pollJobs() {
let finished = false;
try {
const r = await api("/api/jobs");
+ state.loaded = r.loaded;
const seen = new Set();
for (const j of r.items) {
const prev = state.jobs.get(j.id);
- if (prev && prev.status !== j.status && (j.status === "done" || j.status === "error")) finished = true;
- state.jobs.set(j.id, j);
+ if (prev && prev.status !== j.status && (j.status === "done" || j.status === "error")) {
+ finished = true;
+ if (j.status === "done") { learnRate(j); noteFinished(); }
+ if (j.tool !== "generate_audio") Editor.jobFinished(j);
+ }
+ if (prev || j.status === "queued" || j.status === "running") state.jobs.set(j.id, j);
seen.add(j.id);
}
// The server restarted and forgot these: stop waiting for them.
@@ -342,7 +588,7 @@ async function pollJobs() {
}
renderJobs();
} catch { /* server restarting: keep trying */ }
- if (finished) refreshStatus();
+ if (finished) { refreshStatus(); if (!$("#page-library").hidden) loadLibrary(true); }
await new Promise((r) => setTimeout(r, 800));
}
} finally {
@@ -353,6 +599,7 @@ async function pollJobs() {
async function restoreJobs() {
try {
const r = await api("/api/jobs");
+ state.loaded = r.loaded;
// After a reload show the latest few jobs plus anything still waiting.
r.items.forEach((j, i) => { if (i < RESTORE_JOBS || j.status === "queued" || j.status === "running") state.jobs.set(j.id, j); });
renderJobs();
@@ -365,20 +612,28 @@ function metaRows(item) {
const m = item.meta;
if (!m) return [[t("meta.path"), item.path], ["", t("meta.noSidecar")]];
const sf = m.sound_fields && Object.values(m.sound_fields).filter(Boolean).join(" / ");
- const kind = String(m.kind || "");
const rows = [
- [t("meta.kind"), kind.startsWith("edit") ? `${t("kind.edit")} (${kind.split(":")[1] || ""})` : (I18N.en[`kind.${kind}`] ? t(`kind.${kind}`) : kind)],
+ [t("meta.kind"), kindLabel(m)],
[t("meta.type"), m.audio_type && t(`type.${m.audio_type}`)],
[t("meta.prompt"), m.prompt], [t("meta.sound"), sf], [t("meta.promptUsed"), m.prompt_used],
[t("meta.idea"), m.original_idea],
[t("meta.seconds"), fmtLen(typeof m.seconds === "number" ? m.seconds : item.seconds)],
[t("meta.bpm"), m.bpm], [t("meta.seed"), m.seed], [t("meta.cfg"), m.cfg], [t("meta.steps"), m.steps],
+ [t("meta.strength"), m.strength], [t("meta.region"), Array.isArray(m.region) ? m.region.map((x) => `${x}s`).join(" – ") : null],
[t("meta.negative"), m.negative_prompt],
+ [t("meta.stepsDone"), Array.isArray(m.steps) ? m.steps.join(" → ") : null],
+ [t("meta.format"), m.kind === "process" ? `${String(m.format || "").toUpperCase()} · ${m.sample_rate} Hz · ${m.channels === 1 ? "mono" : "stereo"}` : null],
+ [t("meta.loudness"), m.output_lufs != null ? `${m.output_lufs} LUFS` : null],
[t("meta.peak"), m.peak_dbfs != null ? `${m.peak_dbfs} dBFS` : null],
[t("meta.model"), m.model ? `${m.model} (${m.backend})` : null],
[t("meta.input"), m.input_audio], [t("meta.created"), m.created], [t("meta.path"), item.path],
];
- return rows.filter(([, v]) => v !== null && v !== undefined && v !== "");
+ return rows.filter(([, v]) => v !== null && v !== undefined && v !== "" && !(Array.isArray(v)));
+}
+function kindLabel(m) {
+ const kind = String(m.kind || "");
+ if (kind.startsWith("edit")) return `${t("kind.edit")} · ${t(`mode.${kind.split(":")[1]}`)}`;
+ return I18N.en[`kind.${kind}`] ? t(`kind.${kind}`) : kind;
}
function regenerate(item) {
const m = item.meta;
@@ -394,34 +649,39 @@ function libraryItem(item) {
const m = item.meta || {};
const title = m.title || item.file;
// The form has no "raw" type, so only these can be regenerated faithfully.
- const canRegen = m.kind === "generate" && m.seed != null && ["music", "instrument", "sfx"].includes(m.audio_type);
+ const canRegen = m.kind === "generate" && m.seed != null && TYPES.includes(m.audio_type);
const details = el("dl", { class: "item-details", hidden: true },
metaRows(item).flatMap(([k, v]) => [el("dt", { text: k }), el("dd", { text: String(v) })]));
- const toggle = el("button", { class: "link-btn", type: "button", "aria-expanded": "false", text: t("act.details") });
+ const toggle = el("button", { class: "btn btn-sm btn-quiet", type: "button", "aria-expanded": "false", text: t("act.details") });
toggle.addEventListener("click", () => {
details.hidden = !details.hidden;
toggle.setAttribute("aria-expanded", String(!details.hidden));
toggle.textContent = details.hidden ? t("act.details") : t("act.hideDetails");
});
const kind = String(m.kind || "");
- const badge = m.audio_type ? t(`type.${m.audio_type}`) : kind === "process" ? t("kind.process") : item.format.toUpperCase();
+ const badges = [m.audio_type ? t(`type.${m.audio_type}`) : null,
+ kind.startsWith("edit") ? t(`mode.${kind.split(":")[1]}`) : kind === "process" ? t("kind.process") : null,
+ kind === "process" || !m.kind ? item.format.toUpperCase() : null].filter(Boolean);
+ const mini = new MiniWave(item.file, item.seconds);
+ const sub = promptLabel({ prompt: m.prompt, ...prefixSound(m.sound_fields) }) || (m.source && m.source.prompt) || "";
return el("article", { class: "panel item" },
el("div", { class: "item-main" },
el("div", { class: "item-title", title: item.file, text: title }),
el("div", { class: "item-meta" },
- el("span", { class: "badge", text: badge }),
- kind.startsWith("edit") ? el("span", { class: "badge", text: t("kind.edit") }) : null,
- el("span", { text: fmtLen(item.seconds) }),
+ badges.map((b) => el("span", { class: "badge", text: b })),
el("span", { text: fmtDate(item.mtime) }),
m.seed != null ? el("span", { text: t("cand.seed", { seed: m.seed }) }) : null),
- m.prompt || m.sound_fields ? el("div", { class: "item-prompt", text: promptLabel({ prompt: m.prompt, ...prefixSound(m.sound_fields) }) }) : null),
+ sub ? el("div", { class: "item-prompt", title: sub, text: sub }) : null),
el("div", { class: "item-side" },
- el("audio", { controls: true, preload: "none", src: audioUrl(item.file) }),
+ mini.node,
el("div", { class: "item-actions" },
+ el("button", { class: "btn btn-sm", type: "button", text: t("act.edit"), onclick: () => openEditor(item.file) }),
+ el("a", { class: "btn btn-sm btn-quiet", href: audioUrl(item.file, true), download: item.file, text: t("act.download") }),
toggle,
- el("button", { class: "link-btn", type: "button", disabled: !canRegen, text: t("act.regen"), onclick: () => regenerate(item) }),
- el("button", { class: "link-btn", type: "button", text: t("act.copyPath"), onclick: () => copyText(item.path) }),
- el("a", { class: "link-btn", href: audioUrl(item.file, true), download: item.file, text: t("act.download") }))),
+ moreMenu([
+ canRegen ? [t("act.regen"), () => regenerate(item)] : null,
+ [t("act.copyPath"), () => copyText(item.path)],
+ ]))),
details);
}
function prefixSound(sf) {
@@ -433,7 +693,8 @@ function renderLibrary() {
box.replaceChildren(...L.items.map(libraryItem));
$("#lib-count").textContent = t("lib.count", { n: L.total });
$("#lib-empty").hidden = L.items.length > 0;
- $("#lib-empty").textContent = L.query ? t("lib.noMatch") : t("lib.empty");
+ $("#lib-empty-text").textContent = L.query ? t("lib.noMatch", { q: L.query }) : t("lib.empty");
+ $("#lib-empty-btn").textContent = L.query ? t("lib.clearSearch") : t("lib.generateFirst");
$("#lib-more").hidden = L.items.length >= L.total;
}
let libSeq = 0;
@@ -460,12 +721,18 @@ function initLibrary() {
});
$("#lib-refresh").addEventListener("click", () => loadLibrary(true));
$("#lib-more").addEventListener("click", () => loadLibrary(false));
+ $("#lib-empty-btn").addEventListener("click", () => {
+ if (state.lib.query) { $("#lib-search").value = ""; state.lib.query = ""; loadLibrary(true); }
+ else { showPage("generate"); $("#prompt").focus(); }
+ });
}
// ── boot ─────────────────────────────────────────────────────────────────────
+Player.init();
initSettings();
initForm();
initLibrary();
+Editor.init();
applyI18n();
initTabs();
refreshStatus();
diff --git a/src/audio_studio_mcp/static/editor.js b/src/audio_studio_mcp/static/editor.js
new file mode 100644
index 0000000..43d5fab
--- /dev/null
+++ b/src/audio_studio_mcp/static/editor.js
@@ -0,0 +1,676 @@
+// Edit page: waveform with zoom, playhead and a drag-selected range, then
+// "Change with AI" (edit_audio: variation / inpaint / continue) and "Export"
+// (process_audio). Mouse: click = move the playhead (outside the selection it
+// also clears it), drag = select, Shift+click = move the nearest edge,
+// double-click = select all, Ctrl/⌘+wheel = zoom, horizontal wheel = scroll.
+"use strict";
+
+const OVERVIEW_N = 4000;
+const MIN_SPAN = 0.05; // seconds visible at the deepest zoom
+const DRAG_PX = 4; // movement that turns a click into a selection
+
+// Export presets: what the user is making → process_audio settings.
+const PRESETS = {
+ game_sfx: { trim_silence: true, mono: true, loop: false, normalize: "peak", target_lufs: -16, peak_ceiling_db: -1,
+ loop_crossfade_ms: 200, fade_in_ms: 0, fade_out_ms: 0, format: "ogg", sample_rate: "48000" },
+ game_loop: { trim_silence: false, mono: false, loop: true, normalize: "loudness", target_lufs: -16, peak_ceiling_db: -1,
+ loop_crossfade_ms: 200, fade_in_ms: 0, fade_out_ms: 0, format: "ogg", sample_rate: "48000" },
+ video_bgm: { trim_silence: false, mono: false, loop: false, normalize: "loudness", target_lufs: -14, peak_ceiling_db: -1,
+ loop_crossfade_ms: 200, fade_in_ms: 500, fade_out_ms: 2000, format: "wav", sample_rate: "48000" },
+ original: { trim_silence: false, mono: false, loop: false, normalize: "none", target_lufs: -16, peak_ceiling_db: -1,
+ loop_crossfade_ms: 200, fade_in_ms: 0, fade_out_ms: 0, format: "wav", sample_rate: "44100" },
+};
+const PRESET_ORDER = ["game_sfx", "game_loop", "video_bgm", "original", "custom"];
+
+const Editor = {
+ file: null, item: null, seconds: 0, sampleRate: 0, channels: 0,
+ view: { s: 0, e: 1 }, sel: null, playhead: 0, playSel: false,
+ overview: null, detail: null, detailTimer: null, drag: null,
+ audio: new Audio(), visible: false, openSeq: 0,
+
+ // ── setup ──────────────────────────────────────────────────────────────
+ init() {
+ const a = this.audio;
+ a.preload = "auto";
+ a.addEventListener("play", () => { window.dispatchEvent(new CustomEvent("as:play", { detail: "editor" })); this.tick(); this.renderTransport(); });
+ a.addEventListener("pause", () => this.renderTransport());
+ a.addEventListener("ended", () => { this.playhead = this.seconds; this.draw(); this.renderTransport(); });
+ window.addEventListener("as:play", (e) => { if (e.detail !== "editor") a.pause(); });
+
+ const wave = $("#w-wave");
+ wave.addEventListener("pointerdown", (e) => this.pointerDown(e));
+ wave.addEventListener("pointermove", (e) => this.pointerMove(e));
+ wave.addEventListener("pointerup", (e) => this.pointerUp(e));
+ wave.addEventListener("pointercancel", () => { this.drag = null; });
+ wave.addEventListener("dblclick", () => this.selectAll());
+ wave.addEventListener("wheel", (e) => this.wheel(e), { passive: false });
+ wave.addEventListener("keydown", (e) => this.waveKey(e));
+ for (const [id, edge] of [["#w-h-start", "a"], ["#w-h-end", "b"]]) {
+ $(id).addEventListener("pointerdown", (e) => { e.stopPropagation(); this.startEdgeDrag(e, edge); });
+ $(id).addEventListener("keydown", (e) => this.handleKey(e, edge));
+ }
+ const ov = $("#w-overview");
+ ov.addEventListener("pointerdown", (e) => { ov.setPointerCapture(e.pointerId); this.overviewSeek(e); });
+ ov.addEventListener("pointermove", (e) => { if (e.buttons & 1) this.overviewSeek(e); });
+
+ $("#w-play").addEventListener("click", () => this.togglePlay());
+ $("#w-loop").addEventListener("change", (e) => { this.audio.loop = e.target.checked && !this.sel; });
+ $("#w-zoom-in").addEventListener("click", () => this.zoom(0.5));
+ $("#w-zoom-out").addEventListener("click", () => this.zoom(2));
+ $("#w-zoom-fit").addEventListener("click", () => this.setView(0, this.seconds));
+ $("#w-zoom-sel").addEventListener("click", () => this.zoomToSelection());
+ $("#w-sel-all").addEventListener("click", () => this.selectAll());
+ $("#w-sel-clear").addEventListener("click", () => this.setSel(null));
+ for (const id of ["#w-start", "#w-end"]) $(id).addEventListener("change", () => this.selFromInputs());
+ $("#edit-to-library").addEventListener("click", () => showPage("library"));
+ document.addEventListener("keydown", (e) => this.globalKey(e));
+ new ResizeObserver(() => { if (this.visible) { this.scheduleDetail(); this.draw(); } }).observe($("#w-wave"));
+ window.addEventListener("as:theme", () => this.draw());
+ matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () => this.draw());
+
+ // sub tabs
+ for (const b of document.querySelectorAll(".subtabs [role=tab]")) {
+ b.addEventListener("click", () => {
+ for (const o of document.querySelectorAll(".subtabs [role=tab]")) {
+ o.setAttribute("aria-selected", String(o === b));
+ $(`#${o.getAttribute("aria-controls")}`).hidden = o !== b;
+ }
+ });
+ }
+ this.initAiForm();
+ this.initExportForm();
+ },
+ applyI18n() {
+ this.renderTransport();
+ this.renderSelection();
+ this.renderInfo();
+ this.updateAiForm();
+ this.renderPresets();
+ this.updateExportForm();
+ if (!this.file) this.renderRecent();
+ },
+
+ // ── open a file ────────────────────────────────────────────────────────
+ async open(file) {
+ if (file === this.file && this.overview) return;
+ const seq = ++this.openSeq;
+ this.audio.pause();
+ this.file = file;
+ this.item = null; this.overview = null; this.detail = null; this.sel = null; this.playhead = 0;
+ this.seconds = 0;
+ $("#edit-empty").hidden = true;
+ $("#edit-main").hidden = false;
+ $("#w-loading").hidden = false;
+ $("#w-loading").textContent = t("wave.loading");
+ this.audio.src = audioUrl(file);
+ this.renderInfo();
+ let item, peaks;
+ try {
+ [item, peaks] = await Promise.all([api(`/api/library/${encodeURIComponent(file)}`), Peaks.get(file, OVERVIEW_N)]);
+ } catch (e) {
+ if (seq !== this.openSeq) return;
+ this.file = null;
+ this.audio.removeAttribute("src");
+ toast(e.status === 404 ? t("edit.notFound", { file }) : e.message);
+ this.showEmpty();
+ if (location.hash.startsWith("#edit/")) history.replaceState(null, "", "#edit");
+ return;
+ }
+ if (seq !== this.openSeq) return;
+ this.item = item; this.overview = peaks;
+ this.seconds = peaks.seconds; this.sampleRate = peaks.sample_rate; this.channels = peaks.channels;
+ this.view = { s: 0, e: this.seconds || 1 };
+ $("#w-loading").hidden = true;
+ $("#w-start").max = $("#w-end").max = String(this.seconds);
+ this.prefill();
+ this.renderInfo();
+ this.renderSelection();
+ this.renderTransport();
+ this.draw();
+ renderJobs();
+ },
+ showEmpty() {
+ $("#edit-main").hidden = true;
+ $("#edit-empty").hidden = false;
+ this.renderRecent();
+ },
+ shown() {
+ this.visible = true;
+ if (!this.file) { this.showEmpty(); return; }
+ requestAnimationFrame(() => this.draw());
+ },
+ hidden() {
+ this.visible = false;
+ this.audio.pause();
+ },
+ async renderRecent() {
+ const box = $("#edit-recent");
+ let items = [];
+ try { items = (await api("/api/library?limit=6")).items; } catch { /* offline */ }
+ box.replaceChildren(...items.map((it) => el("button", { type: "button", class: "recent-item", onclick: () => openEditor(it.file) },
+ el("span", { class: "recent-name", text: (it.meta && it.meta.title) || it.file }),
+ el("span", { class: "muted small", text: `${fmtLen(it.seconds)} · ${fmtDate(it.mtime)}` }))));
+ if (items.length) box.prepend(el("p", { class: "small muted recent-head", text: t("edit.recent") }));
+ },
+ renderInfo() {
+ if (!this.file) return;
+ const m = (this.item && this.item.meta) || {};
+ $("#edit-name").textContent = m.title || this.file;
+ $("#edit-name").title = this.file;
+ const parts = [];
+ if (this.seconds) parts.push(fmtClock(this.seconds, 1));
+ if (this.sampleRate) parts.push(`${(this.sampleRate / 1000).toFixed(1).replace(/\.0$/, "")} kHz`, this.channels === 1 ? t("edit.mono") : t("edit.stereo"));
+ if (m.audio_type) parts.push(t(`type.${m.audio_type}`));
+ if (m.kind) parts.push(kindLabel(m));
+ $("#edit-info").textContent = parts.join(" · ");
+ const src = $("#edit-source");
+ src.replaceChildren();
+ if (m.input_audio) {
+ const name = baseName(m.input_audio);
+ src.append(el("span", { class: "muted", text: t("edit.madeFrom") }), " ",
+ el("button", { type: "button", class: "link-btn", text: name, onclick: () => openEditor(name) }));
+ }
+ },
+
+ // ── geometry and drawing ─────────────────────────────────────────────────
+ width() { return $("#w-wave").clientWidth || 1; },
+ t2x(t) { return ((t - this.view.s) / (this.view.e - this.view.s)) * this.width(); },
+ x2t(x) { return this.view.s + (x / this.width()) * (this.view.e - this.view.s); },
+ clampT(t) { return Math.max(0, Math.min(this.seconds, t)); },
+ eventT(e) { return this.clampT(this.x2t(e.clientX - $("#w-wave").getBoundingClientRect().left)); },
+ setView(s, e) {
+ if (!this.seconds) return;
+ let span = Math.max(MIN_SPAN, Math.min(this.seconds, e - s));
+ s = Math.max(0, Math.min(this.seconds - span, s));
+ this.view = { s, e: s + span };
+ this.scheduleDetail();
+ this.draw();
+ },
+ zoom(factor, center) {
+ const { s, e } = this.view, span = e - s;
+ if (center == null) center = this.playhead >= s && this.playhead <= e ? this.playhead : (s + e) / 2;
+ const ns = span * factor, k = (center - s) / span;
+ this.setView(center - k * ns, center - k * ns + ns);
+ },
+ zoomToSelection() {
+ if (!this.sel) return;
+ const pad = (this.sel.b - this.sel.a) * 0.05;
+ this.setView(this.sel.a - pad, this.sel.b + pad);
+ },
+ // Fetch finer peaks when the overview has fewer buckets than pixels in view.
+ scheduleDetail() {
+ clearTimeout(this.detailTimer);
+ if (!this.overview || !this.seconds) return;
+ const px = this.width() * (window.devicePixelRatio || 1);
+ const span = this.view.e - this.view.s;
+ if (OVERVIEW_N * (span / this.seconds) >= px) return;
+ const d = this.detail;
+ if (d && d.start <= this.view.s && d.end >= this.view.e && d.min.length / (d.end - d.start) * span >= px) return;
+ this.detailTimer = setTimeout(async () => {
+ const s = Math.max(0, this.view.s - span / 2), e = Math.min(this.seconds, this.view.e + span / 2);
+ const n = Math.min(20000, Math.ceil(px * ((e - s) / span)));
+ const file = this.file;
+ try {
+ const p = await Peaks.get(file, n, s, e);
+ if (file === this.file) { this.detail = p; this.draw(); }
+ } catch { /* keep the overview */ }
+ }, 120);
+ },
+ draw() {
+ if (!this.visible || !this.overview) return;
+ const cv = $("#w-canvas"), ctx = fitCanvas(cv), W = cv.width, H = cv.height;
+ ctx.clearRect(0, 0, W, H);
+ ctx.fillStyle = cssVar("--wave-axis");
+ ctx.fillRect(0, Math.floor(H / 2), W, 1);
+ const { s, e } = this.view, span = e - s;
+ const d = this.detail && this.detail.start <= s + 1e-6 && this.detail.end >= e - 1e-6 ? this.detail : this.overview;
+ const dStart = d === this.overview ? 0 : d.start, dEnd = d === this.overview ? this.seconds : d.end;
+ const n = d.min.length;
+ // slice the buckets in view, then draw them across the canvas
+ const i0 = Math.max(0, Math.floor(((s - dStart) / (dEnd - dStart)) * n));
+ const i1 = Math.min(n, Math.ceil(((e - dStart) / (dEnd - dStart)) * n));
+ const t0 = dStart + (i0 / n) * (dEnd - dStart), t1 = dStart + (i1 / n) * (dEnd - dStart);
+ drawPeaks(ctx, d.min.slice(i0, i1), d.max.slice(i0, i1), {
+ color: cssVar("--wave"), played: cssVar("--wave-played"),
+ split: (this.playhead - t0) / Math.max(1e-9, t1 - t0),
+ x0: ((t0 - s) / span) * W, x1: ((t1 - s) / span) * W, gain: 0.95 });
+ this.drawRuler();
+ this.drawOverview();
+ this.renderOverlay();
+ },
+ drawRuler() {
+ const cv = $("#w-ruler"), ctx = fitCanvas(cv), W = cv.width, H = cv.height, dpr = window.devicePixelRatio || 1;
+ ctx.clearRect(0, 0, W, H);
+ const { s, e } = this.view, span = e - s;
+ const steps = [0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10, 15, 30, 60, 120, 300];
+ const minPx = 80 * dpr;
+ const step = steps.find((st) => (st / span) * W >= minPx) || 600;
+ const decimals = step < 0.1 ? 2 : step < 1 ? 1 : 0;
+ ctx.fillStyle = cssVar("--muted");
+ ctx.strokeStyle = cssVar("--border-strong");
+ ctx.font = `${11 * dpr}px system-ui, sans-serif`;
+ ctx.textBaseline = "top";
+ for (let tk = Math.ceil(s / step) * step; tk <= e + 1e-9; tk += step) {
+ const x = Math.round(((tk - s) / span) * W) + 0.5;
+ ctx.beginPath(); ctx.moveTo(x, H - 6 * dpr); ctx.lineTo(x, H); ctx.stroke();
+ ctx.fillText(fmtClock(tk, decimals), x + 3 * dpr, 2 * dpr);
+ }
+ },
+ drawOverview() {
+ const box = $("#w-overview"), zoomed = this.view.e - this.view.s < this.seconds * 0.999;
+ box.hidden = !zoomed;
+ if (!zoomed) return;
+ const cv = $("#w-ov-canvas"), ctx = fitCanvas(cv);
+ ctx.clearRect(0, 0, cv.width, cv.height);
+ drawPeaks(ctx, this.overview.min, this.overview.max, { color: cssVar("--wave"), gain: 0.9 });
+ const vb = $("#w-view");
+ vb.style.left = `${(this.view.s / this.seconds) * 100}%`;
+ vb.style.width = `${Math.max(0.5, ((this.view.e - this.view.s) / this.seconds) * 100)}%`;
+ },
+ overviewSeek(e) {
+ const r = $("#w-overview").getBoundingClientRect();
+ const c = ((e.clientX - r.left) / r.width) * this.seconds, span = this.view.e - this.view.s;
+ this.setView(c - span / 2, c + span / 2);
+ },
+ renderOverlay() {
+ const W = this.width(), ph = $("#w-playhead"), x = this.t2x(this.playhead);
+ ph.hidden = x < -1 || x > W + 1;
+ ph.style.left = `${x}px`;
+ const wave = $("#w-wave");
+ wave.setAttribute("aria-valuemax", String(Math.round(this.seconds * 100) / 100));
+ wave.setAttribute("aria-valuenow", String(Math.round(this.playhead * 100) / 100));
+ wave.setAttribute("aria-valuetext", `${fmtClock(this.playhead, 1)} / ${fmtClock(this.seconds, 1)}`);
+ const box = $("#w-sel");
+ if (!this.sel) { box.hidden = true; return; }
+ const a = this.t2x(this.sel.a), b = this.t2x(this.sel.b);
+ box.hidden = b < 0 || a > W;
+ box.style.left = `${a}px`;
+ box.style.width = `${Math.max(1, b - a)}px`;
+ for (const [id, v] of [["#w-h-start", this.sel.a], ["#w-h-end", this.sel.b]]) {
+ const h = $(id);
+ h.setAttribute("aria-valuemin", "0");
+ h.setAttribute("aria-valuemax", String(Math.round(this.seconds * 100) / 100));
+ h.setAttribute("aria-valuenow", String(Math.round(v * 100) / 100));
+ h.setAttribute("aria-valuetext", fmtClock(v, 2));
+ }
+ },
+
+ // ── selection ──────────────────────────────────────────────────────────
+ setSel(sel, { quiet } = {}) {
+ const had = !!this.sel;
+ if (sel) {
+ let a = this.clampT(Math.min(sel.a, sel.b)), b = this.clampT(Math.max(sel.a, sel.b));
+ sel = b - a >= 0.01 ? { a, b } : null;
+ }
+ this.sel = sel;
+ this.audio.loop = $("#w-loop").checked && !sel;
+ if (!!sel !== had) $("#x-trim-sel").checked = !!sel; // a new selection is usually what to export
+ this.renderSelection(quiet);
+ this.draw();
+ this.updateAiForm();
+ this.updateExportForm();
+ },
+ selectAll() { if (this.seconds) this.setSel({ a: 0, b: this.seconds }); },
+ selFromInputs() {
+ const a = parseFloat($("#w-start").value), b = parseFloat($("#w-end").value);
+ const bad = !(a >= 0 && b > a && b <= this.seconds + 1e-6);
+ $("#w-start").toggleAttribute("aria-invalid", bad && !(a >= 0));
+ $("#w-end").toggleAttribute("aria-invalid", bad);
+ if (!bad) this.setSel({ a, b }, { quiet: true });
+ },
+ renderSelection(quiet) {
+ const s = this.sel;
+ if (!quiet || !s) {
+ $("#w-start").value = s ? s.a.toFixed(2) : "";
+ $("#w-end").value = s ? s.b.toFixed(2) : "";
+ $("#w-start").removeAttribute("aria-invalid"); $("#w-end").removeAttribute("aria-invalid");
+ }
+ $("#w-start").placeholder = "0.00";
+ $("#w-end").placeholder = this.seconds ? this.seconds.toFixed(2) : "";
+ $("#w-len").textContent = s ? t("wave.length", { len: (s.b - s.a).toFixed(2) }) : t("wave.noSelection");
+ $("#w-sel-clear").disabled = !s;
+ $("#w-zoom-sel").disabled = !s;
+ },
+
+ // ── pointer / keyboard ─────────────────────────────────────────────────
+ pointerDown(e) {
+ if (e.button !== 0 || !this.seconds) return;
+ const wave = $("#w-wave");
+ wave.setPointerCapture(e.pointerId);
+ wave.focus({ preventScroll: true });
+ const tm = this.eventT(e);
+ if (e.shiftKey && this.sel) {
+ const edge = Math.abs(tm - this.sel.a) < Math.abs(tm - this.sel.b) ? "a" : "b";
+ this.drag = { mode: "edge", edge };
+ this.setSel({ ...this.sel, [edge]: tm });
+ } else {
+ this.drag = { mode: "pending", x0: e.clientX, anchor: tm };
+ }
+ },
+ startEdgeDrag(e, edge) {
+ if (e.button !== 0) return;
+ $("#w-wave").setPointerCapture(e.pointerId);
+ this.drag = { mode: "edge", edge };
+ },
+ pointerMove(e) {
+ const d = this.drag;
+ if (!d) return;
+ const tm = this.eventT(e);
+ if (d.mode === "pending" && Math.abs(e.clientX - d.x0) > DRAG_PX) d.mode = "select";
+ if (d.mode === "select") this.setSel({ a: d.anchor, b: tm });
+ else if (d.mode === "edge" && this.sel) {
+ const other = d.edge === "a" ? this.sel.b : this.sel.a;
+ if ((d.edge === "a" && tm > other) || (d.edge === "b" && tm < other)) d.edge = d.edge === "a" ? "b" : "a";
+ this.setSel(d.edge === "a" ? { a: tm, b: other } : { a: other, b: tm });
+ }
+ },
+ pointerUp(e) {
+ const d = this.drag;
+ this.drag = null;
+ if (!d || d.mode !== "pending") return;
+ const tm = this.eventT(e);
+ if (this.sel && (tm < this.sel.a || tm > this.sel.b)) this.setSel(null);
+ this.seek(tm);
+ },
+ wheel(e) {
+ if (!this.seconds) return;
+ const span = this.view.e - this.view.s;
+ if (e.ctrlKey || e.metaKey) {
+ e.preventDefault();
+ this.zoom(Math.exp(Math.max(-1, Math.min(1, e.deltaY * 0.01))), this.eventT(e));
+ } else if (Math.abs(e.deltaX) > Math.abs(e.deltaY) || e.shiftKey) {
+ if (span >= this.seconds) return;
+ e.preventDefault();
+ const dx = Math.abs(e.deltaX) > Math.abs(e.deltaY) ? e.deltaX : e.deltaY;
+ const dt = (dx / this.width()) * span;
+ this.setView(this.view.s + dt, this.view.e + dt);
+ }
+ },
+ waveKey(e) {
+ const step = e.shiftKey ? 5 : 1;
+ if (e.key === "ArrowRight") this.seek(this.playhead + step);
+ else if (e.key === "ArrowLeft") this.seek(this.playhead - step);
+ else if (e.key === "Home") this.seek(this.sel ? this.sel.a : 0);
+ else if (e.key === "End") this.seek(this.sel ? this.sel.b : this.seconds);
+ else return;
+ e.preventDefault();
+ },
+ handleKey(e, edge) {
+ if (!this.sel) return;
+ const step = e.shiftKey ? 0.1 : 0.01;
+ const d = e.key === "ArrowRight" || e.key === "ArrowUp" ? step : e.key === "ArrowLeft" || e.key === "ArrowDown" ? -step : 0;
+ if (!d) return;
+ e.preventDefault();
+ e.stopPropagation();
+ this.setSel({ ...this.sel, [edge]: this.sel[edge] + d });
+ },
+ globalKey(e) {
+ if (!this.visible || !this.file || typing(e) || e.altKey) return;
+ if (e.target.closest && e.target.closest("button, a, summary, [role=menuitem]") && (e.key === " " || e.key === "Enter")) return;
+ const k = e.key;
+ if ((e.metaKey || e.ctrlKey) && k.toLowerCase() === "a") { e.preventDefault(); this.selectAll(); return; }
+ if (e.metaKey || e.ctrlKey) {
+ if (k === "0") { e.preventDefault(); this.setView(0, this.seconds); }
+ return;
+ }
+ if (k === " ") { e.preventDefault(); this.togglePlay(); }
+ else if (k === "l" || k === "L") { $("#w-loop").click(); }
+ else if (k === "Escape") { if (!document.querySelector("details.menu[open]")) this.setSel(null); }
+ else if (k === "+" || k === "=") this.zoom(0.5);
+ else if (k === "-" || k === "_") this.zoom(2);
+ else if (k === "0") this.setView(0, this.seconds);
+ else if (k === "z" || k === "Z") this.zoomToSelection();
+ },
+
+ // ── playback ───────────────────────────────────────────────────────────
+ seek(tm) {
+ this.playhead = this.clampT(tm);
+ this.playSel = !!this.sel && this.playhead >= this.sel.a && this.playhead < this.sel.b;
+ if (this.audio.readyState >= 1) this.audio.currentTime = this.playhead;
+ this.followPlayhead();
+ this.draw();
+ this.renderTransport();
+ },
+ async togglePlay() {
+ const a = this.audio;
+ if (!a.paused) { a.pause(); return; }
+ let start = this.playhead;
+ if (this.sel && (start < this.sel.a || start >= this.sel.b - 0.01)) start = this.sel.a;
+ else if (!this.sel && start >= this.seconds - 0.01) start = 0;
+ this.playSel = !!this.sel;
+ if (a.readyState < 1) await new Promise((r) => a.addEventListener("loadedmetadata", r, { once: true }));
+ a.currentTime = start;
+ this.playhead = start;
+ try { await a.play(); } catch { /* interrupted */ }
+ },
+ tick() {
+ const a = this.audio;
+ if (a.paused) { this.draw(); return; }
+ let tm = a.currentTime;
+ if (this.playSel && this.sel && tm >= this.sel.b) {
+ if ($("#w-loop").checked) { a.currentTime = tm = this.sel.a; }
+ else { a.pause(); a.currentTime = tm = this.sel.a; }
+ }
+ this.playhead = tm;
+ this.followPlayhead();
+ this.draw();
+ this.renderClock();
+ requestAnimationFrame(() => this.tick());
+ },
+ // Page the view along while playing (or after a seek) so the playhead stays visible.
+ followPlayhead() {
+ const { s, e } = this.view, span = e - s;
+ if (span >= this.seconds) return;
+ if (this.playhead > e || this.playhead < s) this.setView(this.playhead - span * 0.1, this.playhead + span * 0.9);
+ },
+ renderClock() {
+ $("#w-clock").textContent = `${fmtClock(this.playhead, 1)} / ${fmtClock(this.seconds, 1)}`;
+ },
+ renderTransport() {
+ const playing = !this.audio.paused;
+ $("#w-play").classList.toggle("playing", playing);
+ $("#w-play-text").textContent = playing ? t("player.pause") : this.sel ? t("wave.playSel") : t("player.play");
+ this.renderClock();
+ },
+
+ // ── Change with AI (edit_audio) ──────────────────────────────────────────
+ aiField(name) { return $("#ai-form").elements.namedItem(name); },
+ aiMode() { return this.aiField("mode").value; },
+ initAiForm() {
+ const f = $("#ai-form");
+ f.addEventListener("change", () => this.updateAiForm());
+ f.addEventListener("input", (e) => { if (e.target.removeAttribute) e.target.removeAttribute("aria-invalid"); this.updateAiForm(); });
+ f.addEventListener("submit", (e) => { e.preventDefault(); this.submitAi(); });
+ f.addEventListener("keydown", (e) => { if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) { e.preventDefault(); f.requestSubmit(); } });
+ },
+ max() { return state.status ? state.status.max_seconds : 380; },
+ extendDefault() {
+ const s = this.seconds;
+ return Math.min(this.max(), Math.ceil(s + Math.min(30, Math.max(5, s))));
+ },
+ prefill() {
+ const m = (this.item && this.item.meta) || {};
+ const src = m.source || {};
+ const type = TYPES.includes(m.audio_type) ? m.audio_type : TYPES.includes(src.audio_type) ? src.audio_type : "music";
+ this.aiField("audio_type").value = type;
+ const prompt = m.prompt || promptLabel({ prompt: "", ...prefixSound(m.sound_fields) }) || src.prompt || "";
+ this.aiField("prompt").value = prompt;
+ this.aiField("duration_seconds").value = this.extendDefault();
+ for (const k of ["title", "seed", "cfg", "steps", "negative_prompt"]) this.aiField(k).value = "";
+ clearErrors($("#ai-form"), $("#ai-error"));
+ // export: a preset that suits the kind of sound
+ this.setPreset(type === "sfx" ? "game_sfx" : type === "instrument" ? "game_loop" : "video_bgm");
+ $("#export-form").elements.namedItem("title").value = "";
+ clearErrors($("#export-form"), $("#x-error"));
+ this.updateAiForm();
+ },
+ selText() { return this.sel ? `${fmtClock(this.sel.a, 1)}–${fmtClock(this.sel.b, 1)}` : ""; },
+ updateAiForm() {
+ if (!$("#ai-form")) return;
+ const mode = this.aiMode(), n = parseInt(this.aiField("variations").value, 10) || 1;
+ $("#strength-field").hidden = mode !== "variation";
+ $("#inpaint-note").hidden = mode !== "inpaint";
+ $("#extend-field").hidden = mode !== "continue";
+ $("#strength-out").textContent = Number(this.aiField("strength").value).toFixed(2);
+ for (const c of document.querySelectorAll(".mode-card")) c.classList.toggle("checked", c.querySelector("input").checked);
+ const note = $("#inpaint-note");
+ note.classList.toggle("warn", !this.sel);
+ note.textContent = this.sel ? t("edit.inpaintSel", { range: this.selText() }) : t("edit.inpaintNoSel");
+ $("#ai-prompt-hint").textContent = t(`edit.promptHint.${mode}`);
+ // extend
+ const dur = this.aiField("duration_seconds");
+ dur.min = String(Math.floor(this.seconds) + 1);
+ dur.max = String(this.max());
+ const target = parseFloat(dur.value);
+ $("#extend-hint").textContent = t("edit.extendHint", { now: fmtClock(this.seconds, 1), max: this.max() });
+ const adds = [5, 10, 30, 60].filter((d) => this.seconds + d <= this.max());
+ $("#extend-chips").replaceChildren(...adds.map((d) => el("button", { type: "button", class: "chip",
+ "aria-pressed": String(Math.abs(target - Math.ceil(this.seconds + d)) < 0.01), text: `+${d} s`,
+ onclick: () => { dur.value = Math.ceil(this.seconds + d); this.updateAiForm(); } })));
+ // submit label states what will happen
+ const btn = $("#ai-submit");
+ btn.disabled = !this.file || (mode === "inpaint" && !this.sel);
+ if (mode === "variation") btn.textContent = n > 1 ? t("edit.submitVariationN", { n }) : t("edit.submitVariation");
+ else if (mode === "inpaint") btn.textContent = this.sel ? t("edit.submitInpaint", { range: this.selText() }) : t("mode.inpaint");
+ else btn.textContent = t("edit.submitContinue", { len: target > 0 ? fmtClock(target) : "—" });
+ if (n > 1 && mode !== "variation") btn.textContent += ` × ${n}`;
+ },
+ async submitAi() {
+ const f = $("#ai-form"), mode = this.aiMode();
+ clearErrors(f, $("#ai-error"));
+ if (mode === "inpaint" && !this.sel) return;
+ const args = { input_audio: this.file, mode, audio_type: this.aiField("audio_type").value,
+ prompt: this.aiField("prompt").value.trim(), variations: parseInt(this.aiField("variations").value, 10) };
+ let expect = this.seconds;
+ if (mode === "variation") args.strength = Number(this.aiField("strength").value);
+ if (mode === "inpaint") { args.start_seconds = +this.sel.a.toFixed(3); args.end_seconds = +this.sel.b.toFixed(3); }
+ if (mode === "continue") {
+ const raw = this.aiField("duration_seconds").value.trim();
+ if (raw !== "") args.duration_seconds = Number(raw);
+ expect = args.duration_seconds || expect;
+ }
+ for (const k of ["seed", "cfg", "steps"]) {
+ const raw = this.aiField(k).value.trim();
+ if (raw !== "") args[k] = Number(raw);
+ }
+ for (const k of ["title", "negative_prompt"]) {
+ const v = this.aiField(k).value.trim();
+ if (v) args[k] = v;
+ }
+ const btn = $("#ai-submit");
+ btn.disabled = true;
+ const job = await queueJob("edit_audio", args, { expectSeconds: expect * args.variations,
+ onError: (e) => showFormError(e.message, e.body && e.body.fields, f, $("#ai-error"), $("#ai-advanced")) });
+ this.updateAiForm();
+ if (job) toast(t("toast.editQueued"));
+ },
+
+ // ── Export (process_audio) ───────────────────────────────────────────────
+ xField(name) { return $("#export-form").elements.namedItem(name); },
+ initExportForm() {
+ const f = $("#export-form");
+ f.addEventListener("change", (e) => {
+ if (e.target.name === "preset") this.setPreset(e.target.value);
+ else if (e.target.name !== "trim_selection" && e.target.name !== "title") this.markCustom();
+ this.updateExportForm();
+ });
+ f.addEventListener("input", (e) => {
+ if (e.target.removeAttribute) e.target.removeAttribute("aria-invalid");
+ if (e.target.type === "number") this.markCustom();
+ this.updateExportForm();
+ });
+ f.addEventListener("submit", (e) => { e.preventDefault(); this.submitExport(); });
+ this.renderPresets();
+ },
+ renderPresets() {
+ const box = $("#presets");
+ if (!box) return;
+ const cur = this.preset || "original";
+ box.replaceChildren(...PRESET_ORDER.map((p) => el("label", { class: `preset${p === cur ? " checked" : ""}` },
+ el("input", { type: "radio", name: "preset", value: p, checked: p === cur }),
+ el("span", { class: "preset-name", text: t(`preset.${p}`) }))));
+ $("#preset-desc").textContent = t(`preset.${cur}Desc`);
+ },
+ setPreset(p) {
+ this.preset = p;
+ const v = PRESETS[p];
+ if (v) {
+ for (const [k, val] of Object.entries(v)) {
+ const fld = this.xField(k);
+ if (!fld) continue;
+ if (fld instanceof RadioNodeList) fld.value = String(val);
+ else if (fld.type === "checkbox") fld.checked = val;
+ else fld.value = String(val);
+ }
+ }
+ if (p === "custom") $("#x-custom").open = true;
+ this.renderPresets();
+ this.updateExportForm();
+ },
+ markCustom() {
+ if (this.preset !== "custom") { this.preset = "custom"; this.renderPresets(); }
+ },
+ updateExportForm() {
+ if (!$("#export-form")) return;
+ const trim = this.xField("trim_selection");
+ trim.disabled = !this.sel;
+ if (!this.sel) trim.checked = false;
+ $("#x-trim-sel-text").textContent = this.sel ? t("exp.trimSel", { range: this.selText() }) : t("exp.trimSelNone");
+ $("#trim-sel-row").classList.toggle("disabled", !this.sel);
+ const norm = this.xField("normalize").value;
+ $("#x-lufs-field").hidden = norm !== "loudness";
+ $("#x-xfade-field").hidden = !this.xField("loop").checked;
+ // plain-language summary of what the export will do
+ const parts = [];
+ if (trim.checked) parts.push(t("sum.trim", { range: this.selText() }));
+ if (this.xField("trim_silence").checked) parts.push(t("sum.silence"));
+ if (this.xField("mono").checked) parts.push(t("sum.mono"));
+ if (norm === "peak") parts.push(t("sum.peak", { db: this.xField("peak_ceiling_db").value }));
+ if (norm === "loudness") parts.push(t("sum.lufs", { lufs: this.xField("target_lufs").value }));
+ if (this.xField("loop").checked) parts.push(t("sum.loop", { ms: this.xField("loop_crossfade_ms").value }));
+ const fi = Number(this.xField("fade_in_ms").value), fo = Number(this.xField("fade_out_ms").value);
+ if (fi || fo) parts.push(t("sum.fade", { a: fi, b: fo }));
+ const fmt = String(this.xField("format").value).toUpperCase(), sr = Number(this.xField("sample_rate").value) / 1000;
+ parts.push(`${fmt} ${sr} kHz`);
+ $("#x-summary").textContent = t("sum.prefix") + parts.join(" · ");
+ $("#x-submit").disabled = !this.file;
+ },
+ async submitExport() {
+ const f = $("#export-form");
+ clearErrors(f, $("#x-error"));
+ const num = (k) => Number(this.xField(k).value);
+ const args = { input_audio: this.file, trim_silence: this.xField("trim_silence").checked, mono: this.xField("mono").checked,
+ normalize: this.xField("normalize").value, peak_ceiling_db: num("peak_ceiling_db"), loop: this.xField("loop").checked,
+ fade_in_ms: num("fade_in_ms"), fade_out_ms: num("fade_out_ms"), format: this.xField("format").value,
+ sample_rate: num("sample_rate") };
+ if (args.normalize === "loudness") args.target_lufs = num("target_lufs");
+ if (args.loop) args.loop_crossfade_ms = num("loop_crossfade_ms");
+ if (this.xField("trim_selection").checked && this.sel) {
+ args.start_seconds = +this.sel.a.toFixed(3);
+ args.end_seconds = +this.sel.b.toFixed(3);
+ }
+ const title = this.xField("title").value.trim();
+ if (title) args.title = title;
+ $("#x-submit").disabled = true;
+ await queueJob("process_audio", args, {
+ onError: (e) => showFormError(e.message, e.body && e.body.fields, f, $("#x-error"), $("#x-custom")) });
+ this.updateExportForm();
+ },
+
+ // ── results of this file ───────────────────────────────────────────────
+ renderJobs(list) {
+ const mine = this.file ? list.filter((j) => baseName((j.arguments || {}).input_audio || "") === this.file) : [];
+ renderJobList($("#edit-jobs"), mine);
+ $("#edit-jobs-empty").hidden = mine.length > 0;
+ },
+ jobFinished(job) {
+ if (job.status !== "done") return;
+ if (job.tool === "process_audio" && job.result && job.result.path) {
+ const file = baseName(job.result.path);
+ toast(t("toast.exported", { file }), { label: t("act.download"), run: () => {
+ const a = el("a", { href: audioUrl(file, true), download: file });
+ document.body.append(a); a.click(); a.remove();
+ } });
+ }
+ },
+};
diff --git a/src/audio_studio_mcp/static/i18n.js b/src/audio_studio_mcp/static/i18n.js
index 3357e04..189aa2e 100644
--- a/src/audio_studio_mcp/static/i18n.js
+++ b/src/audio_studio_mcp/static/i18n.js
@@ -1,144 +1,363 @@
// UI strings: English, Japanese, Simplified Chinese. {name} = placeholder.
window.I18N = {
en: {
- "nav.generate": "Generate", "nav.library": "Library",
+ "nav.generate": "Generate", "nav.edit": "Edit", "nav.library": "Library",
"status.unload": "Free memory", "status.unloadHint": "Unload the model now (it reloads on the next generation)",
- "status.loaded": "Model loaded", "status.notLoaded": "Model not loaded", "status.working": "Generating",
+ "status.loaded": "Model ready", "status.notLoaded": "Model loads on first use", "status.working": "Working",
"status.offline": "Server unreachable", "status.unloaded": "Model unloaded, memory freed",
"status.nothingToUnload": "The model was not loaded",
"settings.language": "Language", "settings.auto": "Auto", "settings.theme": "Theme",
"settings.system": "System", "settings.light": "Light", "settings.dark": "Dark",
- "gen.title": "New sound", "gen.type": "Type",
- "type.music": "Music", "type.instrument": "Instrument", "type.sfx": "Sound effect", "type.raw": "Raw",
- "gen.prompt.music": "Description (English)", "gen.prompt.instrument": "Description (English)",
- "gen.prompt.sfx": "Overall description (optional, English)",
+
+ "gen.title": "New sound", "gen.type": "What do you want to make?", "gen.typeShort": "Type",
+ "type.music": "Music", "type.instrument": "Instrument loop", "type.sfx": "Sound effect", "type.raw": "Raw",
+ "type.musicHint": "Background music: a full track with several instruments.",
+ "type.instrumentHint": "One instrument or a short loop, e.g. a drum beat or a guitar phrase.",
+ "type.sfxHint": "Footsteps, impacts, UI sounds, ambience…",
+ "gen.prompt.music": "Describe the music (English)", "gen.prompt.instrument": "Describe the instrument (English)",
+ "gen.prompt.sfx": "Describe the sound (English)",
"gen.promptHint.music": "Genre, main instruments, rhythm and mood in one or two sentences. Vocals and lyrics are not supported.",
- "gen.promptHint.instrument": "Instrument, playing technique, timbre and style. Loops work best at 6–20 s.",
- "gen.promptHint.sfx": "Describe the sound with the four fields below; they are joined in this order.",
+ "gen.promptHint.instrument": "Instrument, playing style, sound and mood. Loops work best at 6–20 s.",
+ "gen.promptHint.sfx": "One sentence is enough. The detail fields below help for precise effects.",
"gen.promptPh.music": "Lo-fi hip-hop track with mellow electric piano, soft vinyl crackle and relaxed drums",
"gen.promptPh.instrument": "Fingerpicked nylon guitar loop, warm and intimate, close-mic recording",
- "gen.promptPh.sfx": "A glass bottle breaking",
- "sfx.source": "Source", "sfx.action": "Action", "sfx.material": "Material", "sfx.space": "Space",
+ "gen.promptPh.sfx": "A glass bottle shattering on a concrete floor",
+ "gen.examples": "Example prompts", "gen.tryExample": "Try:",
+ "ex.lofi": "Lo-fi chill", "ex.chiptune": "8-bit adventure", "ex.epic": "Epic battle", "ex.ambient": "Calm ambient",
+ "ex.guitar": "Acoustic guitar", "ex.drums": "Funk drums", "ex.pad": "Synth pad",
+ "ex.glass": "Glass breaking", "ex.footsteps": "Footsteps on gravel", "ex.rain": "Rain and thunder",
+ "ex.ui": "UI confirm chime", "ex.door": "Creaky door",
+ "sfx.detail": "Describe in detail (optional)",
+ "sfx.source": "What makes the sound", "sfx.action": "What happens", "sfx.material": "Material / texture", "sfx.space": "Place / distance",
"sfx.sourcePh": "glass bottle", "sfx.actionPh": "shattering on impact, fragments scattering",
"sfx.materialPh": "thick glass, sharp bright transient", "sfx.spacePh": "concrete floor, close-up, dry",
- "gen.duration": "Duration (s)", "gen.bpm": "BPM", "gen.optional": "Optional", "gen.variations": "Candidates",
+ "gen.duration": "Length (seconds)", "gen.durationPresets": "Length presets",
+ "gen.durationHint": "Empty = {def} s. Up to {max} s.",
+ "gen.bpm": "Tempo (BPM)", "gen.auto": "Auto", "gen.variations": "Versions",
"gen.name": "File name", "gen.namePh": "Automatic if empty",
- "gen.advanced": "Advanced", "adv.seed": "Seed", "adv.seedPh": "Random", "adv.cfg": "CFG", "adv.steps": "Steps",
+ "gen.advanced": "Advanced", "gen.modified": "Changed from the defaults", "gen.resetAdvanced": "Reset to defaults",
+ "adv.seed": "Seed", "adv.seedPh": "Random", "adv.cfg": "Prompt strength (CFG)", "adv.steps": "Steps",
"adv.ceiling": "Peak ceiling (dBFS)", "adv.negative": "Negative prompt", "adv.negativePh": "Qualities to avoid",
- "adv.hint": "The negative prompt only applies when CFG is not 1. CFG 3–7 follows the prompt more closely but takes about twice as long.",
- "gen.submit": "Generate", "gen.reset": "Reset",
- "jobs.title": "Results", "jobs.empty": "Generated sounds appear here.",
- "jobs.queued": "Waiting · #{n} in queue", "jobs.running": "Generating… {t}", "jobs.done": "Done in {t}",
- "jobs.error": "Failed", "jobs.lost": "The server restarted before this finished. Please generate again.", "jobs.queueInfo": "{running} generating · {queued} waiting",
- "cand.label": "Candidate {n}", "cand.seed": "seed {seed}",
- "act.download": "Download", "act.copyPath": "Copy path", "act.useSeed": "Use this seed",
+ "adv.hint": "The negative prompt only works when CFG is not 1. CFG 3–7 follows the prompt more closely but takes about twice as long.",
+ "gen.submit": "Generate", "gen.submitN": "Generate {n} versions", "gen.reset": "Clear",
+ "gen.shortcut": "⌘/Ctrl + Enter",
+
+ "jobs.title": "Results", "jobs.empty": "Your sounds appear here.",
+ "jobs.emptyHint": "Pick a starter below or write your own description. The first generation also loads the model, which takes a little longer.",
+ "jobs.queued": "Waiting · #{n} in line", "jobs.loading": "Loading the model (first time only)… {t}",
+ "jobs.running": "Working… {t}", "jobs.runningEst": "Working… {t} / about {e}", "jobs.done": "Done in {t}",
+ "jobs.cancelled": "Cancelled", "jobs.error": "Failed",
+ "jobs.lost": "The server restarted before this finished. Please try again.",
+ "jobs.queueInfo": "{running} working · {queued} waiting", "jobs.exportOf": "Export of {file}",
+ "cand.label": "Version {n}", "cand.single": "Result", "cand.seed": "seed {seed}",
+ "cand.abHint": "Compare: press 1–4 to switch versions at the same moment",
+ "act.edit": "Edit", "act.download": "Download", "act.copyPath": "Copy path", "act.useSeed": "Use this seed",
"act.regen": "Regenerate (same seed)", "act.details": "Details", "act.hideDetails": "Hide details",
+ "act.more": "More actions", "act.cancel": "Cancel", "act.moreLike": "More like this",
"toast.copied": "Path copied", "toast.copyFailed": "Could not copy; select the path in Details", "toast.seedSet": "Seed {seed} set",
- "toast.regenQueued": "Queued with the same settings",
+ "toast.regenQueued": "Queued with the same settings", "toast.moreQueued": "Queued with new seeds",
+ "toast.editQueued": "Queued. Results appear below.", "toast.exported": "Saved {file}",
+
"lib.search": "Search", "lib.searchPh": "Search by name, prompt, seed…", "lib.refresh": "Refresh",
- "lib.count": "{n} files", "lib.empty": "No audio files yet. Generated sounds are saved here.",
- "lib.noMatch": "No files match.", "lib.more": "Show more", "lib.folder": "Folder: {dir}",
+ "lib.count": "{n} files", "lib.empty": "No sounds yet.", "lib.generateFirst": "Generate your first sound",
+ "lib.noMatch": "Nothing matches “{q}”.", "lib.clearSearch": "Clear search", "lib.more": "Show more", "lib.folder": "Folder: {dir}",
"meta.kind": "Kind", "meta.type": "Type", "meta.prompt": "Prompt", "meta.promptUsed": "Prompt sent to the model",
"meta.idea": "Original idea", "meta.sound": "Sound fields", "meta.bpm": "BPM", "meta.seconds": "Length",
"meta.seed": "Seed", "meta.cfg": "CFG", "meta.steps": "Steps", "meta.negative": "Negative prompt",
+ "meta.strength": "Strength", "meta.region": "Region", "meta.stepsDone": "Processing", "meta.format": "Format",
+ "meta.loudness": "Loudness",
"meta.peak": "Peak", "meta.model": "Model", "meta.created": "Created", "meta.path": "Path", "meta.input": "Input",
"meta.noSidecar": "No parameter record (.json) for this file.",
- "kind.generate": "Generated", "kind.edit": "Edit", "kind.process": "Processed",
+ "kind.generate": "Generated", "kind.edit": "Edit", "kind.process": "Export",
"err.network": "Cannot reach the server. Is audio-studio-mcp --web still running?",
- "err.emptyPrompt": "Enter a description or fill in at least one sound field.",
+ "err.emptyPrompt": "Describe the sound first (or click an example).",
+
+ "player.play": "Play", "player.pause": "Pause", "player.position": "Playback position",
+
+ "edit.emptyTitle": "Open a sound to edit it",
+ "edit.emptyHint": "Click “Edit” on a result or in the library. You can make variations, replace a part, extend it, or export it for a game or video.",
+ "edit.browse": "Browse the library", "edit.recent": "Recent sounds", "edit.notFound": "{file} is not in the output folder.",
+ "edit.mono": "mono", "edit.stereo": "stereo", "edit.madeFrom": "Made from",
+ "edit.aiTab": "Change with AI", "edit.exportTab": "Export", "edit.mode": "What to do",
+ "mode.variation": "Make a variation", "mode.variationDesc": "Same idea, new take on the whole sound",
+ "mode.inpaint": "Replace a section", "mode.inpaintDesc": "Regenerate only the selected part",
+ "mode.continue": "Extend", "mode.continueDesc": "Make it longer, in the same style",
+ "edit.strength": "How different?", "edit.subtle": "Close to the original", "edit.loose": "Very different",
+ "edit.totalLength": "Total length after extending (seconds)",
+ "edit.extendHint": "Now {now}. Up to {max} s.",
+ "edit.prompt": "Description (English)",
+ "edit.promptHint.variation": "Describe the result. Keep the original text for the same style, or change it (e.g. another instrument).",
+ "edit.promptHint.inpaint": "What should the selected part sound like? The audio around it matters more than the text.",
+ "edit.promptHint.continue": "Optional. Leave as is to continue in the same style.",
+ "edit.inpaintSel": "{range} is regenerated; everything else stays. Tip: select a bit more than you need.",
+ "edit.inpaintNoSel": "Drag across the waveform to select the part to replace.",
+ "edit.submitVariation": "Make a variation", "edit.submitVariationN": "Make {n} variations",
+ "edit.submitInpaint": "Replace {range}", "edit.submitContinue": "Extend to {len}",
+ "edit.results": "Results from this sound", "edit.noResults": "Edits and exports of this sound appear here.",
+
+ "wave.loop": "Loop", "wave.zoom": "Zoom", "wave.zoomOut": "Zoom out", "wave.zoomIn": "Zoom in", "wave.fit": "Fit",
+ "wave.zoomSel": "Zoom to selection", "wave.playhead": "Playhead", "wave.selStart": "Selection start",
+ "wave.selEnd": "Selection end", "wave.loading": "Loading waveform…", "wave.overview": "Overview: click or drag to move the view",
+ "wave.selection": "Selection", "wave.start": "Start", "wave.end": "End", "wave.selectAll": "Select all", "wave.clear": "Clear",
+ "wave.length": "{len} s", "wave.noSelection": "None: the whole sound is used",
+ "wave.playSel": "Play selection",
+ "wave.help": "Drag to select · Click to move · Space play · L loop · Ctrl/⌘+wheel zoom · Esc clear",
+
+ "exp.purpose": "What is it for?", "exp.customize": "Customize",
+ "exp.trimSilence": "Remove silence at the start and end", "exp.mono": "Mono (one channel)", "exp.loop": "Seamless loop",
+ "exp.volume": "Volume", "exp.volNone": "Keep as is", "exp.volPeak": "Peak (loudest point)", "exp.volLoud": "Loudness (LUFS)",
+ "exp.lufs": "Target (LUFS)", "exp.peak": "Peak limit (dBFS)", "exp.xfade": "Loop crossfade (ms)",
+ "exp.fadeIn": "Fade in (ms)", "exp.fadeOut": "Fade out (ms)", "exp.format": "Format", "exp.rate": "Sample rate",
+ "exp.namePh": "Automatic if empty", "exp.submit": "Export",
+ "exp.trimSel": "Only the selection ({range})", "exp.trimSelNone": "Only the selection (drag on the waveform to select)",
+ "preset.game_sfx": "Game sound effect", "preset.game_loop": "Game music loop", "preset.video_bgm": "Video / YouTube",
+ "preset.original": "Original quality", "preset.custom": "Custom",
+ "preset.game_sfxDesc": "Silence trimmed, mono, peak at −1 dB, OGG 48 kHz — ready for Unity, Godot or Unreal.",
+ "preset.game_loopDesc": "Seamless loop, −16 LUFS, OGG 48 kHz. Set the loop flag in your engine.",
+ "preset.video_bgmDesc": "−14 LUFS (YouTube level), short fade in and out, WAV 48 kHz for video editors.",
+ "preset.originalDesc": "Unchanged 44.1 kHz WAV; only peaks above −1 dB are turned down.",
+ "preset.customDesc": "Your own settings below.",
+ "sum.prefix": "Will export: ", "sum.trim": "selection {range}", "sum.silence": "trim silence", "sum.mono": "mono",
+ "sum.peak": "peak {db} dB", "sum.lufs": "{lufs} LUFS", "sum.loop": "loop ({ms} ms crossfade)", "sum.fade": "fade {a}/{b} ms",
},
ja: {
- "nav.generate": "生成", "nav.library": "ライブラリ",
+ "nav.generate": "生成", "nav.edit": "編集", "nav.library": "ライブラリ",
"status.unload": "メモリを解放", "status.unloadHint": "モデルを今すぐアンロードします(次の生成で再読み込み)",
- "status.loaded": "モデル読み込み済み", "status.notLoaded": "モデル未読み込み", "status.working": "生成中",
+ "status.loaded": "モデル準備完了", "status.notLoaded": "初回の生成時にモデルを読み込みます", "status.working": "処理中",
"status.offline": "サーバーに接続できません", "status.unloaded": "モデルをアンロードしてメモリを解放しました",
"status.nothingToUnload": "モデルは読み込まれていません",
"settings.language": "言語", "settings.auto": "自動", "settings.theme": "テーマ",
"settings.system": "システム", "settings.light": "ライト", "settings.dark": "ダーク",
- "gen.title": "新規作成", "gen.type": "種類",
- "type.music": "音楽", "type.instrument": "楽器", "type.sfx": "効果音", "type.raw": "Raw",
- "gen.prompt.music": "説明(英語)", "gen.prompt.instrument": "説明(英語)",
- "gen.prompt.sfx": "全体の説明(任意・英語)",
+
+ "gen.title": "新しい音", "gen.type": "何を作りますか?", "gen.typeShort": "種類",
+ "type.music": "音楽", "type.instrument": "楽器・ループ", "type.sfx": "効果音", "type.raw": "Raw",
+ "type.musicHint": "BGM:複数の楽器による 1 曲。",
+ "type.instrumentHint": "単一の楽器や短いループ(ドラムビート、ギターのフレーズなど)。",
+ "type.sfxHint": "足音、衝撃音、UI 音、環境音など。",
+ "gen.prompt.music": "音楽の説明(英語)", "gen.prompt.instrument": "楽器の説明(英語)",
+ "gen.prompt.sfx": "音の説明(英語)",
"gen.promptHint.music": "ジャンル・主な楽器・リズム・雰囲気を 1〜2 文で。ボーカルや歌詞は生成できません。",
- "gen.promptHint.instrument": "楽器・奏法・音色・スタイルを書きます。ループは 6〜20 秒が最適です。",
- "gen.promptHint.sfx": "下の 4 項目で音を説明します。この順につなげてモデルに渡します。",
+ "gen.promptHint.instrument": "楽器・奏法・音色・雰囲気を書きます。ループは 6〜20 秒が最適です。",
+ "gen.promptHint.sfx": "1 文で十分です。細かく指定したいときは下の項目を使います。",
"gen.promptPh.music": "Lo-fi hip-hop track with mellow electric piano, soft vinyl crackle and relaxed drums",
"gen.promptPh.instrument": "Fingerpicked nylon guitar loop, warm and intimate, close-mic recording",
- "gen.promptPh.sfx": "A glass bottle breaking",
- "sfx.source": "音源", "sfx.action": "動作", "sfx.material": "素材・質感", "sfx.space": "空間",
+ "gen.promptPh.sfx": "A glass bottle shattering on a concrete floor",
+ "gen.examples": "プロンプトの例", "gen.tryExample": "例:",
+ "ex.lofi": "Lo-fi チル", "ex.chiptune": "8bit 冒険", "ex.epic": "壮大なバトル", "ex.ambient": "穏やかなアンビエント",
+ "ex.guitar": "アコギ", "ex.drums": "ファンクドラム", "ex.pad": "シンセパッド",
+ "ex.glass": "ガラスが割れる", "ex.footsteps": "砂利の足音", "ex.rain": "雨と雷",
+ "ex.ui": "UI 決定音", "ex.door": "きしむドア",
+ "sfx.detail": "詳しく指定する(任意)",
+ "sfx.source": "何が鳴るか", "sfx.action": "どう鳴るか", "sfx.material": "素材・質感", "sfx.space": "場所・距離",
"sfx.sourcePh": "glass bottle", "sfx.actionPh": "shattering on impact, fragments scattering",
"sfx.materialPh": "thick glass, sharp bright transient", "sfx.spacePh": "concrete floor, close-up, dry",
- "gen.duration": "長さ(秒)", "gen.bpm": "BPM", "gen.optional": "任意", "gen.variations": "候補数",
+ "gen.duration": "長さ(秒)", "gen.durationPresets": "長さのプリセット",
+ "gen.durationHint": "空欄なら {def} 秒。最大 {max} 秒。",
+ "gen.bpm": "テンポ(BPM)", "gen.auto": "自動", "gen.variations": "バージョン数",
"gen.name": "ファイル名", "gen.namePh": "空欄なら自動",
- "gen.advanced": "詳細設定", "adv.seed": "シード", "adv.seedPh": "ランダム", "adv.cfg": "CFG", "adv.steps": "ステップ数",
+ "gen.advanced": "詳細設定", "gen.modified": "既定値から変更されています", "gen.resetAdvanced": "既定値に戻す",
+ "adv.seed": "シード", "adv.seedPh": "ランダム", "adv.cfg": "プロンプトの強さ(CFG)", "adv.steps": "ステップ数",
"adv.ceiling": "ピーク上限(dBFS)", "adv.negative": "ネガティブプロンプト", "adv.negativePh": "避けたい要素",
"adv.hint": "ネガティブプロンプトは CFG が 1 以外のときだけ効きます。CFG 3〜7 はプロンプトに忠実になりますが、時間は約 2 倍かかります。",
- "gen.submit": "生成", "gen.reset": "リセット",
- "jobs.title": "結果", "jobs.empty": "生成した音はここに表示されます。",
- "jobs.queued": "待機中・{n} 番目", "jobs.running": "生成中… {t}", "jobs.done": "完了({t})",
- "jobs.error": "失敗", "jobs.lost": "完了前にサーバーが再起動しました。もう一度生成してください。", "jobs.queueInfo": "生成中 {running} 件・待機 {queued} 件",
- "cand.label": "候補 {n}", "cand.seed": "シード {seed}",
- "act.download": "ダウンロード", "act.copyPath": "パスをコピー", "act.useSeed": "このシードを使う",
+ "gen.submit": "生成", "gen.submitN": "{n} バージョン生成", "gen.reset": "クリア",
+ "gen.shortcut": "⌘/Ctrl + Enter",
+
+ "jobs.title": "結果", "jobs.empty": "作った音はここに表示されます。",
+ "jobs.emptyHint": "下の例を選ぶか、説明を書いてみてください。初回はモデルの読み込みがあるため少し時間がかかります。",
+ "jobs.queued": "待機中・{n} 番目", "jobs.loading": "モデルを読み込み中(初回のみ)… {t}",
+ "jobs.running": "処理中… {t}", "jobs.runningEst": "処理中… {t} / 約 {e}", "jobs.done": "完了({t})",
+ "jobs.cancelled": "キャンセルしました", "jobs.error": "失敗",
+ "jobs.lost": "完了前にサーバーが再起動しました。もう一度実行してください。",
+ "jobs.queueInfo": "処理中 {running} 件・待機 {queued} 件", "jobs.exportOf": "{file} の書き出し",
+ "cand.label": "バージョン {n}", "cand.single": "結果", "cand.seed": "シード {seed}",
+ "cand.abHint": "聴き比べ:1〜4 キーで同じ位置のまま切り替え",
+ "act.edit": "編集", "act.download": "ダウンロード", "act.copyPath": "パスをコピー", "act.useSeed": "このシードを使う",
"act.regen": "同じシードで再生成", "act.details": "詳細", "act.hideDetails": "詳細を閉じる",
+ "act.more": "その他の操作", "act.cancel": "キャンセル", "act.moreLike": "似た音をもっと作る",
"toast.copied": "パスをコピーしました", "toast.copyFailed": "コピーできませんでした。詳細からパスを選択してください", "toast.seedSet": "シード {seed} を設定しました",
- "toast.regenQueued": "同じ設定でキューに追加しました",
+ "toast.regenQueued": "同じ設定でキューに追加しました", "toast.moreQueued": "新しいシードでキューに追加しました",
+ "toast.editQueued": "キューに追加しました。結果は下に表示されます。", "toast.exported": "{file} を保存しました",
+
"lib.search": "検索", "lib.searchPh": "名前・プロンプト・シードで検索…", "lib.refresh": "更新",
- "lib.count": "{n} 件", "lib.empty": "まだ音声ファイルがありません。生成した音はここに保存されます。",
- "lib.noMatch": "一致するファイルはありません。", "lib.more": "さらに表示", "lib.folder": "フォルダ: {dir}",
+ "lib.count": "{n} 件", "lib.empty": "まだ音がありません。", "lib.generateFirst": "最初の音を作る",
+ "lib.noMatch": "「{q}」に一致するものはありません。", "lib.clearSearch": "検索をクリア", "lib.more": "さらに表示", "lib.folder": "フォルダ: {dir}",
"meta.kind": "種別", "meta.type": "種類", "meta.prompt": "プロンプト", "meta.promptUsed": "モデルに渡したプロンプト",
"meta.idea": "元のアイデア", "meta.sound": "効果音の項目", "meta.bpm": "BPM", "meta.seconds": "長さ",
"meta.seed": "シード", "meta.cfg": "CFG", "meta.steps": "ステップ数", "meta.negative": "ネガティブプロンプト",
+ "meta.strength": "変化の強さ", "meta.region": "範囲", "meta.stepsDone": "処理内容", "meta.format": "形式",
+ "meta.loudness": "ラウドネス",
"meta.peak": "ピーク", "meta.model": "モデル", "meta.created": "作成日時", "meta.path": "パス", "meta.input": "入力",
"meta.noSidecar": "このファイルにはパラメータ記録(.json)がありません。",
- "kind.generate": "生成", "kind.edit": "編集", "kind.process": "加工",
+ "kind.generate": "生成", "kind.edit": "編集", "kind.process": "書き出し",
"err.network": "サーバーに接続できません。audio-studio-mcp --web が起動しているか確認してください。",
- "err.emptyPrompt": "説明を入力するか、効果音の項目を 1 つ以上入力してください。",
+ "err.emptyPrompt": "まず音の説明を入力してください(例をクリックしても OK)。",
+
+ "player.play": "再生", "player.pause": "一時停止", "player.position": "再生位置",
+
+ "edit.emptyTitle": "編集する音を開いてください",
+ "edit.emptyHint": "結果やライブラリの「編集」をクリックします。バリエーション作成、一部の差し替え、延長、ゲームや動画向けの書き出しができます。",
+ "edit.browse": "ライブラリを見る", "edit.recent": "最近の音", "edit.notFound": "{file} は出力フォルダにありません。",
+ "edit.mono": "モノラル", "edit.stereo": "ステレオ", "edit.madeFrom": "元の音:",
+ "edit.aiTab": "AI で変える", "edit.exportTab": "書き出し", "edit.mode": "操作",
+ "mode.variation": "バリエーション", "mode.variationDesc": "同じアイデアで全体を作り直す",
+ "mode.inpaint": "一部を差し替え", "mode.inpaintDesc": "選択した部分だけ作り直す",
+ "mode.continue": "延長", "mode.continueDesc": "同じ雰囲気で長くする",
+ "edit.strength": "どれくらい変える?", "edit.subtle": "元に近い", "edit.loose": "大きく変える",
+ "edit.totalLength": "延長後の長さ(秒)",
+ "edit.extendHint": "現在 {now}。最大 {max} 秒。",
+ "edit.prompt": "説明(英語)",
+ "edit.promptHint.variation": "結果を説明します。同じ雰囲気ならそのまま、変えたいなら書き換えます(例:別の楽器)。",
+ "edit.promptHint.inpaint": "選択部分をどんな音にするか。説明文より前後の音の影響が大きくなります。",
+ "edit.promptHint.continue": "任意。そのままなら同じ雰囲気で続けます。",
+ "edit.inpaintSel": "{range} を作り直し、それ以外はそのまま残します。コツ:少し広めに選ぶと自然につながります。",
+ "edit.inpaintNoSel": "波形をドラッグして、差し替える部分を選択してください。",
+ "edit.submitVariation": "バリエーションを作る", "edit.submitVariationN": "バリエーションを {n} 個作る",
+ "edit.submitInpaint": "{range} を差し替え", "edit.submitContinue": "{len} まで延長",
+ "edit.results": "この音から作った結果", "edit.noResults": "この音の編集・書き出しの結果はここに表示されます。",
+
+ "wave.loop": "ループ", "wave.zoom": "ズーム", "wave.zoomOut": "縮小", "wave.zoomIn": "拡大", "wave.fit": "全体",
+ "wave.zoomSel": "選択範囲を拡大", "wave.playhead": "再生位置", "wave.selStart": "選択の開始",
+ "wave.selEnd": "選択の終了", "wave.loading": "波形を読み込み中…", "wave.overview": "全体図:クリックまたはドラッグで表示位置を移動",
+ "wave.selection": "選択範囲", "wave.start": "開始", "wave.end": "終了", "wave.selectAll": "すべて選択", "wave.clear": "解除",
+ "wave.length": "{len} 秒", "wave.noSelection": "なし:音全体が対象になります",
+ "wave.playSel": "選択範囲を再生",
+ "wave.help": "ドラッグで選択・クリックで移動・Space 再生・L ループ・Ctrl/⌘+ホイールでズーム・Esc で解除",
+
+ "exp.purpose": "用途は?", "exp.customize": "カスタマイズ",
+ "exp.trimSilence": "先頭と末尾の無音を削除", "exp.mono": "モノラル(1 チャンネル)", "exp.loop": "シームレスループ",
+ "exp.volume": "音量", "exp.volNone": "そのまま", "exp.volPeak": "ピーク(最大音量)", "exp.volLoud": "ラウドネス(LUFS)",
+ "exp.lufs": "目標(LUFS)", "exp.peak": "ピーク上限(dBFS)", "exp.xfade": "ループのクロスフェード(ms)",
+ "exp.fadeIn": "フェードイン(ms)", "exp.fadeOut": "フェードアウト(ms)", "exp.format": "形式", "exp.rate": "サンプルレート",
+ "exp.namePh": "空欄なら自動", "exp.submit": "書き出し",
+ "exp.trimSel": "選択範囲だけ({range})", "exp.trimSelNone": "選択範囲だけ(波形をドラッグして選択)",
+ "preset.game_sfx": "ゲームの効果音", "preset.game_loop": "ゲームのループ BGM", "preset.video_bgm": "動画・YouTube",
+ "preset.original": "元の品質", "preset.custom": "カスタム",
+ "preset.game_sfxDesc": "無音カット・モノラル・ピーク −1 dB・OGG 48 kHz。Unity / Godot / Unreal にそのまま使えます。",
+ "preset.game_loopDesc": "シームレスループ・−16 LUFS・OGG 48 kHz。エンジン側でループ再生を有効にしてください。",
+ "preset.video_bgmDesc": "−14 LUFS(YouTube の基準)・短いフェードイン/アウト・動画編集向け WAV 48 kHz。",
+ "preset.originalDesc": "44.1 kHz WAV のまま。−1 dB を超えるピークだけ下げます。",
+ "preset.customDesc": "下の設定を自分で選びます。",
+ "sum.prefix": "書き出し内容:", "sum.trim": "選択範囲 {range}", "sum.silence": "無音カット", "sum.mono": "モノラル",
+ "sum.peak": "ピーク {db} dB", "sum.lufs": "{lufs} LUFS", "sum.loop": "ループ(クロスフェード {ms} ms)", "sum.fade": "フェード {a}/{b} ms",
},
zh: {
- "nav.generate": "生成", "nav.library": "作品库",
+ "nav.generate": "生成", "nav.edit": "编辑", "nav.library": "作品库",
"status.unload": "释放内存", "status.unloadHint": "立即卸载模型(下次生成时会重新加载)",
- "status.loaded": "模型已加载", "status.notLoaded": "模型未加载", "status.working": "生成中",
+ "status.loaded": "模型已就绪", "status.notLoaded": "首次生成时加载模型", "status.working": "处理中",
"status.offline": "无法连接服务器", "status.unloaded": "已卸载模型并释放内存",
"status.nothingToUnload": "模型尚未加载",
"settings.language": "语言", "settings.auto": "自动", "settings.theme": "主题",
"settings.system": "跟随系统", "settings.light": "浅色", "settings.dark": "深色",
- "gen.title": "新建", "gen.type": "类型",
- "type.music": "音乐", "type.instrument": "单乐器", "type.sfx": "音效", "type.raw": "Raw",
- "gen.prompt.music": "描述(英文)", "gen.prompt.instrument": "描述(英文)",
- "gen.prompt.sfx": "整体描述(可选,英文)",
+
+ "gen.title": "新建声音", "gen.type": "想做什么?", "gen.typeShort": "类型",
+ "type.music": "音乐", "type.instrument": "乐器 / 循环", "type.sfx": "音效", "type.raw": "Raw",
+ "type.musicHint": "背景音乐:多种乐器组成的完整曲子。",
+ "type.instrumentHint": "单一乐器或短循环,例如鼓点、吉他乐句。",
+ "type.sfxHint": "脚步声、撞击声、UI 音、环境音等。",
+ "gen.prompt.music": "描述音乐(英文)", "gen.prompt.instrument": "描述乐器(英文)",
+ "gen.prompt.sfx": "描述声音(英文)",
"gen.promptHint.music": "用一两句话写出风格、主要乐器、节奏和氛围。不能生成人声和歌词。",
- "gen.promptHint.instrument": "写出乐器、演奏方式、音色和风格。循环素材 6–20 秒效果最好。",
- "gen.promptHint.sfx": "用下面 4 个输入框描述声音,会按这个顺序拼接后交给模型。",
+ "gen.promptHint.instrument": "写出乐器、演奏方式、音色和氛围。循环素材 6–20 秒效果最好。",
+ "gen.promptHint.sfx": "一句话就够了。需要精确控制时再填下面的细节。",
"gen.promptPh.music": "Lo-fi hip-hop track with mellow electric piano, soft vinyl crackle and relaxed drums",
"gen.promptPh.instrument": "Fingerpicked nylon guitar loop, warm and intimate, close-mic recording",
- "gen.promptPh.sfx": "A glass bottle breaking",
- "sfx.source": "发声物", "sfx.action": "动作", "sfx.material": "材质", "sfx.space": "空间",
+ "gen.promptPh.sfx": "A glass bottle shattering on a concrete floor",
+ "gen.examples": "提示词示例", "gen.tryExample": "试试:",
+ "ex.lofi": "Lo-fi 放松", "ex.chiptune": "8-bit 冒险", "ex.epic": "史诗战斗", "ex.ambient": "宁静氛围",
+ "ex.guitar": "木吉他", "ex.drums": "放克鼓", "ex.pad": "合成器铺底",
+ "ex.glass": "玻璃碎裂", "ex.footsteps": "碎石路脚步", "ex.rain": "雨声与雷声",
+ "ex.ui": "UI 确认音", "ex.door": "吱呀的木门",
+ "sfx.detail": "详细描述(可选)",
+ "sfx.source": "什么在发声", "sfx.action": "怎样发声", "sfx.material": "材质 / 质感", "sfx.space": "地点 / 距离",
"sfx.sourcePh": "glass bottle", "sfx.actionPh": "shattering on impact, fragments scattering",
"sfx.materialPh": "thick glass, sharp bright transient", "sfx.spacePh": "concrete floor, close-up, dry",
- "gen.duration": "时长(秒)", "gen.bpm": "BPM", "gen.optional": "可选", "gen.variations": "候选数",
+ "gen.duration": "时长(秒)", "gen.durationPresets": "时长预设",
+ "gen.durationHint": "留空为 {def} 秒,最长 {max} 秒。",
+ "gen.bpm": "速度(BPM)", "gen.auto": "自动", "gen.variations": "版本数",
"gen.name": "文件名", "gen.namePh": "留空则自动命名",
- "gen.advanced": "高级参数", "adv.seed": "种子", "adv.seedPh": "随机", "adv.cfg": "CFG", "adv.steps": "步数",
+ "gen.advanced": "高级参数", "gen.modified": "已修改默认值", "gen.resetAdvanced": "恢复默认",
+ "adv.seed": "种子", "adv.seedPh": "随机", "adv.cfg": "提示词强度(CFG)", "adv.steps": "步数",
"adv.ceiling": "峰值上限(dBFS)", "adv.negative": "反向提示词", "adv.negativePh": "想避免的元素",
"adv.hint": "反向提示词只在 CFG 不等于 1 时生效。CFG 3–7 更贴合提示词,但耗时约为 2 倍。",
- "gen.submit": "生成", "gen.reset": "重置",
+ "gen.submit": "生成", "gen.submitN": "生成 {n} 个版本", "gen.reset": "清空",
+ "gen.shortcut": "⌘/Ctrl + Enter",
+
"jobs.title": "结果", "jobs.empty": "生成的声音会显示在这里。",
- "jobs.queued": "排队中 · 第 {n} 位", "jobs.running": "生成中… {t}", "jobs.done": "完成({t})",
- "jobs.error": "失败", "jobs.lost": "完成前服务器已重启,请重新生成。", "jobs.queueInfo": "生成中 {running} 个 · 排队 {queued} 个",
- "cand.label": "候选 {n}", "cand.seed": "种子 {seed}",
- "act.download": "下载", "act.copyPath": "复制路径", "act.useSeed": "使用此种子",
+ "jobs.emptyHint": "选一个下面的示例,或自己写描述。第一次生成需要加载模型,会稍慢一些。",
+ "jobs.queued": "排队中 · 第 {n} 位", "jobs.loading": "正在加载模型(仅首次)… {t}",
+ "jobs.running": "处理中… {t}", "jobs.runningEst": "处理中… {t} / 约 {e}", "jobs.done": "完成({t})",
+ "jobs.cancelled": "已取消", "jobs.error": "失败",
+ "jobs.lost": "完成前服务器已重启,请重新执行。",
+ "jobs.queueInfo": "处理中 {running} 个 · 排队 {queued} 个", "jobs.exportOf": "导出 {file}",
+ "cand.label": "版本 {n}", "cand.single": "结果", "cand.seed": "种子 {seed}",
+ "cand.abHint": "对比试听:按 1–4 在同一位置切换版本",
+ "act.edit": "编辑", "act.download": "下载", "act.copyPath": "复制路径", "act.useSeed": "使用此种子",
"act.regen": "用同一种子重新生成", "act.details": "详情", "act.hideDetails": "收起详情",
+ "act.more": "更多操作", "act.cancel": "取消", "act.moreLike": "再来几个类似的",
"toast.copied": "已复制路径", "toast.copyFailed": "无法复制,请在详情中选中路径", "toast.seedSet": "已设置种子 {seed}",
- "toast.regenQueued": "已用相同设置加入队列",
+ "toast.regenQueued": "已用相同设置加入队列", "toast.moreQueued": "已用新的种子加入队列",
+ "toast.editQueued": "已加入队列,结果会显示在下方。", "toast.exported": "已保存 {file}",
+
"lib.search": "搜索", "lib.searchPh": "按名称、提示词、种子搜索…", "lib.refresh": "刷新",
- "lib.count": "{n} 个文件", "lib.empty": "还没有音频文件。生成的声音会保存在这里。",
- "lib.noMatch": "没有匹配的文件。", "lib.more": "显示更多", "lib.folder": "文件夹:{dir}",
+ "lib.count": "{n} 个文件", "lib.empty": "还没有声音。", "lib.generateFirst": "生成第一个声音",
+ "lib.noMatch": "没有与“{q}”匹配的文件。", "lib.clearSearch": "清除搜索", "lib.more": "显示更多", "lib.folder": "文件夹:{dir}",
"meta.kind": "类别", "meta.type": "类型", "meta.prompt": "提示词", "meta.promptUsed": "实际发给模型的提示词",
"meta.idea": "原始想法", "meta.sound": "音效字段", "meta.bpm": "BPM", "meta.seconds": "时长",
"meta.seed": "种子", "meta.cfg": "CFG", "meta.steps": "步数", "meta.negative": "反向提示词",
+ "meta.strength": "变化强度", "meta.region": "区间", "meta.stepsDone": "处理步骤", "meta.format": "格式",
+ "meta.loudness": "响度",
"meta.peak": "峰值", "meta.model": "模型", "meta.created": "创建时间", "meta.path": "路径", "meta.input": "输入",
"meta.noSidecar": "此文件没有参数记录(.json)。",
- "kind.generate": "生成", "kind.edit": "编辑", "kind.process": "后处理",
+ "kind.generate": "生成", "kind.edit": "编辑", "kind.process": "导出",
"err.network": "无法连接服务器。请确认 audio-studio-mcp --web 仍在运行。",
- "err.emptyPrompt": "请填写描述,或至少填写一个音效字段。",
+ "err.emptyPrompt": "请先描述声音(也可以点一个示例)。",
+
+ "player.play": "播放", "player.pause": "暂停", "player.position": "播放位置",
+
+ "edit.emptyTitle": "打开一个声音来编辑",
+ "edit.emptyHint": "在结果或作品库中点击“编辑”。可以生成变体、替换其中一段、延长,或导出给游戏和视频使用。",
+ "edit.browse": "浏览作品库", "edit.recent": "最近的声音", "edit.notFound": "输出文件夹中没有 {file}。",
+ "edit.mono": "单声道", "edit.stereo": "立体声", "edit.madeFrom": "来源:",
+ "edit.aiTab": "用 AI 修改", "edit.exportTab": "导出", "edit.mode": "操作",
+ "mode.variation": "生成变体", "mode.variationDesc": "同样的想法,整体重新演绎",
+ "mode.inpaint": "替换一段", "mode.inpaintDesc": "只重新生成选中的部分",
+ "mode.continue": "延长", "mode.continueDesc": "保持风格,让它更长",
+ "edit.strength": "改变多少?", "edit.subtle": "接近原声", "edit.loose": "大幅改变",
+ "edit.totalLength": "延长后的总时长(秒)",
+ "edit.extendHint": "当前 {now},最长 {max} 秒。",
+ "edit.prompt": "描述(英文)",
+ "edit.promptHint.variation": "描述想要的结果。保持原文则风格不变,改写则会变化(例如换一种乐器)。",
+ "edit.promptHint.inpaint": "选中的部分应该是什么声音?前后的音频比文字影响更大。",
+ "edit.promptHint.continue": "可选。保持不变则按原风格继续。",
+ "edit.inpaintSel": "重新生成 {range},其余部分保持不变。提示:选得稍宽一些衔接更自然。",
+ "edit.inpaintNoSel": "在波形上拖动,选择要替换的部分。",
+ "edit.submitVariation": "生成变体", "edit.submitVariationN": "生成 {n} 个变体",
+ "edit.submitInpaint": "替换 {range}", "edit.submitContinue": "延长到 {len}",
+ "edit.results": "由这个声音生成的结果", "edit.noResults": "这个声音的编辑和导出结果会显示在这里。",
+
+ "wave.loop": "循环", "wave.zoom": "缩放", "wave.zoomOut": "缩小", "wave.zoomIn": "放大", "wave.fit": "全部",
+ "wave.zoomSel": "放大选区", "wave.playhead": "播放位置", "wave.selStart": "选区开始",
+ "wave.selEnd": "选区结束", "wave.loading": "正在加载波形…", "wave.overview": "全局图:点击或拖动以移动视图",
+ "wave.selection": "选区", "wave.start": "开始", "wave.end": "结束", "wave.selectAll": "全选", "wave.clear": "取消选区",
+ "wave.length": "{len} 秒", "wave.noSelection": "无:使用整个声音",
+ "wave.playSel": "播放选区",
+ "wave.help": "拖动选择 · 点击定位 · 空格播放 · L 循环 · Ctrl/⌘+滚轮缩放 · Esc 取消",
+
+ "exp.purpose": "用在哪里?", "exp.customize": "自定义",
+ "exp.trimSilence": "去掉开头和结尾的静音", "exp.mono": "单声道", "exp.loop": "无缝循环",
+ "exp.volume": "音量", "exp.volNone": "保持不变", "exp.volPeak": "峰值(最响处)", "exp.volLoud": "响度(LUFS)",
+ "exp.lufs": "目标(LUFS)", "exp.peak": "峰值上限(dBFS)", "exp.xfade": "循环交叉淡化(ms)",
+ "exp.fadeIn": "淡入(ms)", "exp.fadeOut": "淡出(ms)", "exp.format": "格式", "exp.rate": "采样率",
+ "exp.namePh": "留空则自动命名", "exp.submit": "导出",
+ "exp.trimSel": "仅导出选区({range})", "exp.trimSelNone": "仅导出选区(在波形上拖动来选择)",
+ "preset.game_sfx": "游戏音效", "preset.game_loop": "游戏循环音乐", "preset.video_bgm": "视频 / YouTube",
+ "preset.original": "原始品质", "preset.custom": "自定义",
+ "preset.game_sfxDesc": "去静音、单声道、峰值 −1 dB、OGG 48 kHz,可直接用于 Unity / Godot / Unreal。",
+ "preset.game_loopDesc": "无缝循环、−16 LUFS、OGG 48 kHz。请在引擎中开启循环播放。",
+ "preset.video_bgmDesc": "−14 LUFS(YouTube 标准)、短淡入淡出、WAV 48 kHz,适合视频剪辑。",
+ "preset.originalDesc": "保持 44.1 kHz WAV,只把超过 −1 dB 的峰值压下来。",
+ "preset.customDesc": "在下面自己设置。",
+ "sum.prefix": "将导出:", "sum.trim": "选区 {range}", "sum.silence": "去静音", "sum.mono": "单声道",
+ "sum.peak": "峰值 {db} dB", "sum.lufs": "{lufs} LUFS", "sum.loop": "循环(交叉淡化 {ms} ms)", "sum.fade": "淡入淡出 {a}/{b} ms",
},
};
diff --git a/src/audio_studio_mcp/static/index.html b/src/audio_studio_mcp/static/index.html
index 8727ae6..18eab3a 100644
--- a/src/audio_studio_mcp/static/index.html
+++ b/src/audio_studio_mcp/static/index.html
@@ -21,6 +21,7 @@
</div>
<nav class="tabs" role="tablist">
<button role="tab" id="tab-generate" aria-controls="page-generate" aria-selected="true" data-page="generate" data-i18n="nav.generate">Generate</button>
+ <button role="tab" id="tab-edit" aria-controls="page-edit" aria-selected="false" data-page="edit" data-i18n="nav.edit">Edit</button>
<button role="tab" id="tab-library" aria-controls="page-library" aria-selected="false" data-page="library" data-i18n="nav.library">Library</button>
</nav>
<div class="status" id="statusbar">
@@ -51,57 +52,66 @@
<h1 class="panel-title" data-i18n="gen.title">New sound</h1>
<fieldset class="field">
- <legend data-i18n="gen.type">Type</legend>
+ <legend data-i18n="gen.type">What do you want to make?</legend>
<div class="segmented" id="type-seg">
<label><input type="radio" name="audio_type" value="music" checked><span data-i18n="type.music">Music</span></label>
<label><input type="radio" name="audio_type" value="instrument"><span data-i18n="type.instrument">Instrument</span></label>
<label><input type="radio" name="audio_type" value="sfx"><span data-i18n="type.sfx">Sound effect</span></label>
</div>
+ <p class="hint" id="type-hint"></p>
</fieldset>
<div class="field">
<label for="prompt" id="prompt-label" data-i18n="gen.prompt.music">Description (English)</label>
<textarea id="prompt" name="prompt" rows="3" spellcheck="false"></textarea>
- <p class="hint" id="prompt-hint" data-i18n="gen.promptHint.music"></p>
+ <p class="hint" id="prompt-hint"></p>
+ <div class="chips" id="examples" role="group" data-i18n-aria-label="gen.examples"></div>
</div>
- <div class="sfx-fields" id="sfx-fields" hidden>
- <div class="field"><label for="sound_source" data-i18n="sfx.source">Source</label><input id="sound_source" name="sound_source" type="text" data-i18n-placeholder="sfx.sourcePh"></div>
- <div class="field"><label for="sound_action" data-i18n="sfx.action">Action</label><input id="sound_action" name="sound_action" type="text" data-i18n-placeholder="sfx.actionPh"></div>
- <div class="field"><label for="sound_material" data-i18n="sfx.material">Material</label><input id="sound_material" name="sound_material" type="text" data-i18n-placeholder="sfx.materialPh"></div>
- <div class="field"><label for="sound_space" data-i18n="sfx.space">Space</label><input id="sound_space" name="sound_space" type="text" data-i18n-placeholder="sfx.spacePh"></div>
+ <details class="sfx-fields" id="sfx-fields" open hidden>
+ <summary data-i18n="sfx.detail">Describe in detail (optional)</summary>
+ <div class="sfx-grid">
+ <div class="field"><label for="sound_source" data-i18n="sfx.source">Source</label><input id="sound_source" name="sound_source" type="text" data-i18n-placeholder="sfx.sourcePh"></div>
+ <div class="field"><label for="sound_action" data-i18n="sfx.action">Action</label><input id="sound_action" name="sound_action" type="text" data-i18n-placeholder="sfx.actionPh"></div>
+ <div class="field"><label for="sound_material" data-i18n="sfx.material">Material</label><input id="sound_material" name="sound_material" type="text" data-i18n-placeholder="sfx.materialPh"></div>
+ <div class="field"><label for="sound_space" data-i18n="sfx.space">Space</label><input id="sound_space" name="sound_space" type="text" data-i18n-placeholder="sfx.spacePh"></div>
+ </div>
+ </details>
+
+ <div class="field">
+ <label for="duration_seconds" data-i18n="gen.duration">Length (seconds)</label>
+ <div class="inline">
+ <input id="duration_seconds" name="duration_seconds" class="num" type="number" min="0.5" max="380" step="0.5" inputmode="decimal">
+ <div class="chips" id="durations" role="group" data-i18n-aria-label="gen.durationPresets"></div>
+ </div>
+ <p class="hint" id="duration-hint"></p>
</div>
<div class="row">
- <div class="field">
- <label for="duration_seconds" data-i18n="gen.duration">Duration (s)</label>
- <input id="duration_seconds" name="duration_seconds" type="number" min="0.5" max="380" step="0.5" inputmode="decimal">
- </div>
- <div class="field" id="bpm-field">
- <label for="bpm" data-i18n="gen.bpm">BPM</label>
- <input id="bpm" name="bpm" type="number" min="30" max="300" step="1" inputmode="numeric" data-i18n-placeholder="gen.optional">
- </div>
<fieldset class="field">
- <legend data-i18n="gen.variations">Candidates</legend>
+ <legend data-i18n="gen.variations">Versions</legend>
<div class="segmented compact">
- <label><input type="radio" name="variations" value="1" checked><span>1</span></label>
- <label><input type="radio" name="variations" value="2"><span>2</span></label>
+ <label><input type="radio" name="variations" value="1"><span>1</span></label>
+ <label><input type="radio" name="variations" value="2" checked><span>2</span></label>
<label><input type="radio" name="variations" value="3"><span>3</span></label>
<label><input type="radio" name="variations" value="4"><span>4</span></label>
</div>
</fieldset>
- </div>
-
- <div class="field">
- <label for="title" data-i18n="gen.name">File name</label>
- <input id="title" name="title" type="text" data-i18n-placeholder="gen.namePh">
+ <div class="field" id="bpm-field">
+ <label for="bpm" data-i18n="gen.bpm">Tempo (BPM)</label>
+ <input id="bpm" name="bpm" type="number" min="30" max="300" step="1" inputmode="numeric" data-i18n-placeholder="gen.auto">
+ </div>
</div>
<details class="advanced" id="advanced">
- <summary data-i18n="gen.advanced">Advanced</summary>
+ <summary><span data-i18n="gen.advanced">Advanced</span><span class="mod-dot" id="adv-dot" hidden data-i18n-title="gen.modified"></span></summary>
+ <div class="field">
+ <label for="title" data-i18n="gen.name">File name</label>
+ <input id="title" name="title" type="text" data-i18n-placeholder="gen.namePh">
+ </div>
<div class="row">
<div class="field"><label for="seed" data-i18n="adv.seed">Seed</label><input id="seed" name="seed" type="number" min="-1" step="1" inputmode="numeric" data-i18n-placeholder="adv.seedPh"></div>
- <div class="field"><label for="cfg" data-i18n="adv.cfg">CFG</label><input id="cfg" name="cfg" type="number" min="0" max="15" step="0.5" placeholder="1.0"></div>
+ <div class="field"><label for="cfg" data-i18n="adv.cfg">Prompt strength (CFG)</label><input id="cfg" name="cfg" type="number" min="0" max="15" step="0.5" placeholder="1.0"></div>
<div class="field"><label for="steps" data-i18n="adv.steps">Steps</label><input id="steps" name="steps" type="number" min="1" max="50" step="1" placeholder="8"></div>
<div class="field"><label for="peak_ceiling_db" data-i18n="adv.ceiling">Peak ceiling (dBFS)</label><input id="peak_ceiling_db" name="peak_ceiling_db" type="number" min="-24" max="0" step="0.5" placeholder="-1.0"></div>
</div>
@@ -110,12 +120,14 @@
<input id="negative_prompt" name="negative_prompt" type="text" data-i18n-placeholder="adv.negativePh">
<p class="hint" data-i18n="adv.hint"></p>
</div>
+ <button type="button" class="link-btn" id="adv-reset" data-i18n="gen.resetAdvanced">Reset to defaults</button>
</details>
<p class="form-error" id="form-error" role="alert" hidden></p>
<div class="actions">
- <button type="submit" class="btn btn-primary" id="gen-submit" data-i18n="gen.submit">Generate</button>
- <button type="button" class="btn btn-quiet" id="gen-reset" data-i18n="gen.reset">Reset</button>
+ <button type="submit" class="btn btn-primary btn-lg" id="gen-submit">Generate</button>
+ <button type="button" class="btn btn-quiet" id="gen-reset" data-i18n="gen.reset">Clear</button>
+ <span class="kbd-hint muted small" data-i18n="gen.shortcut"></span>
</div>
</form>
@@ -125,7 +137,220 @@
<span class="muted small" id="queue-info"></span>
</div>
<div id="jobs" class="jobs"></div>
- <p class="empty" id="jobs-empty" data-i18n="jobs.empty">Generated sounds appear here.</p>
+ <div class="empty-state" id="jobs-empty">
+ <p class="empty-title" data-i18n="jobs.empty">Your sounds appear here.</p>
+ <p class="muted small" data-i18n="jobs.emptyHint"></p>
+ <div class="starter" id="starters"></div>
+ </div>
+ </div>
+ </section>
+
+ <!-- Edit -->
+ <section id="page-edit" class="page" role="tabpanel" aria-labelledby="tab-edit" hidden>
+ <div class="empty-state" id="edit-empty">
+ <p class="empty-title" data-i18n="edit.emptyTitle">Open a sound to edit it</p>
+ <p class="muted small" data-i18n="edit.emptyHint"></p>
+ <div class="recent" id="edit-recent"></div>
+ <button type="button" class="btn" id="edit-to-library" data-i18n="edit.browse">Browse the library</button>
+ </div>
+
+ <div id="edit-main" hidden>
+ <div class="edit-head">
+ <div class="edit-title">
+ <h1 id="edit-name"></h1>
+ <span class="muted small" id="edit-info"></span>
+ </div>
+ <div class="edit-source small" id="edit-source"></div>
+ </div>
+
+ <div class="panel wave-panel">
+ <div class="wave-toolbar">
+ <button type="button" class="btn btn-primary play-main" id="w-play"><span class="icon-play" aria-hidden="true"></span><span id="w-play-text"></span></button>
+ <span class="clock" id="w-clock" aria-live="off">0:00.0 / 0:00.0</span>
+ <label class="toggle"><input type="checkbox" id="w-loop"><span data-i18n="wave.loop">Loop</span></label>
+ <span class="spacer"></span>
+ <div class="zoom" role="group" data-i18n-aria-label="wave.zoom">
+ <button type="button" class="btn btn-sm" id="w-zoom-out" data-i18n-aria-label="wave.zoomOut" data-i18n-title="wave.zoomOut">−</button>
+ <button type="button" class="btn btn-sm" id="w-zoom-in" data-i18n-aria-label="wave.zoomIn" data-i18n-title="wave.zoomIn">+</button>
+ <button type="button" class="btn btn-sm" id="w-zoom-fit" data-i18n="wave.fit">Fit</button>
+ <button type="button" class="btn btn-sm" id="w-zoom-sel" data-i18n="wave.zoomSel">Zoom to selection</button>
+ </div>
+ </div>
+ <canvas class="ruler" id="w-ruler" aria-hidden="true"></canvas>
+ <div class="wave" id="w-wave" tabindex="0" role="slider" data-i18n-aria-label="wave.playhead" aria-valuemin="0">
+ <canvas id="w-canvas" aria-hidden="true"></canvas>
+ <div class="sel" id="w-sel" hidden>
+ <div class="handle start" id="w-h-start" role="slider" tabindex="0" data-i18n-aria-label="wave.selStart"></div>
+ <div class="handle end" id="w-h-end" role="slider" tabindex="0" data-i18n-aria-label="wave.selEnd"></div>
+ </div>
+ <div class="playhead" id="w-playhead"></div>
+ <div class="wave-loading muted small" id="w-loading" data-i18n="wave.loading">Loading waveform…</div>
+ </div>
+ <div class="overview" id="w-overview" data-i18n-title="wave.overview" hidden>
+ <canvas id="w-ov-canvas" aria-hidden="true"></canvas>
+ <div class="view-box" id="w-view"></div>
+ </div>
+ <div class="sel-bar">
+ <span class="sel-label" data-i18n="wave.selection">Selection</span>
+ <label class="sel-field"><span data-i18n="wave.start">Start</span><input type="number" id="w-start" class="num" min="0" step="0.01" inputmode="decimal"></label>
+ <label class="sel-field"><span data-i18n="wave.end">End</span><input type="number" id="w-end" class="num" min="0" step="0.01" inputmode="decimal"></label>
+ <span class="sel-len" id="w-len"></span>
+ <button type="button" class="link-btn" id="w-sel-all" data-i18n="wave.selectAll">Select all</button>
+ <button type="button" class="link-btn" id="w-sel-clear" data-i18n="wave.clear">Clear</button>
+ <span class="spacer"></span>
+ <span class="muted small wave-help" id="w-help" data-i18n="wave.help"></span>
+ </div>
+ </div>
+
+ <div class="edit-body">
+ <div class="panel edit-tools">
+ <div class="subtabs" role="tablist">
+ <button role="tab" id="st-ai" aria-selected="true" aria-controls="ai-form" data-i18n="edit.aiTab">Change with AI</button>
+ <button role="tab" id="st-export" aria-selected="false" aria-controls="export-form" data-i18n="edit.exportTab">Export</button>
+ </div>
+
+ <form id="ai-form" class="form-body" role="tabpanel" aria-labelledby="st-ai" novalidate>
+ <fieldset class="field">
+ <legend class="sr-only" data-i18n="edit.mode">Mode</legend>
+ <div class="mode-cards" id="mode-cards">
+ <label class="mode-card"><input type="radio" name="mode" value="variation" checked><span class="mode-name" data-i18n="mode.variation">Make a variation</span><span class="mode-desc" data-i18n="mode.variationDesc"></span></label>
+ <label class="mode-card"><input type="radio" name="mode" value="inpaint"><span class="mode-name" data-i18n="mode.inpaint">Replace a section</span><span class="mode-desc" data-i18n="mode.inpaintDesc"></span></label>
+ <label class="mode-card"><input type="radio" name="mode" value="continue"><span class="mode-name" data-i18n="mode.continue">Extend</span><span class="mode-desc" data-i18n="mode.continueDesc"></span></label>
+ </div>
+ </fieldset>
+
+ <div class="field" id="strength-field">
+ <label for="strength"><span data-i18n="edit.strength">How different?</span> <output id="strength-out" class="muted"></output></label>
+ <input id="strength" name="strength" type="range" min="0.05" max="1" step="0.05" value="0.6">
+ <div class="range-labels muted small"><span data-i18n="edit.subtle">Close to the original</span><span data-i18n="edit.loose">Very different</span></div>
+ </div>
+
+ <p class="note" id="inpaint-note" hidden></p>
+
+ <div class="field" id="extend-field" hidden>
+ <label for="ai-duration" data-i18n="edit.totalLength">Total length after extending (seconds)</label>
+ <div class="inline">
+ <input id="ai-duration" name="duration_seconds" class="num" type="number" min="1" step="1" inputmode="decimal">
+ <div class="chips" id="extend-chips"></div>
+ </div>
+ <p class="hint" id="extend-hint"></p>
+ </div>
+
+ <div class="field">
+ <label for="ai-prompt" id="ai-prompt-label" data-i18n="edit.prompt">Description (English)</label>
+ <textarea id="ai-prompt" name="prompt" rows="2" spellcheck="false"></textarea>
+ <p class="hint" id="ai-prompt-hint"></p>
+ </div>
+
+ <div class="row">
+ <div class="field">
+ <label for="ai-type" data-i18n="gen.typeShort">Type</label>
+ <select id="ai-type" name="audio_type">
+ <option value="music" data-i18n="type.music">Music</option>
+ <option value="instrument" data-i18n="type.instrument">Instrument</option>
+ <option value="sfx" data-i18n="type.sfx">Sound effect</option>
+ </select>
+ </div>
+ <fieldset class="field">
+ <legend data-i18n="gen.variations">Versions</legend>
+ <div class="segmented compact">
+ <label><input type="radio" name="variations" value="1"><span>1</span></label>
+ <label><input type="radio" name="variations" value="2" checked><span>2</span></label>
+ <label><input type="radio" name="variations" value="3"><span>3</span></label>
+ <label><input type="radio" name="variations" value="4"><span>4</span></label>
+ </div>
+ </fieldset>
+ </div>
+
+ <details class="advanced" id="ai-advanced">
+ <summary data-i18n="gen.advanced">Advanced</summary>
+ <div class="field">
+ <label for="ai-title" data-i18n="gen.name">File name</label>
+ <input id="ai-title" name="title" type="text" data-i18n-placeholder="gen.namePh">
+ </div>
+ <div class="row">
+ <div class="field"><label for="ai-seed" data-i18n="adv.seed">Seed</label><input id="ai-seed" name="seed" type="number" min="-1" step="1" data-i18n-placeholder="adv.seedPh"></div>
+ <div class="field"><label for="ai-cfg" data-i18n="adv.cfg">Prompt strength (CFG)</label><input id="ai-cfg" name="cfg" type="number" min="0" max="15" step="0.5" placeholder="1.0"></div>
+ <div class="field"><label for="ai-steps" data-i18n="adv.steps">Steps</label><input id="ai-steps" name="steps" type="number" min="1" max="50" step="1" placeholder="8"></div>
+ </div>
+ <div class="field">
+ <label for="ai-negative" data-i18n="adv.negative">Negative prompt</label>
+ <input id="ai-negative" name="negative_prompt" type="text" data-i18n-placeholder="adv.negativePh">
+ </div>
+ </details>
+
+ <p class="form-error" id="ai-error" role="alert" hidden></p>
+ <div class="actions"><button type="submit" class="btn btn-primary btn-lg" id="ai-submit"></button></div>
+ </form>
+
+ <form id="export-form" class="form-body" role="tabpanel" aria-labelledby="st-export" novalidate hidden>
+ <fieldset class="field">
+ <legend data-i18n="exp.purpose">What is it for?</legend>
+ <div class="preset-grid" id="presets"></div>
+ <p class="hint" id="preset-desc"></p>
+ </fieldset>
+
+ <label class="check" id="trim-sel-row"><input type="checkbox" name="trim_selection" id="x-trim-sel"><span id="x-trim-sel-text"></span></label>
+
+ <details class="advanced" id="x-custom">
+ <summary data-i18n="exp.customize">Customize</summary>
+ <div class="checks">
+ <label class="check"><input type="checkbox" name="trim_silence"><span data-i18n="exp.trimSilence">Remove silence at the start and end</span></label>
+ <label class="check"><input type="checkbox" name="mono"><span data-i18n="exp.mono">Mono</span></label>
+ <label class="check"><input type="checkbox" name="loop"><span data-i18n="exp.loop">Seamless loop</span></label>
+ </div>
+ <div class="row">
+ <div class="field">
+ <label for="x-normalize" data-i18n="exp.volume">Volume</label>
+ <select id="x-normalize" name="normalize">
+ <option value="none" data-i18n="exp.volNone">Keep as is</option>
+ <option value="peak" data-i18n="exp.volPeak">Peak (loudest point)</option>
+ <option value="loudness" data-i18n="exp.volLoud">Loudness (LUFS)</option>
+ </select>
+ </div>
+ <div class="field" id="x-lufs-field"><label for="x-lufs" data-i18n="exp.lufs">Target (LUFS)</label><input id="x-lufs" name="target_lufs" type="number" min="-40" max="-5" step="1"></div>
+ <div class="field"><label for="x-peak" data-i18n="exp.peak">Peak limit (dBFS)</label><input id="x-peak" name="peak_ceiling_db" type="number" min="-24" max="0" step="0.5"></div>
+ </div>
+ <div class="row">
+ <div class="field" id="x-xfade-field"><label for="x-xfade" data-i18n="exp.xfade">Loop crossfade (ms)</label><input id="x-xfade" name="loop_crossfade_ms" type="number" min="1" max="5000" step="10"></div>
+ <div class="field"><label for="x-fin" data-i18n="exp.fadeIn">Fade in (ms)</label><input id="x-fin" name="fade_in_ms" type="number" min="0" max="10000" step="10"></div>
+ <div class="field"><label for="x-fout" data-i18n="exp.fadeOut">Fade out (ms)</label><input id="x-fout" name="fade_out_ms" type="number" min="0" max="10000" step="10"></div>
+ </div>
+ <div class="row">
+ <fieldset class="field">
+ <legend data-i18n="exp.format">Format</legend>
+ <div class="segmented compact">
+ <label><input type="radio" name="format" value="wav"><span>WAV</span></label>
+ <label><input type="radio" name="format" value="ogg"><span>OGG</span></label>
+ <label><input type="radio" name="format" value="flac"><span>FLAC</span></label>
+ </div>
+ </fieldset>
+ <fieldset class="field">
+ <legend data-i18n="exp.rate">Sample rate</legend>
+ <div class="segmented compact">
+ <label><input type="radio" name="sample_rate" value="44100"><span>44.1 kHz</span></label>
+ <label><input type="radio" name="sample_rate" value="48000"><span>48 kHz</span></label>
+ </div>
+ </fieldset>
+ </div>
+ <div class="field">
+ <label for="x-title" data-i18n="gen.name">File name</label>
+ <input id="x-title" name="title" type="text" data-i18n-placeholder="exp.namePh">
+ </div>
+ </details>
+
+ <p class="summary small" id="x-summary"></p>
+ <p class="form-error" id="x-error" role="alert" hidden></p>
+ <div class="actions"><button type="submit" class="btn btn-primary btn-lg" id="x-submit" data-i18n="exp.submit">Export</button></div>
+ </form>
+ </div>
+
+ <div class="results">
+ <div class="results-head"><h2 data-i18n="edit.results">Results from this sound</h2></div>
+ <div id="edit-jobs" class="jobs"></div>
+ <p class="empty-state small" id="edit-jobs-empty" data-i18n="edit.noResults"></p>
+ </div>
+ </div>
</div>
</section>
@@ -139,13 +364,18 @@
</div>
<p class="muted small folder" id="lib-folder"></p>
<div id="library" class="library"></div>
- <p class="empty" id="lib-empty" hidden data-i18n="lib.empty">No audio files yet.</p>
+ <div class="empty-state" id="lib-empty" hidden>
+ <p class="empty-title" id="lib-empty-text"></p>
+ <button type="button" class="btn" id="lib-empty-btn"></button>
+ </div>
<div class="more"><button class="btn btn-quiet" id="lib-more" hidden data-i18n="lib.more">Show more</button></div>
</section>
</main>
<div class="toast" id="toast" role="status" aria-live="polite" hidden></div>
<script src="/static/i18n.js"></script>
+<script src="/static/wave.js"></script>
+<script src="/static/editor.js"></script>
<script src="/static/app.js"></script>
</body>
</html>
diff --git a/src/audio_studio_mcp/static/wave.js b/src/audio_studio_mcp/static/wave.js
new file mode 100644
index 0000000..d15b51f
--- /dev/null
+++ b/src/audio_studio_mcp/static/wave.js
@@ -0,0 +1,164 @@
+// Waveform drawing, peaks loading and the shared player for result / library
+// cards. One <audio> element plays every card, so starting one sound stops the
+// previous one; the editor has its own element and pauses this one (and back).
+"use strict";
+
+const Peaks = {
+ cache: new Map(), // key -> Promise of the /api/peaks answer
+ get(file, n, start, end) {
+ const q = `n=${n}` + (start != null ? `&start=${start.toFixed(4)}&end=${end.toFixed(4)}` : "");
+ const key = `${file}?${q}`;
+ if (!this.cache.has(key)) {
+ if (this.cache.size > 200) this.cache.clear();
+ const p = fetch(`/api/peaks/${encodeURIComponent(file)}?${q}`).then((r) => {
+ if (!r.ok) throw new Error(`peaks ${r.status}`);
+ return r.json();
+ });
+ p.catch(() => this.cache.delete(key));
+ this.cache.set(key, p);
+ }
+ return this.cache.get(key);
+ },
+};
+
+function cssVar(name) { return getComputedStyle(document.documentElement).getPropertyValue(name).trim(); }
+
+// Size a canvas to its CSS box at device resolution; returns the 2D context.
+function fitCanvas(cv) {
+ const dpr = window.devicePixelRatio || 1, r = cv.getBoundingClientRect();
+ const w = Math.max(1, Math.round(r.width * dpr)), h = Math.max(1, Math.round(r.height * dpr));
+ if (cv.width !== w || cv.height !== h) { cv.width = w; cv.height = h; }
+ return cv.getContext("2d");
+}
+
+// Draw min/max columns. `split` (0..1) colours the part left of it as played.
+function drawPeaks(ctx, mins, maxs, { color, played, split = 0, x0 = 0, x1 = ctx.canvas.width, gain = 1 }) {
+ const H = ctx.canvas.height, mid = H / 2, n = mins.length, w = x1 - x0;
+ if (!n || w <= 0) return;
+ const amp = (H / 2 - 1) * gain;
+ const splitX = x0 + split * w;
+ for (let x = Math.floor(x0); x < x1; x++) {
+ const i0 = Math.floor(((x - x0) / w) * n), i1 = Math.max(i0 + 1, Math.floor(((x + 1 - x0) / w) * n));
+ let lo = 1, hi = -1;
+ for (let i = i0; i < i1 && i < n; i++) { if (mins[i] < lo) lo = mins[i]; if (maxs[i] > hi) hi = maxs[i]; }
+ if (hi < lo) continue;
+ const top = mid - hi * amp, bot = mid - lo * amp;
+ ctx.fillStyle = played && x < splitX ? played : color;
+ ctx.fillRect(x, top, 1, Math.max(1, bot - top));
+ }
+}
+
+// ── shared card player ─────────────────────────────────────────────────────
+const Player = {
+ audio: new Audio(),
+ file: null,
+ owner: null, // the MiniWave currently loaded
+ listeners: new Set(),
+ init() {
+ const a = this.audio;
+ a.preload = "auto";
+ const tick = () => this.emit();
+ for (const ev of ["play", "pause", "ended", "timeupdate", "loadedmetadata", "seeked"]) a.addEventListener(ev, tick);
+ a.addEventListener("play", () => { this.raf(); window.dispatchEvent(new CustomEvent("as:play", { detail: "cards" })); });
+ window.addEventListener("as:play", (e) => { if (e.detail !== "cards") a.pause(); });
+ let rt; // redraw thumbnails after a resize or theme change
+ const redraw = () => { clearTimeout(rt); rt = setTimeout(() => this.emit(), 100); };
+ window.addEventListener("resize", redraw);
+ window.addEventListener("as:theme", redraw);
+ matchMedia("(prefers-color-scheme: dark)").addEventListener("change", redraw);
+ },
+ raf() {
+ if (this.audio.paused) return;
+ this.emit();
+ requestAnimationFrame(() => this.raf());
+ },
+ emit() { for (const f of this.listeners) f(); },
+ async play(mini, at) {
+ const a = this.audio;
+ if (this.file !== mini.file) {
+ this.file = mini.file;
+ a.src = audioUrl(mini.file);
+ }
+ this.owner = mini;
+ if (at != null) {
+ if (a.readyState < 1) await new Promise((r) => a.addEventListener("loadedmetadata", r, { once: true }));
+ a.currentTime = Math.min(at, (a.duration || at) - 0.01);
+ }
+ try { await a.play(); } catch { /* interrupted by another play() */ }
+ this.emit();
+ },
+ pause() { this.audio.pause(); },
+ isPlaying(mini) { return this.owner === mini && !this.audio.paused; },
+ time(mini) { return this.owner === mini ? this.audio.currentTime : 0; },
+};
+
+// Compact player: play button + waveform thumbnail (click / arrow keys seek) + time.
+class MiniWave {
+ constructor(file, seconds) {
+ this.file = file;
+ this.seconds = seconds || 0;
+ this.peaks = null;
+ this.btn = el("button", { class: "play-btn", type: "button", "aria-label": t("player.play"), onclick: () => this.toggle() });
+ this.cv = el("canvas", { class: "mini-wave-canvas", "aria-hidden": "true" });
+ this.track = el("div", { class: "mini-wave-track", role: "slider", tabindex: "0", "aria-label": t("player.position"),
+ "aria-valuemin": "0", onpointerdown: (e) => this.seekPointer(e), onkeydown: (e) => this.key(e) }, this.cv);
+ this.time = el("span", { class: "mini-time" });
+ this.node = el("div", { class: "mini-wave", dataset: { file } }, this.btn, this.track, this.time);
+ this.node.mini = this;
+ this.update = () => this.render();
+ Player.listeners.add(this.update);
+ MiniWave.observer.observe(this.node);
+ this.render();
+ }
+ async load() {
+ if (this.peaks) return;
+ try {
+ this.peaks = await Peaks.get(this.file, 240);
+ this.seconds = this.peaks.seconds;
+ } catch { this.peaks = { min: [], max: [] }; }
+ this.render();
+ }
+ toggle() { Player.isPlaying(this) ? Player.pause() : Player.play(this, Player.owner === this ? null : 0); }
+ seekTo(sec) { Player.play(this, Math.max(0, Math.min(this.seconds, sec))); }
+ seekPointer(e) {
+ if (!this.seconds) return;
+ const r = this.track.getBoundingClientRect();
+ this.seekTo(((e.clientX - r.left) / r.width) * this.seconds);
+ }
+ key(e) {
+ const step = e.shiftKey ? 5 : 1, now = Player.time(this);
+ if (e.key === "ArrowRight") this.seekTo(now + step);
+ else if (e.key === "ArrowLeft") this.seekTo(now - step);
+ else if (e.key === "Home") this.seekTo(0);
+ else if (e.key === " " || e.key === "Enter") this.toggle();
+ else return;
+ e.preventDefault();
+ }
+ render() {
+ if (!this.node.isConnected && this.drawn) { Player.listeners.delete(this.update); return; }
+ const playing = Player.isPlaying(this), now = Player.time(this);
+ this.btn.classList.toggle("playing", playing);
+ this.btn.setAttribute("aria-label", playing ? t("player.pause") : t("player.play"));
+ this.time.textContent = Player.owner === this && now > 0 ? `${fmtClock(now)} / ${fmtClock(this.seconds)}` : fmtClock(this.seconds);
+ this.track.setAttribute("aria-valuemax", String(Math.round(this.seconds * 10) / 10));
+ this.track.setAttribute("aria-valuenow", String(Math.round(now * 10) / 10));
+ this.track.setAttribute("aria-valuetext", `${fmtClock(now)} / ${fmtClock(this.seconds)}`);
+ if (!this.peaks || !this.node.isConnected) return;
+ const ctx = fitCanvas(this.cv);
+ ctx.clearRect(0, 0, this.cv.width, this.cv.height);
+ drawPeaks(ctx, this.peaks.min, this.peaks.max, {
+ color: cssVar("--wave"), played: cssVar("--wave-played"), split: this.seconds ? now / this.seconds : 0 });
+ this.drawn = true;
+ }
+}
+MiniWave.observer = new IntersectionObserver((entries) => {
+ for (const e of entries) if (e.isIntersecting) { e.target.mini.load(); MiniWave.observer.unobserve(e.target); }
+}, { rootMargin: "200px" });
+
+// m:ss.t for waveform times, m:ss for card lengths
+function fmtClock(sec, decimals = 0) {
+ sec = Math.max(0, sec || 0);
+ const m = Math.floor(sec / 60), s = sec - m * 60;
+ const ss = decimals ? s.toFixed(decimals).padStart(3 + decimals, "0") : String(Math.floor(s)).padStart(2, "0");
+ return `${m}:${ss}`;
+}
diff --git a/tests/fake_web_server.py b/tests/fake_web_server.py
index 11a5598..7d90f48 100644
--- a/tests/fake_web_server.py
+++ b/tests/fake_web_server.py
@@ -7,6 +7,8 @@ import sys
import time
from pathlib import Path
+import numpy as np
+
sys.path.insert(0, str(Path(__file__).parent))
from conftest import FakeBackend # noqa: E402
@@ -16,7 +18,14 @@ from audio_studio_mcp import server # noqa: E402
class SlowFake(FakeBackend):
def _generate(self, seeds, req):
time.sleep(float(os.environ.get("FAKE_DELAY", "0")))
- return super()._generate(seeds, req)
+ res = super()._generate(seeds, req)
+ # beats with decays, so the waveform looks like audio in screenshots
+ for s, a in zip(seeds, res.audios):
+ t = np.arange(a.shape[-1]) / self.sample_rate
+ beat = 0.5 + s % 3 * 0.1
+ env = np.exp(-6 * (t % beat)) * (0.35 + 0.3 * np.sin(2 * np.pi * t / (3 + s % 4)) ** 2)
+ a *= env.astype(np.float32)
+ return res
server.set_backend(SlowFake())