SpeechPopup.js 5.9 KB
const {
  ALIYUN
} = require("~/config")
const getToken = require("~/utils/aliyun/token").getToken
const SpeechRecognition = require("~/utils/aliyun/sr")
const sleep = require("~/utils/aliyun/util").sleep

let timer = null
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    show: {
      type: Boolean,
      value: false,
      observer: function (n) {
        if (n) {
          this.onStart();
        } else {
          this.clearTime()
        }
      }
    },
    // 对话灵感内容
    inspirationContent: {
      type: String,
      observer: function (n) {
        this.setData({content:n})
      }
    }
  },
  /**
   * 组件的初始数据
   */
  data: {
    times: 0,
  },
  lifetimes:{
    attached() {
      console.log('attached')
      this.connectSr()
    },
    detached: function() {
        this.data.srStart = false
        wx.getRecorderManager().stop()
        if (this.data.sr) {
            this.data.sr.shutdown()
        } else {
            console.log("sr is null")
        }
    },
  },

  /**
   * 组件的方法列表
   */
  methods: {
    clearTime() {
      this.setData({
        times:0
      })
      clearInterval(timer)
      timer = null
    },
    onSrStop: async function () {
      console.log('onSrStop')
      wx.getRecorderManager().stop()
      await sleep(500)
      if (this.data.srStart && this.data.sr) {
        try {
          console.log("prepare close sr")
          await this.data.sr.close()
          this.data.srStart = false
        } catch (e) {
          this.triggerEvent('close')
          this.data.srStart = false
          console.log("close sr failed:" + e)
        }
      }
    },
    onSrStart: async function () {
      if (!this.data.sr) {
        const {
          name
        } = wx.$util.getUserInfo();
        wx.$sendSentry(name+'语音识别连接失败')
        console.log("sr is null")
        return
      }
      if (this.data.srStart) {
        console.log("sr is started!")
        return
      }
      
      let {
        times
      } = this.data
      timer = setInterval(() => {
        if(times >= 59) {
          this.onSend()
        }
        this.setData({
          times: ++times
        })
      }, 1000) 
      let sr = this.data.sr
      try {
        let param = sr.defaultStartParams();
        console.log(param,'param')
        // param.audio_address = 'https://glsk-oss.oss-cn-shenzhen.aliyuncs.com/quality/27199017763051.mp3'
        await sr.start(param)
        this.data.srStart = true
      } catch (e) {
        wx.$sendSentry('语音转文字连接失败' + JSON.stringify(e))
        console.log("start failed:" + e)
        return
      }
      wx.getRecorderManager().start({
        duration: 600000,
        numberOfChannels: 1,
        sampleRate: 16000,
        format: "mp3",
        frameSize: 4
      })
    },
    connectSr: async function (options) {
      wx.getRecorderManager().onFrameRecorded((res) => {
        if (res.isLastFrame) {
          console.log("record done")
        }
        if (this.data.sr && this.data.srStart) {
          console.log("send " + res)
          this.data.sr.sendAudio(res.frameBuffer)
        }
      })
      wx.getRecorderManager().onStart(() => {
        console.log("start recording...")
      })
      wx.getRecorderManager().onStop((res) => {
        console.log("stop recording...")
        if (res.tempFilePath) {
          const {isClose} = this.data
          if(isClose) {
          wx.removeSavedFile({
            filePath: res.tempFilePath
          })
          }else {
            this.setData({filePath:res.tempFilePath})
          }
        }
      })
      wx.getRecorderManager().onError((res) => {
        console.log("recording failed:" + res)
        wx.$sendSentry('语音转文字失败' + JSON.stringify(res))
        // this.connectSr()
      })
      try {
        this.data.token = await getToken(ALIYUN.AKID,
          ALIYUN.AKKEY)
      } catch (e) {
        console.log("error on get token:", JSON.stringify(e))
        return
      }
      let sr = new SpeechRecognition({
        url: ALIYUN.URL,
        appkey: ALIYUN.APPKEY,
        token: this.data.token
      })
      sr.on("started", (msg) => {
        console.log("Client recv started")
        this.setData({
          srResult: msg
        })
      })
      sr.on("changed", (msg) => {
        console.log("Client recv changed:", msg)
        this.setData({
          srResult: msg
        })
      })
      sr.on("completed", (msg) => {
        console.log(JSON.parse(msg))
        const {
          result
        } = JSON.parse(msg).payload
        const {
          isClose,
          times,
          filePath
        } = this.data
        if (!isClose) {
          if (!result) {
            wx.$util.showToast('没有声音')
            // this.data.srStart = false
            this.triggerEvent('close')
            return
          }
          if(times)
          this.triggerEvent('send', {result,filePath,times:times>60?60:times})
        }
      })
      sr.on("closed", () => {
        console.log("Client recv closed");
        // this.data.srStart = false
      })
      sr.on("failed", (msg) => {
        console.log("Client recv failed:", msg)
        this.setData({
          srResult: msg
        })
      })
      this.data.sr = sr
    },
    // 开始事件
    onStart() {
      this.onSrStart()
    },
    onReset: wx.$util.throttle(function (e) {
      this.setData({
        isClose: true
      }, () => {
        this.onSrStop()
      })
      setTimeout(()=>{
        this.clearTime()
        this.setData({
          times:0
        },()=>{
          this.onSrStart()
        })
       
      },1000)
    },1500),
    onClose() {
      this.setData({
        isClose: true
      }, () => {
        this.triggerEvent('close')
        this.onSrStop()
      })
    },
    onSend: wx.$util.throttle(function (e) {
      this.setData({
        isClose: false
      }, () => {
        this.onSrStop()
      })
    },1500),
  }
})