wsconnecter.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  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*|ws:\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 ) {
  47. if(speechSokt == undefined) return;
  48. if ( speechSokt.readyState === 1 ) { // 0:CONNECTING, 1:OPEN, 2:CLOSING, 3:CLOSED
  49. speechSokt.send( oneData );
  50. }
  51. };
  52. // SOCEKT连接中的消息与状态响应
  53. function onOpen( e ) {
  54. // 发送json
  55. var chunk_size = new Array( 5, 10, 5 );
  56. var request = {
  57. "chunk_size": chunk_size,
  58. "wav_name": "h5",
  59. "is_speaking": true,
  60. "chunk_interval":10,
  61. "mode":getAsrMode(),
  62. };
  63. if(isfilemode)
  64. {
  65. request.wav_format=file_ext;
  66. }
  67. var hotwords=getHotwords();
  68. if(hotwords.length>0)
  69. {
  70. request.hotwords=hotwords;
  71. }
  72. console.log(request);
  73. speechSokt.send( JSON.stringify(request) );
  74. console.log("连接成功");
  75. stateHandle(0);
  76. }
  77. function onClose( e ) {
  78. stateHandle(1);
  79. }
  80. function onMessage( e ) {
  81. msgHandle( e );
  82. }
  83. function onError( e ) {
  84. info_div.innerHTML="连接"+e;
  85. console.log(e);
  86. stateHandle(2);
  87. }
  88. }