1 本地部署ChatTTS
参考 windows10部署ChatTTS+Apifox调用
2 实现过程
部署好本地ChatTTS模型后,测试接口正常。让ESP32接入局域网络,发送post请求生成wav文件,ESP32通过远程获取文件来得到音频文件,并播放音频文件。
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
const char* ssid = "EzhanNet";
const char* password = "11111111";
const char* serverUrl = "http://192.168.0.121:9994/tts";
void sendPostTTSRequest() {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin(serverUrl); // 目标URL
String payload = "text=windows&voice=1111&top_p=0.7&top_k=20&temperature=0.3&custom_voice=3531&refine_max_new_token=384";
http.addHeader("Content-Type", "application/x-www-form-urlencoded"); // 设置请求头
int httpResponseCode = http.POST(payload); // 发送 POST 请求
if (httpResponseCode > 0) {
String response = http.getString(); // 获取响应
Serial.printf("Response code: %d\n", httpResponseCode);
// Serial.println("Response: " + response);
getWavFile(response);
} else {
Serial.println("发送 POST 时出错: " + String(httpResponseCode));
}
http.end(); // 结束请求
} else {
Serial.println("WiFi not connected");
}
}
void getWavFile(String response) {
// 解析 JSON 响应
DynamicJsonDocument docJson(4096);
DeserializationError error = deserializeJson(docJson, response);
if (!error) {
const char* response_info = docJson["url"];
Serial.println("chattts speak file: " + String(response_info));
HTTPClient http2;
http2.begin(String(response_info));
int httpCode = http2.GET();
if(httpCode > 0) {
// HTTP header has been send and Server response header has been handled
Serial.printf("[HTTP] GET... code: %d\n", httpCode);
// file found at server
if(httpCode == HTTP_CODE_OK) {
String payload = http2.getString();
Serial.println(payload);
}
} else {
Serial.printf("[HTTP] GET... failed, error: %s\n", http2.errorToString(httpCode).c_str());
}
http2.end();
} else {
Serial.println("解析 JSON 失败: " + String(error.c_str()));
}
}
void setup() {
Serial.begin(115200);
// 连接到WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
Serial.print("IP : ");
Serial.println(WiFi.localIP());
sendPostTTSRequest();
}
void loop() {
}