input-box.js 6.76 KB
// components/tab-input/index.js
const {
  ALIYUN
} = require("~/config")
const getToken = require("~/utils/aliyun/token").getToken
const SpeechRecognition = require("~/utils/aliyun/sr")
const sleep = require("~/utils/aliyun/util").sleep
Component({

  /**
   * 组件的属性列表
   */
  properties: {
    isSend: {
      type: Boolean,
      value: true,
      observer: function (n) {
        this.setData({
          isClear: n
        })
      }
    },
    promptOnOff: {
      type: Boolean,
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    show: false,
    tipsOpen: true,
    startTimeStamp: 0,
    isListening: false,
    inputType: 2
  },
  attached() {
    this.connectSr()
    const _this = this;
    wx.getRendererUserAgent({
      success(res) {
        let isPad = /iPad|Android.*Tablet|Kindle|Silk/i.test(res.userAgent)
        _this.setData({
          isPad
        })
      }
    })
  },
  /**
   * 组件的方法列表
   */
  methods: {
    // 获取焦点
    focusEven(e) {
      this.triggerEvent('setInput', 1)
    },

    // 失去焦点
    blurEven(e) {
      this.triggerEvent('setInput', 0)
    },
    onClose() {
      this.setData({
        show: false,
        isClose: true
      })
      this.onSrStop()
    },
    tabType(e) {
      const {
        type: inputType
      } = e.target.dataset
      this.setData({
        inputType
      })
    },
    openTips(e) {
      const {
        type
      } = e.target.dataset
      this.setData({
        tipsOpen: type == 0
      })
      this.triggerEvent('speech', {
        tips: type == 0,
        status: 'tab'
      })
    },
    onSrStop: async function () {
      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) {
          console.log("close sr failed:" + e)
        }
      }
    },
    onSrStart: async function () {
      if (!this.data.sr) {
        console.log("sr is null")
        return
      }

      if (this.data.srStart) {
        console.log("sr is started!")
        return
      }
      let sr = this.data.sr
      try {
        await sr.start(sr.defaultStartParams())
        this.data.srStart = true
      } catch (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) {
          wx.removeSavedFile({
            filePath: res.tempFilePath
          })
        }
      })
      wx.getRecorderManager().onError((res) => {
        console.log("recording failed:" + res)
      })

      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) => {
        const {
          result
        } = JSON.parse(msg).payload
        const {
          isClose
        } = this.data
        if (!isClose) {
          if (!result) {
            wx.$util.showToast('没有声音')
            return
          }
          this.triggerEvent('send', result)
        }

      })

      sr.on("closed", () => {
        console.log("Client recv closed")
      })

      sr.on("failed", (msg) => {
        console.log("Client recv failed:", msg)
        this.setData({
          srResult: msg
        })
      })

      this.data.sr = sr
    },
    sendMsg() {
      const {
        isClear
      } = this.data;
      this.triggerEvent('send', this.data.inputValue);
      if (isClear) this.setData({
        inputValue: ''
      })
    },
    handleInput(e) {
      let inputValue = e.detail
      this.setData({
        inputValue
      })
    },
    setInputValue(inputValue) {
      this.setData({
        inputValue
      })
    },
    touchstart(e) {
      this.setData({
        startTimeStamp: e.timeStamp
      })
    },
    // 手指按下事件
    onPress() {
      const _this = this
      wx.getSetting({
        success(res) {
          if (!res.authSetting['scope.record']) {
            wx.authorize({
              scope: 'scope.record',
              success() {
                _this.setData({
                  show: true
                })
                _this.triggerEvent('setzindex', -1)
                _this.onSrStart()
              },
              fail() {
                // 用户拒绝了授权
                console.log('用户拒绝了授权')
                wx.showModal({
                  title: '提示',
                  content: '需要获取录音权限,请点击确定进入设置页面进行授权。',
                  showCancel: false,
                  success(res) {
                    if (res.confirm) {
                      wx.openSetting({
                        success(res) {
                          console.log(res.authSetting)
                          // 用户在设置页面设置了录音权限
                          if (res.authSetting['scope.record']) {
                            console.log('用户在设置页面设置了录音权限')
                          } else {
                            console.log('用户在设置页面未设置录音权限')
                          }
                        }
                      })
                    }
                  }
                })
              }
            })
          } else {
            _this.setData({
              show: true
            })
            _this.triggerEvent('setzindex', -1)
            _this.onSrStart()
          }
        }
      })
    },
    onSend() {
      this.setData({
        show: false,
        isClose: false
      })
      this.triggerEvent('setzindex', 100)
      this.onSrStop()
    },
  }
})