1. Application scenarios

Assume a scenario where a patient is in critical condition and needs to be seen by a doctor urgently, and write an emergency report for subsequent treatment. At this time, the system needs to actively push messages to the doctor. In order to better attract attention, voice broadcasting is adopted. Use StompJs and the SpeechSynthesis interface to do this.

2. Introduce StompJS

Speaking of real-time push of server messages, I believe many people will think of WebSocket. The server only needs to complete a handshake with the browser, and persistent connection can be established between the two, and two-way data transmission can be carried out. WebSocket can save server resources and bandwidth, and is the first choice for real-time communication.

Stomp is an upper-layer protocol based on WebSocket (SockJS). The implementation of Websocket on the client side looks relatively simple, but it needs good coordination and debugging with the background to achieve the best effect. Browser compatibility through SockJS and Stomp increases message semantics and usability.

1. Install

npm install stompjs
npm install sockjs-client
Copy the code

2. Create a client

/ / use StompJs
let url = "ws://xxxx";
let socket = new SockJS(url);
let client = Stomp.over(socket);

/ / using the WebSocket
let url = "ws://xxxx";
let client = Stomp.client(url);
Copy the code

3. Connect server (CONNECT)

client.connect({login,passcode},successCallback,errorCallback);
// login,passcode is the user's login and password credentials,
// successCallback callback to connect successfully
ErrorCallback Callback for connection failure
Copy the code

4. Disconnect

client.disconnect(function(){
   console.log("Disconnect")})Copy the code

5.Heart-beating

“Heart-beating” : the frequency of sending a message. It has two properties: incoming is the receiving frequency and outgoing is the sending frequency. The default value is 10000ms and the value is set manually.

client.heartbeat.incoming = 5000;
client.heartbeat.outgoing = 5000;
Copy the code

6. Send a message

The client sends a message to the server using client.send(destination, {}, body) with three parameters:

  • The first argument (string) is required and is the destination to which the message is sent;
  • The second argument (object) is optional and contains additional header information;
  • The third argument (string) is optional, the message to be sent.

7. Subscribe messages

The client receives the message sent by the server using client.subscribe(destination, callback, {}) with three arguments

  • The first argument (string) is required, the destination to receive the message;
  • The second argument, required, is a callback function;
  • The third parameter {object} is optional and contains additional header information.

8. Unsubscribe

Unsubscribe messages can use the unsubscribe() method

let mySubscribe =  client.subscribe;
 mySubscribe.unsubscribe();
Copy the code

3. Introduce SpeechSynthesis

HTML5 new voice synthesis API, used to synthesize the specified text into the corresponding voice, does not support IE browser.

SpeechSynthesisUtterance

The SpeechSynthesisUtterance interface contains what speech services should read and information about how to read (such as language, tone, and volume).

attribute

  • textThings to read
  • langLanguage used (e.g. “zh-cn”)
  • pitchThe tone of speech (0-2, default 1, the higher the value is, the sharper, the lower the lower)
  • rateSpeaking speed (between 0.1 and 10, default 1, the larger the value is, the faster you speak, the smaller the slower you speak)
  • voiceSet the speaking voice
  • volumeVolume (0-1, default 1)

methods

  • onstartTriggered when speech synthesis begins
  • onpauseTriggered when voice pauses
  • onresumeTriggered when speech synthesis resumes
  • onendTrigger when voice ends

A text instance can be created using New SpeechSynthesisUtterance (), whereas real speech is created with speechSynthesis.

The SpeechSynthesis interface is the control interface for speech services; It can be used to get information on the device about available synthetic sounds, to start, pause, or to do other commands

Here are some common methods:

  • speakStart synthesizing the voice, adding the corresponding instance to the voice queue
  • cancelStop synthesizing speech and delete all speech in the queue
  • pausePause speech synthesis
  • resumeResume paused voice
  • getVoicesReturns an array of voice packages supported by the browser

Use the sample

let u = new SpeechSynthesisUtterance()
u.text = 'Hello, cicada.'
u.lang = 'zh'
u.rate = 0.8
window.speechSynthesis.speak(u)
Copy the code

4. Code practices

import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
export default{
  data(){
    return{
      stompClient:null.connectNumber:0}},mounted(){
    this.initWebSocket()
  },
  methods:{
    initWebSocket () {
      // Create a connection object
      let socket = new SockJS('/ws')
      // Get the client object of the STOMP subprotocol
      this.stompClient = Stomp.over(socket)
      // Initiate a Websocket connection to the server
      this.stompClient.connect({}, this.onConnected, this.onError)
    },
    onConnected () {
      this.stompClient.subscribe('/user/queue/newRegisterSend'.function (payload) {
         // When the message is received, the voice broadcast is performed
         let u = new SpeechSynthesisUtterance()
         u.text = payload.body
         u.lang = 'zh'
         u.rate = 0.8
         window.speechSynthesis.speak(u)
      })
      this.connectNumber = 0
    },
    onError () {
      this.connectNumber++
      if(this.connectNumber<10) {this.initWebSocket()
      }
    },
     disconnect () {
      // Check whether the previous connection is established and disconnect it immediately. Otherwise, the connection will be disconnected after 3 seconds
      if (this.stompClient && this.stompClient.connected) {
        this.stompClient.disconnect()
      } else if (this.stompClient && !this.stompClient.connected) {
        setTimeout(function () {
          that.stompClient.disconnect()
        }, 3000)}}},beforeDestroy: function () {
    // Disconnect when the page leaves and clear the timer
    if (this.stompClient) {
      this.disconnect()
    }
  }
}
Copy the code
Copy the code