添加续播与 seek 支持

- play_file 增加 start_at 参数(ffmpeg -ss 快进)
- stop 记录停止位置,player_status 增加 stopped_at/resumable
- 新增 resume() 从上次位置续播
- 新增 seek(seconds) 跳到指定位置
- MCP.md 同步更新
This commit is contained in:
jmj committed 2026-11-30 03:25:39 +08:00
1 parent 4ac2e959e0
commit 5f42bb8cdc
3 files changed
+83 -19

No files matched your search

+8 -2
View File
@@ -57,8 +57,14 @@ TTS 语音播报。**这是最常用的工具。**
下载音频到 NAS 音乐库(默认 `storages/music`),返回 `{"ok", "path", "bytes"}`。之后可用 `play_file` 播放。
**设计原则**:AI 只传 URL / 路径引用,**不要通过 MCP 传音频二进制**。
### `play_file(path, volume?)`
播放 NAS 上已有的音频文件,路径必须以 `/vol1/` 开头。
### `play_file(path, volume?, start_at?)`
播放 NAS 上已有的音频文件,路径必须以 `/vol1/` 开头。`start_at` 可指定从第几秒开始。
### `resume(volume?)`
从上次 `stop()` 的位置继续播放。没有可续播内容时返回 `ok: false`。
### `seek(seconds, volume?)`
从当前/上次音频的指定秒数开始播放(如跳到第 30 秒)。
### `stop()`
停止当前播放(TTS 或音乐)。正在播放时再次调用 `speak` 也会先停止前一个。
+42 -14
View File
@@ -152,7 +152,8 @@ _play_lock = threading.Lock()
_current: Optional[subprocess.Popen] = None
_current_lock = threading.Lock()
# 播放状态跟踪(供 player_status 查询)
_now: dict = {"playing": False, "source": None, "started_at": None, "title": None, "duration": None}
_now: dict = {"playing": False, "source": None, "started_at": None, "title": None, "duration": None,
"start_at": 0.0, "stopped_at": None} # start_at: 本次从第几秒开始;stopped_at: 上次停止时的位置
def _probe_duration(src: str) -> Optional[float]:
@@ -166,6 +167,13 @@ def _probe_duration(src: str) -> Optional[float]:
return None
def _elapsed() -> float:
"""当前已播放的绝对位置(秒)= 起始偏移 + 实际经过时间。"""
if not _now.get("started_at") or not _now.get("playing"):
return _now.get("stopped_at") or 0.0
return _now["start_at"] + max(0.0, time.time() - _now["started_at"])
def player_state() -> dict:
"""返回当前播放状态,含进度。"""
with _current_lock:
@@ -173,12 +181,13 @@ def player_state() -> dict:
playing = bool(p and p.poll() is None)
st = dict(_now)
st["playing"] = playing
dur = st.get("duration")
if playing and st.get("started_at"):
elapsed = max(0.0, time.time() - st["started_at"])
elapsed = max(0.0, st["start_at"] + time.time() - st["started_at"])
st["elapsed_sec"] = round(elapsed, 1)
if st.get("duration"):
st["progress_pct"] = round(min(100.0, elapsed / st["duration"] * 100), 1)
st["remaining_sec"] = round(max(0.0, st["duration"] - elapsed), 1)
if dur:
st["progress_pct"] = round(min(100.0, elapsed / dur * 100), 1)
st["remaining_sec"] = round(max(0.0, dur - elapsed), 1)
else:
st["progress_pct"] = None
st["remaining_sec"] = None
@@ -187,13 +196,23 @@ def player_state() -> dict:
st["progress_pct"] = None
st["remaining_sec"] = None
st["playing"] = False
st["resumable"] = bool(st.get("source") and st.get("stopped_at") and not playing and st["stopped_at"] > 1)
return st
def resume_position() -> Optional[float]:
"""返回可续播的位置(秒),无则 None。"""
st = player_state()
return st["stopped_at"] if st["resumable"] else None
def stop() -> bool:
"""停止当前播放。"""
"""停止当前播放,记录停止位置以便续播。"""
with _current_lock:
p = _current
was_playing = bool(p and p.poll() is None)
if was_playing:
_now["stopped_at"] = round(_elapsed(), 1)
if p and p.poll() is None:
try:
p.terminate()
@@ -204,9 +223,11 @@ def stop() -> bool:
return False
def play(src: str, node: str, vol_pct: Optional[int] = None, blk: bool = True, timeout: float = 600.0) -> dict:
def play(src: str, node: str, vol_pct: Optional[int] = None, blk: bool = True, timeout: float = 600.0,
start_at: float = 0.0) -> dict:
"""
播放文件或 URL(ffmpeg 能解的任何东西,含 http/https 流)。
start_at: 从第几秒开始(seek/续播)。
返回 {"ok", "node", "volume", "seconds"}。
"""
global _current
@@ -223,8 +244,17 @@ def play(src: str, node: str, vol_pct: Optional[int] = None, blk: bool = True, t
return {"ok": False, "error": f"音量校验失败: 请求 {vol}%, 实际 {final_vol:.2f}"}
t0 = time.time()
title = None
if src.startswith("http"):
title = src.split("?")[0].rstrip("/").split("/")[-1] or src
else:
title = os.path.basename(src) or src
duration = _probe_duration(src)
start_at = max(0.0, min(start_at, duration - 1)) if duration else max(0.0, start_at)
# ffmpeg -ss 放在 -i 之前 = 快速 seek(按关键帧),本地文件几乎瞬时
ss = ["-ss", f"{start_at:.2f}"] if start_at > 0 else []
dec = subprocess.Popen(
["ffmpeg", "-v", "error", "-i", src, "-f", "wav", "-ac", "2", "-ar", "44100", "-"],
["ffmpeg", "-v", "error", *ss, "-i", src, "-f", "wav", "-ac", "2", "-ar", "44100", "-"],
env=_env(), stdout=subprocess.PIPE, stderr=subprocess.PIPE,
)
pw = subprocess.Popen(
@@ -232,13 +262,9 @@ def play(src: str, node: str, vol_pct: Optional[int] = None, blk: bool = True, t
env=_env(), stdin=dec.stdout, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
dec.stdout.close()
title = None
if src.startswith("http"):
title = src.split("?")[0].rstrip("/").split("/")[-1] or src
else:
title = os.path.basename(src) or src
_now.update({"source": src, "started_at": time.time(), "title": title,
"duration": _probe_duration(src)})
"duration": duration, "start_at": start_at, "stopped_at": None,
"playing": True})
with _current_lock:
_current = pw # global:让 stop() 能找到并终止它
try:
@@ -253,6 +279,8 @@ def play(src: str, node: str, vol_pct: Optional[int] = None, blk: bool = True, t
with _current_lock:
_current = None
_now["playing"] = False
if rc == 0:
_now["stopped_at"] = None # 自然播完,无可续播
err = ""
if rc != 0:
try:
+33 -3
View File
@@ -104,12 +104,13 @@ def play_url(url: str, volume: Optional[int] = None) -> dict:
@mcp.tool()
def play_file(path: str, volume: Optional[int] = None) -> dict:
def play_file(path: str, volume: Optional[int] = None, start_at: float = 0.0) -> dict:
"""播放 NAS 上已有的音频文件。
Args:
path: 绝对路径,必须在 /vol1/ 下
volume: 音量百分比 0-100
start_at: 从第几秒开始(seek/续播)
"""
p = Path(path).resolve()
if not str(p).startswith("/vol1/") or not p.is_file():
@@ -117,7 +118,7 @@ def play_file(path: str, volume: Optional[int] = None) -> dict:
node, err = _sink_or_error()
if err:
return {"ok": False, "error": err}
return audio.play(str(p), node, volume)
return audio.play(str(p), node, volume, start_at=start_at)
@mcp.tool()
@@ -153,9 +154,38 @@ def download(url: str, save_dir: Optional[str] = None) -> dict:
return audio.download(url, d)
@mcp.tool()
def resume(volume: Optional[int] = None) -> dict:
"""从上次停止的位置继续播放。没有可续播内容时返回 ok: false。"""
pos = audio.resume_position()
if pos is None:
return {"ok": False, "error": "没有可续播的内容(请先播放后再 stop)"}
src = audio._now.get("source")
if not src:
return {"ok": False, "error": "续播源丢失"}
node, err = _sink_or_error()
if err:
return {"ok": False, "error": err}
res = audio.play(src, node, volume, start_at=pos)
return {**res, "resumed_from_sec": pos}
@mcp.tool()
def seek(seconds: float, volume: Optional[int] = None) -> dict:
"""从当前/上次音频的指定位置开始播放(如跳到第 30 秒)。"""
src = audio._now.get("source")
if not src:
return {"ok": False, "error": "没有可跳转的音频"}
node, err = _sink_or_error()
if err:
return {"ok": False, "error": err}
res = audio.play(src, node, volume, start_at=float(seconds))
return {**res, "seek_to_sec": round(float(seconds), 1)}
@mcp.tool()
def stop() -> dict:
"""停止当前正在播放的内容(TTS 或音乐)。"""
"""停止当前正在播放的内容(TTS 或音乐),并记录位置以便 resume() 续播。"""
return {"ok": True, "stopped": audio.stop()}