opentts离线文字转语音

298 阅读1分钟

采用opentts

1.配置镜像源

cd /etc/docker/

vim daemon.json

{
 "registry-mirrors": ["https://docker.m.daocloud.io"],
 "exec-opts": ["native.cgroupdriver=systemd"],
 "experimental": true
}

2.重新加载

1018 sudo systemctl daemon-reload

1019 sudo service docker restart

3.拉取镜像

docker.aityp.com/image/docke…

docker pull swr.cn-north-4.myhuaweicloud.com/ddn-k8s/docker.io/synesthesiam/opentts:zh-2.1

4.运行镜像

docker run -d -p 5500:5500 swr.cn-north-4.myhuaweicloud.com/ddn-k8s/docker.io/synesthesiam/opentts:zh-2.1

5.访问

http://192.168.10.131:5500/

6.开发

@RestController
@RequestMapping("/leisure")
@Validated
@EnableAutoTryCatch
public class ConverApi {
    @Autowired
    private RestTemplate restTemplate;

    public Object getTtsResponse(String text) {
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.set("Accept", "*/*");
        headers.set("Accept-Encoding", "identity;q=1, *;q=0");
        headers.set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");
        headers.set("Connection", "keep-alive");
        headers.set("Range", "bytes=0-");
        HttpEntity<String> requestEntity = new HttpEntity<>(headers);
        String url = "http://ip:5500/api/tts";
        String requestUrl = UriComponentsBuilder.fromHttpUrl(url)
        .queryParam("voice", "coqui-tts:zh_baker")
        .queryParam("text", text)
        .queryParam("vocoder", "high")
        .queryParam("denoiserStrength", "0.03")
        .queryParam("cache", "false")
        .build(false) // 禁用编码
        .toUriString();

        ResponseEntity<byte[]> response = restTemplate.exchange(requestUrl, HttpMethod.GET, requestEntity, byte[].class);
        if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
            // 保存文件
            try (FileOutputStream fileOutputStream = new FileOutputStream("output.wav")) {
                fileOutputStream.write(response.getBody());
            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } else {
            throw new RuntimeException("TTS服务响应异常: " + response.getStatusCode());
        }
        return "";
    }

    @GetMapping("/conver")
    public Result<String> conver() throws Exception {
        getTtsResponse("告警信息,请注意查收");
        return Result.ofSuccess();
    }

}

禁用编码: 不然响应和浏览器不一致