微信小程序語音聊天智能對話(核心源碼)

“智能聊”:微信小程序詳解

這次是1.0版本的更新,整體設計請參考上一篇文章:
手把手教你做自然語言理解智能對話的微信小程序【核心源碼】

本次更新內容:
1.鍵盤輸入框和語音輸入的切換
2.語音輸入圖標

掃碼體驗(小程序名:智能聊

這裏寫圖片描述 這裏寫圖片描述

更新之後的界面:

這裏寫圖片描述

錄音中

這裏寫圖片描述

廢話不多說,直接上代碼:

index.wxml

<view class="container">
  <scroll-view class="scrool-view" scroll-y="true" scroll-with-animation="true" scroll-into-view="{{scrolltop}}" enable-back-to-top="true">
    <view class="chat-list">
      <block wx:for="{{chatList}}" wx:key="time">
        <view id="roll{{index + 1}}" class="chat-left" wx:if="{{item.orientation == 'l'}}">
          <image class="avatar-img" src="/res/image/chat_logo.png"></image>
          <text>{{item.text}}</text>
          <image class="avatar-img"></image>
        </view>
        <view id="roll{{index + 1}}" class="chat-right" wx:if="{{item.orientation == 'r'}}">
          <image class="avatar-img"></image>
          <text>{{item.text}}{{item.url}}</text>
          <image class="avatar-img" src="{{userLogoUrl}}"></image>
        </view>
      </block>
    </view>
  </scroll-view>
  <view class="showAuthor weui-footer weui-footer__text"><view id="rollend" class="olamicontent">語義解析技術由OLAMI提供</view><view class="author" bindtap="contactMe">聯繫作者</view></view>
  <form bindsubmit="sendChat">
    <view class="ask-input-word">
      <image class="text-video-img" src="/res/image/speak.png" hidden="{{keyboard}}" bindtap="switchInputType"></image>
      <image class="text-video-img" src="/res/image/keyboard.png" hidden="{{!keyboard}}" bindtap="switchInputType"></image>
      <input class="input-big" hidden="{{keyboard}}" focus="{{!keyboard}}" placeholder="" confirm-type="send" name="ask_word" type="text" bindconfirm="sendChat" bindinput="Typing" value="{{askWord}}" />
      <button hidden="{{!keyboard}}" bindtouchstart="touchdown" bindtouchend="touchup">按住 說話</button>
    </view>
  </form>
</view>
<image class="speaker" hidden="{{!isSpeaking}}" src="{{speakerUrl}}"></image>

使用keyboard來控制文本框和語音輸入的切換,最後的image是語音輸入時的圖標。

JS控制代碼

index.js(部分代碼)

......(省略部分代碼)
  // 切換語音輸入和文字輸入
  switchInputType:function(){
    this.setData({
      keyboard: !(this.data.keyboard),
    })
  },
  // 按鈕按下
  touchdown:function(){
    this.setData({
      isSpeaking : true,
    })
    that.speaking.call();
    console.log("[Console log]:Touch down!Start recording!");
    // 開始錄音
    wx.startRecord({
      'success':function(res){
        var tempFilePath = res.tempFilePath;
        that.data.filePath = tempFilePath;
        console.log("[Console log]:Record success!File path:" + tempFilePath);
        that.voiceToChar();
      },
      'fail':function(){
        console.log("[Console log]:Record failed!");
        wx.showModal({
          title: '錄音失敗',
          content:'換根手指再試一次!',
          showCancel: false,
          confirmText: '確定',
          confirmColor: '#09BB07',
        })
      },
    });
  },
  // 按鈕鬆開
  touchup:function(){
    wx.stopRecord();
    console.log("[Console log]:Touch up!Stop recording!");
    this.setData({
      isSpeaking: false,
      speakerUrl: '/res/image/speaker0.png',
    })
    clearInterval(that.speakerInterval);
  },
  // 語音轉文字
  voiceToChar:function(){
    var urls = app.globalData.slikToCharUrl;
    var voiceFilePath = that.data.filePath;
    if(voiceFilePath == null){
      console.log("[Console log]:File path do not exist!");
      wx.showModal({
        title: '錄音文件不存在',
        content: '我也不知道哪錯了,反正你就再試一次吧!',
        showCancel: false,
        confirmText: '確定',
        confirmColor: '#09BB07',
      })
      return;
    }
    var appkey = app.globalData.NLPAppkey;
    var appsecret = app.globalData.NLPAppSecret;
    var NLPCusid = app.globalData.NLPCusid;
    wx.showLoading({
      title: '語音識別中...',
    })
    // 語音識別
    wx.uploadFile({
      url: urls,
      filePath: voiceFilePath,
      name: 'file',
      formData: { "appKey": appkey, "appSecret": appsecret, "userId": NLPCusid },
      header: { 'content-type': 'multipart/form-data' },
      success: function (res) {
        wx.hideLoading();
        var data = JSON.parse(res.data);
        var seg = JSON.parse(data.result).seg;
        console.log("[Console log]:Voice to char:" + seg);
        if(seg == null || seg.length == 0){
          wx.showModal({
            title: '錄音識別失敗',
            content: "我什麼都沒聽到,你再說一遍!",
            showCancel: false,
            success: function (res) {
            }
          });
          return;
        }
        that.addChat(seg, 'r');
        console.log("[Console log]:Add user voice input to chat list");
        that.sendRequest(seg);
        return;
      },
      fail: function (res) {
        console.log("[Console log]:Voice upload failed:" + res.errMsg);
        wx.hideLoading();
        wx.showModal({
          title: '錄音識別失敗',
          content: "請你離WIFI近一點再試一次!",
          showCancel: false,
          success: function (res) {
          }
        });
      }
    });
  },
    // 聯繫作者
  contactMe:function(){
    if(that.data.contactFlag){
	  // 語義平臺自定義回覆,有問題可以聯繫博主
	  // 此處也可以調用addChat直接添加回復。
      that.sendRequest("");
    }
    else{
      wx.showModal({
        title: '提示',
        content: '你都點過了,還點幹嘛!!',
        showCancel:false,
      });
    }
    that.data.contactFlag = false;
  },
  // 麥克風幀動畫 
  speaking:function() {
    // 話筒幀動畫 
    var i = 0;
    that.speakerInterval = setInterval(function () {
      i++;
      i = i % 7;
      that.setData({
        speakerUrl: that.data.speakerUrlPrefix + i + that.data.speakerUrlSuffix,
      });
      console.log("[Console log]:Speaker image changing...");
    }, 300);
  }
......(省略部分代碼)

上面代碼略有更改,最近更新到了微信官方的語音插件,因爲邏輯都是一致的,只是語音識別調用的接口不一樣,所以博客中的代碼也就沒有更新。

如有任何問題可以聯繫博主。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章