微软(TTS)文本转语音服务API实现

04-23 1334阅读 0评论

此博客实现与java实现微软文本转语音(TTS)经验总结_java tts_${简简单单}的博客-CSDN博客之上,首先感谢博客源码的提供,本人在上面添加了一些详细的注释,方便大家跟好的理解和使用,毕竟我已经用原文调试了一下午才调通,一些细节的问题给大家标注出来,免得浪费大家的时间,下面直接开始代码吧!

首先大家需要去微软官网获取到密钥,方便调用时可以使用,大家注意看下图,我们一定要注意给我们分配到的区域,我这里是分配到eastus ,就是east us(美国东部)的意思,大家一定需要注意一下,后面会使用到的,然后终结点里面的地址就是我们获取token的地址

下面我们准备几个类,方便后面使用,大家把代码都复制到自己项目中,不要有遗漏:

package com.daoversal.util;
public class ByteArray {
    private byte[] data;
    private int length;
 
    public ByteArray(){
        length = 0;
        data = new byte[length];
    }
 
    public ByteArray(byte[] ba){
        data = ba;
        length = ba.length;
    }
 
    /**
    合并数组
     */
    public  void cat(byte[] second, int offset, int length){
 
        if(this.length + length > data.length) {
            int allocatedLength = Math.max(data.length, length);
            byte[] allocated = new byte[allocatedLength  0) {
                ba.cat(buf2, 0, rn2);
            }
            inSt.close();
            webRequest.disconnect();
            return ba.getArray();
        } catch (Exception e) {
            log.error("Synthesis tts speech failed {}", e.getMessage());
        }
        return null;
    }
}
package com.daoversal.util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.concurrent.TimeUnit;
/**
 * 此类获取token,每次调用都需要使用到token的
 * token的有效期是10分钟,但是不建议大家10分钟调一次,免得使用了失效的token
 */
@Component
@Slf4j
public class Authentication {
    @Autowired
    private RedissonClient redisson;
    public String genAccessToken() {
        InputStream inSt;
        HttpsURLConnection webRequest;
        try {
            //先从redis里面取缓存的token,如果没有就远程拉取,有的话就直接使用,大家可根据自己的业务调整
            Object ob = redisson.getBucket("accessToken").get();
            String accessToken = ob == null ? null : ob.toString();
            if (StringUtils.isEmpty(accessToken)) {
                webRequest = HttpsConnection.getHttpsConnection(TtsConst.ACCESS_TOKEN_URI);
                webRequest.setDoInput(true);
                webRequest.setDoOutput(true);
                webRequest.setConnectTimeout(5000);
                webRequest.setReadTimeout(5000);
                webRequest.setRequestMethod("POST");
 
                byte[] bytes = new byte[0];
                webRequest.setRequestProperty("content-length", String.valueOf(bytes.length));
                //api的key,取微软官网获取
                webRequest.setRequestProperty("Ocp-Apim-Subscription-Key", TtsConst.API_KEY);
                webRequest.connect();
 
                DataOutputStream dop = new DataOutputStream(webRequest.getOutputStream());
                dop.write(bytes);
                dop.flush();
                dop.close();
 
                inSt = webRequest.getInputStream();
                InputStreamReader in = new InputStreamReader(inSt);
                BufferedReader bufferedReader = new BufferedReader(in);
                StringBuilder strBuffer = new StringBuilder();
                String line = null;
                while ((line = bufferedReader.readLine()) != null) {
                    strBuffer.append(line);
                }
 
                bufferedReader.close();
                in.close();
                inSt.close();
                webRequest.disconnect();
 
                accessToken = strBuffer.toString();
                //获取到了token,缓存到redis里面,5分钟失效
                redisson.getBucket("accessToken").set(accessToken,5L, TimeUnit.MINUTES);
                //设置accessToken的过期时间为5分钟
                log.info("New tts access token {}", accessToken);
            }
            return accessToken;
        } catch (Exception e) {
            log.error("Generate tts access token failed {}", e.getMessage());
        }
        return null;
    }
}

最后就是调用了,大家可以测试了:

package com.daoversal.web;
import com.daoversal.framework.http.Response;
import com.daoversal.task.DvWeekCountTask;
import com.daoversal.task.RechargeTask;
import com.daoversal.task.UserGradeCountTask;
import com.daoversal.task.WindControlMsgTask;
import com.daoversal.util.TtsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import okhttp3.*;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
/**
 * 

* 套餐价值释放记录表 前端控制器 *

* * @author HayDen * @since 03 22 10:44:13 */ @RestController @RequestMapping("/test") @Api(value = "test") public class TestController { @Resource private TtsService testService; @PostMapping("/ttsService") @ApiOperation(value = "获取ttsService", httpMethod = "POST" ) public void ttsService(String text) { // byte[] bte = testService.genAudioBytes(res,"en-US","Male","en-US-JennyNeural"); byte[] bte = testService.genAudioBytes(text,"zh-CN","Male","zh-CN-YunxiNeural"); String value = "hllo.mp3"; convertByteArrayToFile(bte,value); System.out.println("213213123"); } /** * 此文件是将byte[] 转换成文件存储到指定路径的 * @param arr * @param value */ public static void convertByteArrayToFile(byte[] arr,String value) { try ( BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(arr)); //这里是转换以后的文件存储的路径 FileOutputStream fileOutputStream = new FileOutputStream("/Users/recovery/Downloads/"+value); BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream) ) { int data; while ((data = bis.read()) != -1) { bos.write(data); } bos.flush(); } catch (IOException e) { e.printStackTrace(); } } }

最后大家需要注意一下就是如果你选的是英文en-US,但是输入的文本是中文的话他是不会翻译的,所以大家一定要注意自己的语言类型不要弄错了,如果有疑问可以留言哦,我看到肯定会毫无保留的给大家说明的。

如果这篇文章在你一筹莫展的时候帮助到了你,可以请作者吃个棒棒糖🙂,如果有啥疑问或者需要完善的地方欢迎大家在下面留言或者私信作者优化改进。

微软(TTS)文本转语音服务API实现


免责声明
本网站所收集的部分公开资料来源于AI生成和互联网,转载的目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。
文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。

发表评论

快捷回复: 表情:
评论列表 (暂无评论,1334人围观)

还没有评论,来说两句吧...

目录[+]