且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

阿里云智能语音交互长文本语音合成Java SDK使用说明

更新时间:2022-06-27 08:18:52

使用说明

  • 在使用SDK之前,请先阅读接口说明,详情请参见接口说明
  • 为使用长文本语音合成服务,请将SDK版本更新至2.1.1及以上。
  • 部分超高***景声音(如“知琪”等)暂不支持通过实时接口(Java SDK及C++ SDK)调用,只支持RESTful API异步调用,具体请详见接口说明声音类型支持接口类型列的描述。

下载安装

1.导入Maven依赖文件

<dependency>
    <groupId>com.alibaba.nls</groupId>
    <artifactId>nls-sdk-tts</artifactId>
    <version>2.2.1</version>
</dependency>

代码示例

1.获取token

import java.io.IOException;
import com.alibaba.nls.client.AccessToken;
public class CreateToken {
    public static synchronized String token(String accessKeyId,String accessKeySecret) {
        AccessToken accessToken = new AccessToken(accessKeyId, accessKeySecret);
        try {
            accessToken.apply();
            return accessToken.getToken();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

2.实现代码示例

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

import com.alibaba.ai.zxb.A_Token.CreateToken;
import com.alibaba.nls.client.protocol.NlsClient;
import com.alibaba.nls.client.protocol.OutputFormatEnum;
import com.alibaba.nls.client.protocol.SampleRateEnum;
import com.alibaba.nls.client.protocol.tts.SpeechSynthesizer;
import com.alibaba.nls.client.protocol.tts.SpeechSynthesizerListener;
import com.alibaba.nls.client.protocol.tts.SpeechSynthesizerResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SpeechLongSynthesizerDemo {
    private static final Logger logger = LoggerFactory.getLogger(SpeechLongSynthesizerDemo.class);
    private static long startTime;
    private String appKey;
    NlsClient client;
    public SpeechLongSynthesizerDemo(String appKey, String token, String url) {
        this.appKey = appKey;
        //创建NlsClient实例应用全局创建一个即可。生命周期可和整个应用保持一致,默认服务地址为阿里云线上服务地址。
        if(url.isEmpty()) {
            client = new NlsClient(token);
        } else {
            client = new NlsClient(url, token);
        }
    }
    private static SpeechSynthesizerListener getSynthesizerListener() {
        SpeechSynthesizerListener listener = null;
        try {
            listener = new SpeechSynthesizerListener() {
                File f=new File((int)(1+Math.random()*(500-1+1))+"ttsForLongText"+(int)(1+Math.random()*(500-1+1))+".mp3");
                FileOutputStream fout = new FileOutputStream(f);
                private boolean firstRecvBinary = true;
                //语音合成结束
                @Override
                public void onComplete(SpeechSynthesizerResponse response) {
                    // 调用onComplete时,表示所有TTS数据已经接收完成,因此为整个合成数据的延迟。该延迟可能较大,不一定满足实时场景。
                    System.out.println("name: " + response.getName() + ", status: " + response.getStatus()+", output file :"+f.getAbsolutePath());
                }
                //语音合成的语音二进制数据
                @Override
                public void onMessage(ByteBuffer message) {
                    try {
                        if(firstRecvBinary) {
                            // 此处计算首包语音流的延迟,收到第一包语音流时,即可以进行语音播放,以提升响应速度(特别是实时交互场景下)。
                            firstRecvBinary = false;
                            long now = System.currentTimeMillis();
                            logger.info("tts first latency : " + (now - SpeechLongSynthesizerDemo.startTime) + " ms");
                        }
                        byte[] bytesArray = new byte[message.remaining()];
                        message.get(bytesArray, 0, bytesArray.length);
                        //System.out.println("write array:" + bytesArray.length);
                        fout.write(bytesArray);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                @Override
                public void onFail(SpeechSynthesizerResponse response){
                    // task_id是调用方和服务端通信的唯一标识,当遇到问题时,需要提供此task_id以便排查。
                    System.out.println(
                            "task_id: " + response.getTaskId() +
                                    //状态码
                                    ", status: " + response.getStatus() +
                                    //错误信息
                                    ", status_text: " + response.getStatusText());
                }
            };
        } catch (Exception e) {
            e.printStackTrace();
        }
        return listener;
    }
    public void process(String text) {
        SpeechSynthesizer synthesizer = null;
        try {
            //创建实例,建立连接。
            synthesizer = new SpeechSynthesizer(client, getSynthesizerListener());
            synthesizer.setAppKey(appKey);
            //设置返回音频的编码格式。
            synthesizer.setFormat(OutputFormatEnum.MP3);
            //设置返回音频的采样率。
            synthesizer.setSampleRate(SampleRateEnum.SAMPLE_RATE_16K);
            //发音人。注意Java SDK不支持调用超高***景对应的发音人(例如"zhiqi"),如需调用请使用restfulAPI方式。
            synthesizer.setVoice("siyue");
            //语调,范围是-500~500,可选,默认是0。
            synthesizer.setPitchRate(0);
            //语速,范围是-500~500,默认是0。
            synthesizer.setSpeechRate(0);
            //设置用于语音合成的文本
            // 此处调用的是setLongText接口(原语音合成接口是setText)。
            synthesizer.setLongText(text);
            //此方法将以上参数设置序列化为JSON发送给服务端,并等待服务端确认。
            long start = System.currentTimeMillis();
            synthesizer.start();
            logger.info("tts start latency " + (System.currentTimeMillis() - start) + " ms");
            SpeechLongSynthesizerDemo.startTime = System.currentTimeMillis();
            //等待语音合成结束
            synthesizer.waitForComplete();
            logger.info("tts stop latency " + (System.currentTimeMillis() - start) + " ms");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭连接
            if (null != synthesizer) {
                synthesizer.close();
            }
        }
    }
    public void shutdown() {
        client.shutdown();
    }
    public static void main(String[] args) throws Exception {
        String appKey = "您的appKey";
        String token = CreateToken.token("accessKeyId","accessKeySecret");
        // url取默认值
        String url = "wss://nls-gateway.cn-shanghai.aliyuncs.com/ws/v1";
        String ttsTextLong = "狂人日记 鲁迅 \n" +
                "凡事总须研究,才会明白。古来时常吃人,我也还记得,可是不甚清楚。我翻开历史一查,这历史没有年代,歪歪斜斜的每页上都写着“仁义道德”几个字。我横竖睡不着,仔细看了半夜,才从字缝里看出字来,满本都写着两个字是“吃人”!\n" +
                "书上写着这许多字,佃户说了这许多话,却都笑吟吟的睁着怪眼看我。\n" +
                "我也是人,他们想要吃我了!\n" +
                "吃人的是我哥哥!我是吃人的人的兄弟!\n" +
                "我自己被人吃了,可仍然是吃人的人的兄弟!";
        SpeechLongSynthesizerDemo demo = new SpeechLongSynthesizerDemo(appKey, token, url);
        demo.process(ttsTextLong);
        demo.shutdown();
    }
}

参考链接

智能语音交互JavaSDK