All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.qingxun.javasdkapi.examples.OnlineVoiceTransOpenApiClientDemo Maven / Gradle / Ivy

package com.qingxun.javasdkapi.examples;

import cn.hutool.core.util.ArrayUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qingxun.javasdkapi.clients.OnlineVoiceTransOpenApiClient;
import com.qingxun.javasdkapi.clients.OnlineVoiceTransWebSocketClient;
import com.qingxun.javasdkapi.request.OnlineVoiceGetConnecionIdRequest;
import com.qingxun.javasdkapi.request.OnlineVoiceGetDownloadUrlRequest;
import com.qingxun.javasdkapi.response.OnlineMsg;
import com.qingxun.javasdkapi.response.OnlineVoiceGetConnectionIdResponse;
import com.qingxun.javasdkapi.response.OnlineVoiceGetDownloadUrlResponse;
import org.apache.commons.lang3.StringUtils;
import org.java_websocket.handshake.ServerHandshake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.URISyntaxException;

import static com.qingxun.javasdkapi.common.JsonUtil.objectMapper;

/**
 * 语音识别翻译
 */
public class OnlineVoiceTransOpenApiClientDemo {

    private final static String appId = "您的appId";
    private final static String privateKey = "您的privateKey";
    private final static String fromLan = "语音的原语言";
    private final static String toLan = "语音的目标语言";

    private final static OnlineVoiceTransOpenApiClient onlineVoiceTransOpenApiClient = new OnlineVoiceTransOpenApiClient(appId, privateKey);

    private final static Logger log = LoggerFactory.getLogger(OnlineVoiceTransOpenApiClientDemo.class);


    public static OnlineVoiceGetConnectionIdResponse getConnectionId() {
        OnlineVoiceGetConnecionIdRequest onlineVoiceGetConnecionIdRequest = new OnlineVoiceGetConnecionIdRequest.Builder().setFrom(fromLan)
                .setTo(toLan).builder();
        return onlineVoiceTransOpenApiClient.excute(onlineVoiceGetConnecionIdRequest);
    }

    public static OnlineVoiceGetDownloadUrlResponse getDownloadUrl(Integer recordId) {
        OnlineVoiceGetDownloadUrlRequest onlineVoiceGetDownloadUrlRequest = new OnlineVoiceGetDownloadUrlRequest.Builder().setRecordId(recordId).builder();
        return onlineVoiceTransOpenApiClient.excute(onlineVoiceGetDownloadUrlRequest);
    }


    //自定义在线语音处理逻辑
    static class OnlineHandler extends OnlineVoiceTransWebSocketClient.AbstractOnlineVoiceHandler {

        private Integer recordId;

        private String websocketUrl;

        public OnlineHandler(Integer recordId,String websocketUrl) {
            this.recordId = recordId;
            this.websocketUrl = websocketUrl;
        }

        @Override
        public void handMessage(OnlineMsg onlineMsg) {
            try {
                log.info("接收到内容{}",objectMapper.writeValueAsString(onlineMsg));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            if (onlineMsg == null) {
                return;
            }
            if (onlineMsg.getState().equals("transing")) {
                if (onlineMsg.getMsgType() != null && onlineMsg.getMsgType() == 0) {
                    log.info("语音识别 原文:{}", onlineMsg.getTransMsg());
                }
                if (onlineMsg.getMsgType() != null && onlineMsg.getMsgType() == 1) {
                    log.info("语音识别 译文:{}", onlineMsg.getTransMsg());
                }
            }
            if (onlineMsg.getState().equals("receiveend")) {
                log.info("由于余额不足或者长时间未发送语音数据导致服务器拒绝接受在线语音数据");
            }
            if (onlineMsg.getState().equals("sucess")) {
                log.info("在线语音全部转写翻译成功");
                //下载译文音频
                OnlineVoiceGetDownloadUrlResponse onlineVoiceGetDownloadUrlResponse = getDownloadUrl(recordId);
                try {
                    log.info("译文音频的下载链接{}", objectMapper.writeValueAsString(onlineVoiceGetDownloadUrlResponse));
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }

            }

        }

        @Override
        public void handleOpen(ServerHandshake serverHandshake) {
            log.info("{}连接成功",websocketUrl);

        }

        @Override
        public void handleClose(int i, String s, boolean b) {
            log.info("连接关闭{} {} {}",i,s,b);
        }

        @Override
        public void handleError(Exception e) {
            e.printStackTrace();

        }
    }

    public static void main(String[] args) throws URISyntaxException, IOException, InterruptedException {

        OnlineVoiceGetConnectionIdResponse response = getConnectionId();
        log.info("获取connectionId结果{}",objectMapper.writeValueAsString(response));
        if (null == response || response.getRecordId() == null || StringUtils.isEmpty(response.getConnectionId())) {
            log.error("获取connectionId失败");
        }
        String url = onlineVoiceTransOpenApiClient.getConnectionWebSocketUrl(response.getConnectionId());
       log.info("连接地址{}",url);
        OnlineHandler onlineHandler = new OnlineHandler(response.getRecordId(),url);
        //在线语音websocket连接
        OnlineVoiceTransWebSocketClient onlineVoiceTransWebSocketClient = new OnlineVoiceTransWebSocketClient(url, onlineHandler);
        onlineVoiceTransWebSocketClient.connect();
        //模拟发送在线语音
        FileInputStream inputStream = new FileInputStream("/Users/cedric/Downloads/test.wav");
        int bufferSize = 2560;
        byte[] b = new byte[bufferSize];
        int len;
        int all = 0;
        while (!onlineVoiceTransWebSocketClient.isOpen()) {
            Thread.sleep(1000);
        }
        try {
            while ((len = inputStream.read(b)) > 0) {
                all += 1;
                log.info("发送了{}字节,共发送{}次,需要发送{}次", len, all, (inputStream.available() / 2560));
                //发送语音数据
                onlineVoiceTransWebSocketClient.send(ArrayUtil.sub(b, 0, len));
            }
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
        onlineVoiceTransWebSocketClient.send("{\"state\":\"recordend\",\"transMsg\":null,\"msgType\":null}");

        Thread.sleep(600000L);

    }


}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy