tts_ceshi.py 3.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. from pathlib import Path
  2. from typing import Optional
  3. import time # 新增:导入时间模块
  4. import requests
  5. URL = "http://127.0.0.1:1024/tts"
  6. def tts_request(
  7. text: str,
  8. voice: Optional[str] = None,
  9. rate: Optional[str] = None,
  10. volume: Optional[str] = None,
  11. pitch: Optional[str] = None,
  12. output_path: str = "speech.wav",
  13. ):
  14. """Send text to Edge TTS server and save returned audio file.
  15. 新增:记录请求开始/结束时间,计算总耗时
  16. """
  17. # ========== 新增:记录请求开始时间 ==========
  18. start_time = time.time() # 开始时间(时间戳)
  19. start_time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(start_time)) # 格式化开始时间
  20. print(f"📅 请求开始时间: {start_time_str}")
  21. headers = {"Content-Type": "application/json"}
  22. data = {"text": text}
  23. if voice:
  24. data["voice"] = voice
  25. if rate:
  26. data["rate"] = rate
  27. if volume:
  28. data["volume"] = volume
  29. if pitch:
  30. data["pitch"] = pitch
  31. try:
  32. resp = requests.post(URL, json=data, headers=headers, timeout=30)
  33. # ========== 新增:记录请求结束时间 & 计算耗时 ==========
  34. end_time = time.time()
  35. end_time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(end_time))
  36. total_duration = round((end_time - start_time) * 1000, 2) # 总耗时(毫秒)
  37. print(f"📅 请求结束时间: {end_time_str}")
  38. print(f"⏱️ 请求总耗时: {total_duration} 毫秒")
  39. print("服务器响应状态码:", resp.status_code)
  40. print("服务器响应内容类型:", resp.headers.get("Content-Type"))
  41. # 成功返回音频流
  42. if resp.status_code == 200 and str(resp.headers.get("Content-Type", "")).startswith("audio/"):
  43. Path(output_path).write_bytes(resp.content)
  44. print(f"✅ 已保存音频到 {output_path}")
  45. # ========== 新增:返回结果中包含时间信息 ==========
  46. return {
  47. "file": output_path,
  48. "start_time": start_time_str,
  49. "end_time": end_time_str,
  50. "duration_ms": total_duration # 耗时(毫秒)
  51. }
  52. # 非 200 时解析错误并抛出
  53. try:
  54. detail = resp.json()
  55. except Exception:
  56. detail = resp.text
  57. print("⚠️ 接口返回错误:", detail)
  58. resp.raise_for_status()
  59. return None
  60. except requests.exceptions.HTTPError as e:
  61. print(f"HTTP 错误: {e}")
  62. return None
  63. except requests.exceptions.ConnectionError:
  64. print("❌ 无法连接到服务器,请检查 IP/端口 或服务器是否在线")
  65. return None
  66. except requests.exceptions.Timeout:
  67. print("❌ 请求超时,请检查服务器网络")
  68. return None
  69. except Exception as e:
  70. print(f"其他错误: {str(e)}")
  71. return None
  72. if __name__ == "__main__":
  73. # 示例:直接克隆文字
  74. result = tts_request("克隆文字", voice="zh-CN-YunxiaNeural", rate="+0%", volume="+0%", pitch="+0Hz")
  75. if result:
  76. print("请求成功:", result)
  77. # 示例:单独提取时间信息
  78. print(f"音频生成耗时: {result['duration_ms']} 毫秒")
  79. else:
  80. print("请求失败")