ESP32调用本地部署的ChatTTS
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); // 目标URLString 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 handledSerial.printf("[HTTP] GET... code: %d\n", httpCode);// file found at serverif(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);// 连接到WiFiWiFi.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() {
}