import it.sauronsoftware.jave.AudioAttributes;
import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.EncodingAttributes;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

public class Speech {

    public void saveWav(String text, String filePath) {
        ActiveXComponent ax = new ActiveXComponent("Sapi.SpVoice");
        Dispatch spVoice = ax.getObject();
        ax = new ActiveXComponent("Sapi.SpFileStream");
        Dispatch spFileStream = ax.getObject();
        ax = new ActiveXComponent("Sapi.SpAudioFormat");
        Dispatch spAudioFormat = ax.getObject();

        // 设置音频流格式
        Dispatch.put(spAudioFormat, "Type", new Variant(22));
        // 设置文件输出流格式
        Dispatch.putRef(spFileStream, "Format", spAudioFormat);
        // 调用输出 文件流打开方法,创建一个.wav文件
        Dispatch.call(spFileStream, "Open", new Variant(filePath), new Variant(
                3), new Variant(true));
        // 设置声音对象的音频输出流为输出文件对象
        Dispatch.putRef(spVoice, "AudioOutputStream", spFileStream);
        // 设置音量 0到100
        Dispatch.put(spVoice, "Volume", new Variant(100));
        // 设置朗读速度
        Dispatch.put(spVoice, "Rate", new Variant(-3));
        // 开始朗读
        Dispatch.call(spVoice, "Speak", new Variant(text));
        // 关闭输出文件
        Dispatch.call(spFileStream, "Close");
        Dispatch.putRef(spVoice, "AudioOutputStream", null);

        spAudioFormat.safeRelease();
        spFileStream.safeRelease();
        spVoice.safeRelease();
        ax.safeRelease();
    }

    public void saveMp3(String text, String filePath) throws Exception {
        File target = new File(filePath);
        //如果文件已经存在直接返回
        if(target.exists()) {
            return;
        }
        String wavPath = filePath.substring(0, filePath.lastIndexOf("."))
                + ".wav";
        saveWav(text, wavPath);
        File source = new File(wavPath);
        AudioAttributes audio = new AudioAttributes();
        audio.setCodec("libmp3lame");
        audio.setBitRate(new Integer(36000));
        audio.setChannels(new Integer(2));
        audio.setSamplingRate(new Integer(44100));
        EncodingAttributes attrs = new EncodingAttributes();
        attrs.setFormat("mp3");
        attrs.setAudioAttributes(audio);
        Encoder encoder = new Encoder();
        encoder.encode(source, target, attrs);
    }
}

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐