wsconnecter.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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 speechSokt;
  8. var connKeeperID;
  9. var msgHandle = config.msgHandle;
  10. var stateHandle = config.stateHandle;
  11. this.wsStart = function () {
  12. var Uri = document.getElementById('wssip').value; //"wss://111.205.137.58:5821/wss/" //设置wss asr online接口地址 如 wss://X.X.X.X:port/wss/
  13. if(Uri.match(/wss:\S*/))
  14. {
  15. console.log("Uri"+Uri);
  16. }
  17. else
  18. {
  19. alert("请检查wss地址正确性");
  20. return 0;
  21. }
  22. if ( 'WebSocket' in window ) {
  23. speechSokt = new WebSocket( Uri ); // 定义socket连接对象
  24. speechSokt.onopen = function(e){onOpen(e);}; // 定义响应函数
  25. speechSokt.onclose = function(e){
  26. console.log("onclose ws!");
  27. speechSokt.close();
  28. onClose(e);
  29. };
  30. speechSokt.onmessage = function(e){onMessage(e);};
  31. speechSokt.onerror = function(e){onError(e);};
  32. return 1;
  33. }
  34. else {
  35. alert('当前浏览器不支持 WebSocket');
  36. return 0;
  37. }
  38. };
  39. // 定义停止与发送函数
  40. this.wsStop = function () {
  41. if(speechSokt != undefined) {
  42. console.log("stop ws!");
  43. speechSokt.close();
  44. }
  45. };
  46. this.wsSend = function ( oneData,stop ) {
  47. if(speechSokt == undefined) return;
  48. if ( speechSokt.readyState === 1 ) { // 0:CONNECTING, 1:OPEN, 2:CLOSING, 3:CLOSED
  49. speechSokt.send( oneData );
  50. if(stop){
  51. setTimeout(speechSokt.close(), 3000 );
  52. }
  53. }
  54. };
  55. // SOCEKT连接中的消息与状态响应
  56. function onOpen( e ) {
  57. // 发送json
  58. var chunk_size = new Array( 5, 10, 5 );
  59. var request = {
  60. "chunk_size": chunk_size,
  61. "wav_name": "h5",
  62. "is_speaking": true,
  63. "chunk_interval":10,
  64. "mode":getAsrMode(),
  65. };
  66. console.log(request);
  67. speechSokt.send( JSON.stringify(request) );
  68. console.log("连接成功");
  69. stateHandle(0);
  70. }
  71. function onClose( e ) {
  72. stateHandle(1);
  73. }
  74. function onMessage( e ) {
  75. msgHandle( e );
  76. }
  77. function onError( e ) {
  78. info_div.innerHTML="连接"+e;
  79. console.log(e);
  80. stateHandle(2);
  81. }
  82. }