wsconnecter.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /**
  2. * Copyright FunASR (https://github.com/alibaba-damo-academy/FunASR). All Rights
  3. * Reserved. MIT License (https://opensource.org/licenses/MIT)
  4. */
  5. /* 2021-2023 by zhaoming,mali aihealthx.com */
  6. function WebSocketConnectMethod( config ) { //定义socket连接方法类
  7. var Uri = "wss://111.205.137.58:5821/wss/" //设置wss asr online接口地址 如 wss://X.X.X.X:port/wss/
  8. var speechSokt;
  9. var connKeeperID;
  10. var msgHandle = config.msgHandle;
  11. var stateHandle = config.stateHandle;
  12. this.wsStart = function () {
  13. if ( 'WebSocket' in window ) {
  14. speechSokt = new WebSocket( Uri ); // 定义socket连接对象
  15. speechSokt.onopen = function(e){onOpen(e);}; // 定义响应函数
  16. speechSokt.onclose = function(e){onClose(e);};
  17. speechSokt.onmessage = function(e){onMessage(e);};
  18. speechSokt.onerror = function(e){onError(e);};
  19. }
  20. else {
  21. alert('当前浏览器不支持 WebSocket');
  22. }
  23. };
  24. // 定义停止与发送函数
  25. this.wsStop = function () {
  26. if(speechSokt != undefined) {
  27. speechSokt.close();
  28. }
  29. };
  30. this.wsSend = function ( oneData,stop ) {
  31. if(speechSokt == undefined) return;
  32. if ( speechSokt.readyState === 1 ) { // 0:CONNECTING, 1:OPEN, 2:CLOSING, 3:CLOSED
  33. speechSokt.send( oneData );
  34. if(stop){
  35. setTimeout(speechSokt.close(), 3000 );
  36. }
  37. }
  38. };
  39. // SOCEKT连接中的消息与状态响应
  40. function onOpen( e ) {
  41. // 发送json
  42. var chunk_size = new Array( 5, 10, 5 );
  43. var request = {
  44. "chunk_size": chunk_size,
  45. "wav_name": "h5",
  46. "is_speaking": true,
  47. "chunk_interval":10,
  48. };
  49. speechSokt.send( JSON.stringify(request) );
  50. console.log("连接成功");
  51. stateHandle(0);
  52. }
  53. function onClose( e ) {
  54. stateHandle(1);
  55. }
  56. function onMessage( e ) {
  57. msgHandle( e );
  58. }
  59. function onError( e ) {
  60. info_div.innerHTML="连接"+e;
  61. console.log(e);
  62. stateHandle(2);
  63. }
  64. }