语音交互服务 SIS-websocket接口:代码示例

时间:2024-07-03 11:01:13

代码示例

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;

/**
 * 此demo仅供测试使用,强烈建议使用SDK
 * 使用前需已配置okhttp、okio jar包。jar包可通过下载SDK获取。
 */
public class SasrWebsocketDemo {
  public void sasrWebsocketDemo() {
    try {
      // endpoint和projectId需要替换成实际信息。
      String url = "wss://{{endpoint}}/v1/{{project_id}}/asr/short-audio";
      String token = "对应region的token";
      byte[] data = null;  // 存放将要发送音频的byte数组
      OkHttpClient okHttpClient = new OkHttpClient();
      Request request = new Request.Builder().url(url).header("X-Auth-Token", token).build();
      WebSocket webSocket = okHttpClient.newWebSocket(request, new MyListener());
      webSocket.send("{\"command\": \"START\", \"config\": {\"audio_format\": \"pcm8k16bit\", \"property\": \"chinese_8k_common\"}}");
      webSocket.send(ByteString.of(data));  // audio太大注意要分片发送,否则会报错。建议分片大小3200
      webSocket.send("{  \"command\": \"END\"}");
      Thread.sleep(10000);
      webSocket.close(1000, null);

    } catch (Exception e) {
      e.printStackTrace();
    }

  }

  class MyListener extends WebSocketListener {
    @Override

    public void onOpen(WebSocket webSocket, Response response) {
      System.out.println("conneected");
    }

    @Override
    public void onClosed(WebSocket webSocket, int code, String reason) {

      System.out.println("closed");
    }

    @Override
    public void onFailure(WebSocket webSocket, Throwable t, Response response) {
      t.printStackTrace();
    }

    @Override
    public void onMessage(WebSocket webSocket, String text) {
      System.out.println(text);
    }

  }

  public static void main(String[] args) {
    SasrWebsocketDemo sasrWebsocketDemo = new SasrWebsocketDemo();
    sasrWebsocketDemo.sasrWebsocketDemo();
  }
}
support.huaweicloud.com/api-sis/sis_03_0095.html