Python调用ChatTTS API接口:
#********************************************* #author:wgscd #date:2024-7-27 #install list: #pip install fastapi #pip install requests #pip install uvicorn[standard] # 在命令行中运行以下命令来启动服务器: #uvicorn main:app --reload (假设mian是你的python代码文件名) #********************************************* import requests import json from fastapi import FastAPI, Path, Query, Header, Cookie from fastapi.responses import RedirectResponse from fastapi.responses import StreamingResponse app = FastAPI() @app.get("/") async def read_root(): return {"Hello": "World"} @app.get("/tts") async def read_items( q: str = Query(None), x_token: str = Header(None), cookie: str = Cookie(None)): some_file_path = getTTSData(q) # r"d:\Pictures\work\roles_audio2.MP3.mp3" if some_file_path=='': return {'err':'no audio file.'} def iterfile(): # (1) with open(some_file_path, mode="rb") as file_like: # (2) yield from file_like # (3) return StreamingResponse(iterfile(), media_type="audio/mpeg") #return RedirectResponse(url="https://www.baidu.com",status_code=308) # 在实际部署时,你需要运行一个ASGI服务器,比如Uvicorn来运行你的FastAPI应用。 # 下面的命令只是示例,用于在开发环境中启动你的应用。 # 在命令行中运行以下命令来启动服务器: #uvicorn 4:app --reload def getTTSData(q:str): print('----6666---------q:'+q) # 目标URL response = requests.post('http://127.0.0.1:9966/tts', data={ "text": q, "prompt": "", "voice": "11.csv", "speed": 5, "temperature": 0.3, "top_p": 0.7, "top_k": 20, "refine_max_new_token": 384, "infer_max_new_token": 2048, "text_seed": 42, "skip_refine": 0, "is_stream": 0, "custom_voice": 333 }) # 检查请求是否成功 if response.status_code == 200: # 将响应内容转换为JSON格式 response_data = response.json() # 现在你可以按需要处理response_data了 print(response_data.get("filename")) return response_data.get("filename") else: print('请求失败,状态码:', response.status_code) return ''
最后在抖灵里添加自定义音色接口地址:http://127.0.0.1:8000/tts?q={text}
附抖灵地址:http://douyin163.top/
标签:ChatTTS,return,Python,app,API,file,import,data,response From: https://www.cnblogs.com/wgscd/p/18327281