微信小程序录音,语音转文字怎么实现?

📢 博客主页:星辰丶xing-CSDN博客

🎥 本文由星辰丶xing原创,首发于CSDN

🏅 欢迎点赞 👍 收藏 ⭐留言 📝 如有错误敬请指正!

⭐ 以梦为马🦄,不负韶华❗

✨⭐🌟✨💫✨🌟⭐🌙

 

1,权限问题

    录音之前需要先获取权限,如果用户拒绝则无法录音。调用这段代码如果没有给权限会弹出一个授权提示,点击允许可以告知用户同意权限也可以不告知,点击拒绝会弹出如图2所示,点击确定会跳转到权限设置页面

    wx.authorize({  
      scope: 'scope.record',  
      success() {  
        console.log('用户同意授权录音权限');  
      },  
      fail() {  
        // 用户拒绝授权录音权限  
        console.log('用户拒绝授权录音权限');  
        wx.showModal({  
          title: '权限请求',  
          content: '录音功能需要您的授权,请前往设置页面打开授权',
          confirmColor:'#A083FF',
          showCancel: false,  
          success(modalRes) {  
            if (modalRes.confirm) {  
              wx.openSetting({  
                withSubscriptions: false,
                success(settingRes) {  
                  if (settingRes.authSetting['scope.record']) {  
                  } else {  
                    wx.showToast({  
                      title: '录音权限未打开',  
                      icon: 'none',
                      duration:2500
                    });  
                  }  
                },  
                fail(err) {  
                  console.error('打开设置页面失败', err);
                }  
              });  
            }  
          }  
        });  
      }  
    });

2,录音api

    创建录音实例,然后在需要用到的时候调用

<button bind:tap="startSound">开始录音</button>
<button bind:tap="endSound">停止录音</button>
const recordSound = wx.getRecorderManager()
*创建录音对象的这段代码可以放到录音开始的位置,也可以放到onLoad里面然后把对象赋值到data里方便调用,也可以在放到外面跟page({})平级或者page({})里面跟data平级(具体看个人的使用习惯)

// 开始录音
startSound(){
  recordSound.start({
    format:'mp3'
  })
},

// 结束录音
endSound(){
  recordSound.stop()
  const that = this
  // 录音结束的回调函数
  recordSound.onStop((res) => {
    const { tempFilePath } = res
    console.log('结束录音', tempFilePath)
    // 这里可以把录音放到data里面也可以直接掉接口把录音文件传递到服务器上
  })
},

3,语音转文字

    1,建议在后端去实现语音转文字,文字转语音,避免复杂的操作放到前端
    2,如果放到前端上面,实现方式(以腾讯云智能语音插件为例)

        插件文档地址腾讯云智能语音 | 小程序插件 | 微信公众平台

        a.在“小程序管理后台-设置-第三方服务-插件管理”中搜索"wx3e17776051baf153",并申请使用。(个人类目暂无法添加插件)

        b.注册腾讯云账号,开通相应权限,根据文档获取对应的秘钥,appid等

        c.小程序中使用--首先需要app.json里面写下面这段代码,配置好之后就可以在页面中使用

        d.小程序基础库版本 >= 2.10.0

        e.一些参数需要看文档,这里并没有过多的描述

        *使用之前一定要查看最新的文档避免遇到坑,浪费时间,也可以直接在腾讯云官网找客服解决问题

  "plugins": {
    "QCloudAIVoice": {
      "version": "2.3.1",
      "provider": "wx3e17776051baf153"
    }
  }

version版本号
provider:插件id
*json文件不支持注释,记得不要添加注释

4,语音合成

        1,合成语音的源文本,按UTF-8编码统一计算。中文最大支持150个汉字(全角标点符号算一个汉字);英文最大支持500个字母(半角标点符号算一个字母)。

        2,生成的音频有效期是1分钟,所以转完文字之后就如果不尽快播放就需要上传到服务器换取永久路径

        3,如果需要转的文字过长,就需要切割字符串然后逐条转成语音,逐条换取传递到服务器上换永久音频,需要的地方逐条播放(注意音频下载的话可能需要在小程序管理后台配置相关域名)

// 文字转语音
  txtToSpeak(content:any){
    let that = this
    let plugin = requirePlugin("QCloudAIVoice");
    plugin.setQCloudSecret(腾讯云id, 秘钥, 秘钥key,控制台是否打印(true/false)); //设置腾讯云账号信息,其中appid(非微信appid)是数字,secret是字符串,
    console.log(content,'contentcontent')
    const text = content
    plugin.textToSpeech({
          content: text, // 文本
          speed: -0.2, // 语速
          volume: 3, // 音量
          voiceType: 1001, // 音色 
          language: 1, // 中文
          projectId: 0,
          sampleRate: 16000,
  
          success: function(data:any) {
            console.log(data,'data')
          },
          fail: function(error:any){
              console.log(error,'error');
          }
      })
  },

5,实时语音识别

        1,语音转文字和录音不能同时使用

        2,语音转文字结束OnRecorderStop()这个回调函数里可以获取刚才语音转文字音频的临时路径

        3,具体使用

                a.进入页面先调用soundIdentify()方法初始化---this.soundIdentify()

                b.然后在转文字开始之前调用enableIt()这个方法---this.enableIt()

                c.转文字结束调用写上这段代码即可--this.data.speechRecognizerManager.stop()

        4,具体使用可以根据实际情况去调整

        5,电脑端不支持转文字,所以需要再手机上去体验

        6,如果一个页面有录音和转文字不是同时进行的,结束录音微信开发者工具可能会卡死,手机端目前没有问题

  // 语音转文字开始
  enableIt(){
    // 需要开始识别时调用此方法
    const params = {
          secretkey: '秘钥key',
          secretid:  '秘钥',
          appid: 腾讯云id,
          engine_model_type : '16k_zh', // 语音模型
    };
    this.data.speechRecognizerManager.start(params);
  },

  // 声音识别
  soundIdentify(){
      this.data.speechRecognizerManager = pluginHappiness.speechRecognizerManager();
      this.data.speechRecognizerManager.OnRecognitionStart = (res:any) => {
        console.log('开始识别', res);
      }
      // 一句话开始
      this.data.speechRecognizerManager.OnSentenceBegin = (res:any) => {
        console.log('一句话开始', res)
      }
      // 识别变化时
      this.data.speechRecognizerManager.OnRecognitionResultChange = (res:any) => {
        console.log('识别变化时', res)
      }
      // 一句话结束
      this.data.speechRecognizerManager.OnSentenceEnd = (res:any) => {
        let txt = res.result.voice_text_str
        console.log('一句话结束识别结果', txt)
        
      }
      // 识别结束
      this.data.speechRecognizerManager.OnRecognitionComplete = (res:any) => {
        console.log('识别结束', res);
      }
      // 识别错误
      this.data.speechRecognizerManager.OnError = (res:any) => {
        // code为6001时,国内站用户请检查是否使用境外代理,如果使用请关闭。境外调用需开通国际站服务
        console.log('识别失败', res);
      }
      // 录音结束(最长10分钟)时回调
      this.data.speechRecognizerManager.OnRecorderStop = (res:any) => {
        console.log('录音结束', res);
        console.log('识别结束', res.tempFilePath);
      }
  },

6,录音文件转文字

audioFilesToText(url:any){
    let that = this
    let plugin = requirePlugin("QCloudAIVoice");
    plugin.setQCloudSecret(腾讯云id, 秘钥, 秘钥key,控制台是否打印(true/false)); //设置腾讯云账号信息,其中appid(非微信appid)是数字,secret是字符串, 
    plugin.sentenceRecognition({
      engSerViceType: '16k_zh',  //引擎类型
      sourceType: 0,  //0:语音 URL
      voiceFormat: 'mp3',  // 音频格式
      url: url, // 音频路径
      data: '',
      dataLen: 0,
      projectId: 0,
      success(data:any) {
          console.log('识别成功', data.result)
      },
      fail(err:any) {
          console.log('识别失败', err)
      }
})
  },

  • 31
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现微信小程序中的语音文字功能,可以按照以下步骤进行设置: 1. 首先,需要在小程序的json配置文件中添加record权限,用于语音输入: ``` "permission": { "record": { "desc": "用于语音输入" } } ``` 2. 然后,在小程序的wxml文件中添加录音组件,用于录制语音: ``` <recorder id="recorder" duration="60000" event-bindend="onRecordEnd" event-binderror="onRecordError"></recorder> ``` 3. 接下来,在小程序的js文件中,使用微信的语音识别API实现语音文字的功能。你可以使用微信提供的插件“微信同声传译”来帮助实现。以下是一个示例代码: ``` const plugin = requirePlugin("WechatSI") const manager = plugin.getRecordRecognitionManager() // 监听录音结束事件 manager.onStop = function(res) { const text = res.result // 这里可以对换后的文字进行处理或展示 } // 监听录音错误事件 manager.onError = function(res) { // 处理录音错误 } // 开始录音 manager.start({ lang: "zh_CN" // 设置语言为中文 }) ``` 通过以上步骤,你可以在微信小程序实现语音文字的功能。请注意,为了使用语音识别API,你需要在小程序管理后台申请并获取相应的API权限。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [微信小程序实现文字语音](https://download.csdn.net/download/weixin_38616139/14878012)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [微信小程序实现语音识别文字功能及遇到的坑](https://download.csdn.net/download/weixin_38665804/13616802)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [微信小程序语音文字demo](https://blog.csdn.net/takeingloop/article/details/130810514)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值