前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >微信小程序对接云开发录音文件识别nodejs sdk

微信小程序对接云开发录音文件识别nodejs sdk

原创
作者头像
张世强
修改2020-07-24 12:16:18
2.6K0
修改2020-07-24 12:16:18
举报
文章被收录于专栏:zhangzhang

1.项目需求

将微信好友发送过来的录音文件在线识别为文字

2.项目准备

  • 微信小程序开发者账号

前往注册

  • 微信开发者工具

前往下载

  • 腾讯云录音文件识别之Node.js SDK

参考文档

3.项目演示

云函数部分

新建项目

  • 创建一个名为cloud的云函数根目录

配置cloud目录为云函数根目录

代码语言:javascript
复制
	"cloudfunctionRoot": "cloud/",

点击编译发现cloud新增了一个云图标

创建用于存放录音文件识别API的云函数voiceRecognize

添加"request"依赖包

代码语言:javascript
复制
"request": "^2.85.0"

执行如下命令安装依赖包

代码语言:javascript
复制
npm install

下载录音文件识别Node.js SDK到本地并解压

拷贝"tencentcloud"目录到云函数"voiceRecognize"的包管理目录"node_modules"下

我们可以点击微信开发者工具中的项目详情中的本地目录快速进入到项目的磁盘文件系统中

拷贝后进入工具刷新资源管理器

配置tencentcloud模块

代码语言:javascript
复制
tencentcloud:require("../tencentcloud")

完善云函数入口文件index.js中的Demo

代码语言:javascript
复制
// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
// 云函数入口函数
exports.main = async (event, context) => {
  //将require中路径替换为项目中SDK的真实路径
//将require中路径替换为项目中SDK的真实路径
const tencentcloud = require("tencentcloud");
module.exports = tencentcloud;


// 导入对应产品模块的client models以及需要用到的模块
const AsrClient = tencentcloud.asr.v20190614.Client;
const models = tencentcloud.asr.v20190614.Models;
const Credential = tencentcloud.common.Credential;
const ClientProfile = tencentcloud.common.ClientProfile;
const HttpProfile = tencentcloud.common.HttpProfile;

// Your SecretId、Your SecretKey 需要替换成客户自己的账号信息
let cred = new Credential("", "");// 你的腾讯云账号的API秘钥

let httpProfile = new HttpProfile();
httpProfile.reqMethod = "POST";
httpProfile.reqTimeout = 30;
httpProfile.endpoint = "asr.tencentcloudapi.com";

let clientProfile = new ClientProfile();
clientProfile.httpProfile = httpProfile;
clientProfile.signMethod = "TC3-HMAC-SHA256";
// 实例化要请求产品(asr)的client对象
let client = new AsrClient(cred, "", clientProfile);

//通过语音URL方式调用 

// 实例化一个请求对象
let req = new models.CreateRecTaskRequest();
// 设置接口需要的参数,参考 接入须知 中 [请求接口说明]
req.EngineModelType = '16k_0';
req.ChannelNum = 1;
req.ResTextFormat = 0;
req.SourceType = 0;
// req.Url = 'https://tencent-1256311141.cos.ap-chengdu.myqcloud.com/ai/mp1131.mp3';
req.Url=event.url;
// 通过client对象调用想要访问的接口,需要传入请求对象以及响应回调函数
return new Promise((resolve, reject) => {   // 通过Promise容器来接收异步API的回调,然后通过当前脚本返回给客户端
  client.CreateRecTask(req, function(errMsg, response) {
    if (errMsg) {
      resolve({ "Result": errMsg })
    }

    resolve({ "Result": response})
});
})
}

再创建一个名为getdata的云函数

仍然是进到磁盘文件系统

拷贝云函数voiceRecognize的目录内容到getdata云函数目录下(重复的直接覆盖)

替换云函数getdata的index入口文件内容

代码语言:javascript
复制
// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
// 云函数入口函数
exports.main = async (event, context) => {
  //将require中路径替换为项目中SDK的真实路径
//将require中路径替换为项目中SDK的真实路径
const tencentcloud = require("tencentcloud");
module.exports = tencentcloud;


// 导入对应产品模块的client models以及需要用到的模块
const AsrClient = tencentcloud.asr.v20190614.Client;
const models = tencentcloud.asr.v20190614.Models;
const Credential = tencentcloud.common.Credential;
const ClientProfile = tencentcloud.common.ClientProfile;
const HttpProfile = tencentcloud.common.HttpProfile;

// Your SecretId、Your SecretKey 需要替换成客户自己的账号信息
let cred = new Credential("", "");  // 你的腾讯云账号的API秘钥

let httpProfile = new HttpProfile();
httpProfile.reqMethod = "POST";
httpProfile.reqTimeout = 30;
httpProfile.endpoint = "asr.tencentcloudapi.com";

let clientProfile = new ClientProfile();
clientProfile.httpProfile = httpProfile;
clientProfile.signMethod = "TC3-HMAC-SHA256";
// 实例化要请求产品(asr)的client对象
let client = new AsrClient(cred, "", clientProfile);

//通过语音URL方式调用 
//调用录音识别结果查询接口
let reqResult = new models.DescribeTaskStatusRequest();
//reqResult.TaskId 为创建识别任务时 response 里的 TaskId 字段
//示例 TaskId 不可用,需要客户替换成可用 TaskId
reqResult.TaskId = event.TaskId;
return new Promise((resolve, reject) => {   // 通过Promise容器来接收异步API的回调,然后通过当前脚本返回给客户端
  client.DescribeTaskStatus(reqResult, function(errMsg, response) {
    if (errMsg) {
      resolve({ "Result": errMsg })
    }

    resolve({ "Result": response})
});
})
}

接下来上传两个云函数的所有内容到云端,右键点击云函数目录,分别对两个云函做如下操作

小程序部分

注册录音文件识别页面

代码语言:javascript
复制
"pages/recordfile/recordfile",

点击编译生成页面目录

完善xml页面Demo

代码语言:javascript
复制
<!--pages/recordfile/recordfile.wxml-->
<button type="primary" bindtap="uploadRecord">识别微信会话音频文件</button>
 <textarea value="{{TaskId}}" auto-height placeholder="这里会展示识别任务ID" placeholder-style="color:green;" />
 <button type="primary" bindtap="getResult">查询识别结果</button>
 <textarea value="{{data}}" auto-height placeholder="这里会展示识别结果" placeholder-style="color:red;" />
 <view wx:if="{{ status=='doing'}}">请稍等,正在识别中...</view>

完善js页面Demo

代码语言:javascript
复制
Page({
  /**定义一些逻辑数据 */
   data:{
     tempVoicePaths:"", //录音文件的本地临时文件
     fileID:"", //录音文件上传至云存储中后生成的文件ID
     tempUrl:"",//云存储提供的录音文件临时url
   },
 
  /**将录音文件的Url上传至服务端进行识别,获取到识别任务的ID */
   uploadRecord:function(e){
     var that=this;
     wx.chooseMessageFile({
       count: 10,
       type: 'all',
       success (res) {
         // tempFilePath可以作为img标签的src属性显示图片
         console.log("会话中选择的音频文件在微信客户端的临时路径"+res.tempFiles[0].path)
         that.setData({
           tempVoicePaths: res.tempFiles[0].path
         })
 
       wx.cloud.init()
       var cloudPath = Date.parse(new Date())/1000;
       cloudPath = cloudPath / 1000;
       cloudPath=cloudPath.toString();
       wx.cloud.uploadFile({
       cloudPath: cloudPath, // 上传至云端的路径
       filePath: that.data.tempVoicePaths, // 小程序临时文件路径
       success: res => {
         // 返回文件 ID
         console.log("将音频文件上传到云存储后,返回的文件ID是"+res.fileID)
         wx.cloud.init()
         wx.cloud.getTempFileURL({
           fileList: [res.fileID],
           success: res => {
            console.log("通过文件ID从云存储获取到的音频文件的临时url是:")
             console.log(res.fileList[0].tempFileURL)
             that.setData({
              tempUrl: res.fileList[0].tempFileURL
            })
             wx.cloud.callFunction({
               // 云函数名称
               name: 'voiceRecognize',
               // 传给云函数的参数
               data: {
                 url:that.data.tempUrl
               },
               success: function(res) {
                 console.log("上传的临时url"+that.data.tempUrl)
                 console.log(res)
                 console.log(res.result.Result.Data.TaskId)
                 wx.setStorage({
                   key:"TaskId",
                   data: res.result.Result.Data.TaskId
                 })
                 that.setData({
                   TaskId: "任务ID是:"+res.result.Result.Data.TaskId
                 })
               },
               fail: console.error
             })
           },
           fail: err => {
             // handle error
           }
         })
       },
       fail: console.error
     })
       }
     })
     
   },
   getResult:function(){
     var that=this
     wx.cloud.init()
     wx.cloud.callFunction({
       // 云函数名称
       name: 'getdata',
       // 传给云函数的参数
       data: {
         TaskId:wx.getStorageSync('TaskId')
       },
       success: function(res) {
         console.log(res)
         that.setData({
           data: res.result.Result.Data.Result,
           status:res.result.Result.Data.StatusStr
         })
       },
       fail: console.error
     })
 
   }
 })

测试

点击"预览"出现二维码,微信扫描二维码后选择微信会话中的一个mp3文件

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1.项目需求
  • 2.项目准备
  • 3.项目演示
    • 云函数部分
    • 小程序部分
    • 测试
    相关产品与服务
    云函数
    云函数(Serverless Cloud Function,SCF)是腾讯云为企业和开发者们提供的无服务器执行环境,帮助您在无需购买和管理服务器的情况下运行代码。您只需使用平台支持的语言编写核心代码并设置代码运行的条件,即可在腾讯云基础设施上弹性、安全地运行代码。云函数是实时文件处理和数据处理等场景下理想的计算平台。
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档