实现文字转语音功能

 

Python实现文字转语音功能 https://zhuanlan.zhihu.com/p/26726297

 

语音库(发音人) - 朗读女 http://www.443w.com/tts/?post=2

 

文档中心--百度AI https://ai.baidu.com/docs#/TTS-Online-Python-SDK/top

 

 

 

Java SDK_语音合成(TTS)_智能语音交互-阿里云 https://help.aliyun.com/document_detail/30431.html

 

package com.mycom;


import com.alibaba.idst.nls.NlsClient;
import com.alibaba.idst.nls.NlsFuture;
import com.alibaba.idst.nls.event.NlsEvent;
import com.alibaba.idst.nls.event.NlsListener;
import com.alibaba.idst.nls.protocol.NlsRequest;
import com.alibaba.idst.nls.protocol.NlsResponse;

import java.io.File;
import java.io.FileOutputStream;

import java.util.Random;

import java.io.IOException;
import java.util.logging.*;
import java.text.SimpleDateFormat;

public class TTSmy implements NlsListener {
    private NlsClient client = new NlsClient();
    private String akId;
    private String akSecert;
    private String tts_text = "薄雾浓云愁永昼。瑞脑消金兽。阿里巴巴与四十大盗。";
    String LogDir = "D://JAVALOGtts//";

    public TTSmy(String akId, String akSecret) {
        System.out.println("init Nls client...");
        this.akId = akId;
        this.akSecert = akSecret;
        // 初始化NlsClient
        client.init();
    }

    public void shutDown() {
        System.out.println("close NLS client");
        client.close();
        System.out.println("demo done");

    }

    public void startTTS() {
        String audioDir = "D:/AliTts/";
//        String audiopath = audioDir + "InforId_" + this.randomPositiveIntWithTm() + ".wav";
        String audiopath = audioDir + "A_0627InforId_" + this.randomPositiveIntWithTm() + ".mp3";
        File file = new File(audiopath);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        NlsRequest req = new NlsRequest();
        String appkey = "nls-service";
        req.setAppKey(appkey);//设置语音文件格式
        req.setTtsRequest(tts_text);
        req.setTtsEncodeType("wav");//返回语音数据格式,支持pcm,wav,alaw
        req.setTtsVolume(30);//音量大小,阈值0-100
        req.setTtsSpeechRate(0);//语速,阈值-500~500
        req.setTtsBackgroundMusic(1, 0);//背景音乐编号,偏移量
        req.authorize(akId, akSecert);
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            NlsFuture future = client.createNlsFuture(req, this);//实例化请求,传入请求和监听器
            int total_len = 0;
            byte[] data;
            while ((data = future.read()) != null) {
                fileOutputStream.write(data, 0, data.length);
            }
            fileOutputStream.close();
            System.out.println("tts audio file size is :" + total_len);
            future.await(10000);//设置服务端超时时间
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onMessageReceived(NlsEvent e) {
        NlsResponse response = e.getResponse();
        String result = "";
        int statusCode = response.getStatus_code();
        if (response.getTts_ret() != null) {
            result += "\nget tts result: statusCode=[" + statusCode + "], " + response.getTts_ret();
        }

        if (result != null) {
            System.out.println(result);
        } else {
            System.out.println("response.jsonResults.toString()");
        }
    }

    @Override
    public void onOperationFailed(NlsEvent e) {
        //识别失败的回调
        System.out.print("on operation failed");
        System.out.println(e.getErrorMessage());
    }

    @Override
    public void onChannelClosed(NlsEvent e) {
        //socket连接关闭的回调
        System.out.println("on websocket closed;");


    }


    /*
     * user defined function
     *
     * */
    public int randomPositiveInt() {
        int i = new Random().nextInt();
        return Math.abs(i);
    }

    public String randomPositiveIntWithTm() {
        int i = this.randomPositiveInt();
        long tmMillis = System.currentTimeMillis();
        String r = String.valueOf(i) + "_" + String.valueOf(tmMillis);
        return r;
    }

    public static String getThisFilename() {
        return Thread.currentThread().getStackTrace()[2].getFileName();
    }

    public static String getThisClassname() {
        return Thread.currentThread().getStackTrace()[2].getClassName();
    }

    //    public static void main(String[] args) {
    public static void main(String[] args) throws SecurityException, IOException {
//        String akId = args[0];
//        String akSecret = args[1];
        String akId = "L7";
        String akSecret = "rrq72";

        TTSmy tts = new TTSmy(akId, akSecret);
        //todo log4j
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd--HH-mm-ss");
        long cTm = System.currentTimeMillis();
        String df = sdf.format(cTm);

        Logger logger = Logger.getLogger(tts.getClass().getName());
        String fn = tts.LogDir + df + tts.getThisFilename() + ".log";
        FileHandler fileHandler = new FileHandler(fn);
        LogRecord lr = new LogRecord(Level.INFO, "akId,akSecret:" + akId + "_" + akSecret);
        SimpleFormatter sf = new SimpleFormatter();
        fileHandler.setFormatter(sf);
        logger.addHandler(fileHandler);
        logger.log(lr);

        tts.startTTS();
        tts.shutDown();
    }

}

  

posted @ 2018-04-04 14:52  papering  阅读(390)  评论(0编辑  收藏  举报