【java 文本转换音频 】

常见的系统需求需要对文字做音频转换处理,liunx上不支持jacob,Jacob是一个针对Windows平台,本篇文章就是简单的做个示例说明下,用到的工具包依赖为:

<dependency>
    <groupId>com.hynnet</groupId>
    <artifactId>jacob</artifactId>
    <version>1.18</version>
</dependency>

文件 jacob-1.18-x64.dll 需放入jre/bin 中,

    public static String textToSpeech(String text){
        ActiveXComponent component = new ActiveXComponent("Sapi.SpVoice");
        Dispatch dispatch = component.getObject();
        String audioUrl = "";
        Dispatch fileStreamDispatch=null;
        Dispatch audioDispatch=null;
        try {
            // 生成空的语音文件
            component = new ActiveXComponent("Sapi.SpFileStream");
            fileStreamDispatch = component.getObject();
            // 音频
            component = new ActiveXComponent("Sapi.SpAudioFormat");
            audioDispatch = component.getObject();
            // 设置文件流格式
            Dispatch.putRef(fileStreamDispatch, "Format", audioDispatch);
            // 设置视频输出流的格式
            Dispatch.put(audioDispatch, "Type", new Variant(22));
            //自动生成 音频存储的位置及文件名称
            String autoPath = "D:3333";
            //拼接文件 类型
            audioUrl = autoPath +".mp3";
            // 调用输出流打开方法,创建一个.wav .mp3 .mp4 .wma文件
            Dispatch.call(fileStreamDispatch,"Open",new Variant(audioUrl),new Variant(3),new Variant(true));
            // 设置声音对象的音频流输出流为输出文件对象
            Dispatch.putRef(dispatch,"AudioOutputStream",fileStreamDispatch);
            // 设置音量大小
            Dispatch.put(dispatch,"Volume",new Variant(100));
            // 将文本读取进去
            Dispatch.call(dispatch, "Speak",new Variant(text));
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            // 关闭输出文件流
            Dispatch.call(fileStreamDispatch,"Close");
            Dispatch.putRef(dispatch,"AudioOutputStream",null);
            audioDispatch.safeRelease();
            fileStreamDispatch.safeRelease();
            dispatch.safeRelease();
            component.safeRelease();
        }
        return audioUrl;
    }

直接使用即可

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值