springboot微软文本转语音(texttospeach) java实现微软文本转语音

java实现微软文本转语音(TTS)经验总结

  • 官网地址:

    https://docs.microsoft.com/zh-cn/azure/cognitive-services/speech-service/quickstarts/setup-platform?tabs=windows%2Cubuntu%2Cdotnet%2Cjre%2Cmaven%2Cnodejs%2Cmac%2Cpypi&pivots=programming-language-java

  • 参数文档和其他文档

    https://docs.microsoft.com/zh-cn/java/api/com.microsoft.cognitiveservices.speech.speechconfig?view=azure-java-stable#com-microsoft-cognitiveservices-speech-speechconfig-fromsubscription(string-string)

  • 选到语音名称

    在ssml选一个语音,会生成到左边代码里,voice name=‘xxxxxx’

    https://azure.microsoft.com/zh-cn/services/cognitive-services/text-to-speech/#features

一、直接上代码

方式一:直接调用

  <dependency>
      <groupId>com.microsoft.cognitiveservices.speechgroupId>
      <artifactId>client-sdkartifactId>
      <version>1.12.1version>
  dependency>

@PostMapping("/text-to-url")
    @ApiOperation("地址识别")
    public Result getArea(String text) {
        SpeechConfig speechConfig = SpeechConfig.fromSubscription("你的apiKey", "eastasia");//key,地区
        speechConfig.setSpeechSynthesisLanguage("zh-CN");//语言
        speechConfig.setSpeechSynthesisVoiceName("zh-CN-XiaoxiaoNeural");//语言名称
     	 speechConfig.setSpeechSynthesisOutputFormat(SpeechSynthesisOutputFormat.Riff24Khz16BitMonoPcm);
        SpeechSynthesizer synthesizer = new SpeechSynthesizer(speechConfig, null);
        SpeechSynthesisResult result = synthesizer.SpeakText(text);
        AudioDataStream stream = AudioDataStream.fromResult(result);
        stream.saveToWavFile("D:/file.wav");//生成位置
        stream.close();
        return new Result();
    }

方式二:ssml(因为别人写过了,我这边就不写了,实测不好用,看了官方文档,写了方式一)

  • 参考地址:http://t.zoukankan.com/aohongzhu-p-15174381.html

  • 参考地址的原文地址:https://www.cnblogs.com/aohongzhu/p/15174381.html

改进(退化成没有redis)

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
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.Date;
@Component
@Slf4j
public class Authentication {
    private String assessToken = null;//token缓存
    private Date setTime = null;//设置的有效时间
    /**
     * @param token   新获取的token
     *
     */
    private void setToken(String token) {
        this.assessToken = token;
        this.setTime = new Date(new Date().getTime() + TtsConst.ACCESS_TOKEN_EXPIRE_TIME * 1000L);
    }
    /**
     * 判断是否在有效期前
     * @return token
     */
    private String getAssessToken() {
        Date date = new Date();
        if (date.getTime() - this.setTime.getTime() < 0L) {
            return this.assessToken;
        }
        return null;
    }
    public String genAccessToken() {
        InputStream inSt;
        HttpsURLConnection webRequest;

        try {
            String accessToken = this.getAssessToken();
            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));
                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();
                //设置accessToken的过期时间为9分钟
                this.setToken(accessToken);
                log.info("获取微软tss token成功,token: {}", accessToken);
            }
            return accessToken;
        } catch (Exception e) {
            log.error("生成微软tss token失败,错误信息:{}", e.getMessage());
        }
        return null;
    }
}

你可能感兴趣的:(Java,java,spring,boot,microsoft)