小程序语音识别功能 wx.createInnerAudioContext

news2025/3/31 12:10:44

在这里插入图片描述

页面样式html+css
<view class="recorder_content">
  <view class="result_content">
    <view class="r_title">语音识别结果显示:</view>
    <view class="r_h_input">
      <text wx:if="{{resultDetails.result}}" class="{{resultDetails && resultDetails.status <=0 ?'r_h_input_red':''}}">{{ resultDetails.result || '识别失败'}}</text>
    </view>
  </view>
  <view class="button_content">
    <button bindtouchstart="touchstart" bindtouchend="touchend" disabled="{{!canRecord}}">
      {{longPress == '1' ? '按住说话' : '说话中...'}}
    </button>
    <button bindtap="playRecording" disabled="{{!canRecord || !tempFilePath}}">播放录音</button>
  </view>
</view>




.recorder_content{
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-direction: column;
  border-top: 1rpx solid #f7f7f7;
}
.result_content{
  width: 94%;
  margin: 0 auto;
}

.r_title{
  font-size: 26rpx;
  padding: 30rpx 0rpx;
}
.r_title_padding-b{
  padding-bottom: 0rpx;
}
.button_content{
  width: 100%;
  display: flex;
}
button{
  margin: 20rpx auto;
  font-size: 30rpx;
  width: 45%;
}

.r_h_input_red{
  color: red;
}
data 初始化数据
data: {
    canRecord: false,
    isRecording: false,
    tempFilePath: '',
    playbackUrl: '',
    recorderManager: '',
    recorderLang: {},
    longPress: 1, //1显示 按住说话 2显示 说话中,
    screenHeight: 0,
    innerAudioContext: null,
    resultInput: '',
    resultDetails: {},
    startTimeStamp: 0
  },
onLoad和app.js
  onLoad: function () {
    const innerAudioContext = wx.createInnerAudioContext({
      useWebAudioImplement: false // 是否使用 WebAudio 作为底层音频驱动,默认关闭。对于短音频、播放频繁的
    })
    setTimeout(() => {
      this.setData({
        innerAudioContext: innerAudioContext
      })
    })

    this.requestMicrophonePermission();
  },

	// app.js 文件内容
	"scope.record": {
      "desc": "用于录音"
    }

在这里插入图片描述

requestMicrophonePermission(获取权限)
requestMicrophonePermission: function () {
    wx.getSetting({
      success: (res) => {
        console.log('获取麦克风权限================', res)
        console.log(!res.authSetting['scope.record'])
        if (!res.authSetting['scope.record']) {
          wx.authorize({
            scope: 'scope.record',
            success: (res) => {
              console.log('用户已授权录音================', res);
              this.setData({
                canRecord: true
              });
            },
            fail: (err) => {
              console.error('用户拒绝授权录音================', err);
              wx.showModal({
                title: '需要授权录音',
                content: '您需要授权录音功能以正常使用本应用',
                showCancel: false,
                confirmText: '前往设置',
                success(res) {
                  if (res.confirm) {
                    wx.openSetting({
                      success(settingRes) {
                        if (settingRes.authSetting['scope.record']) {
                          console.log('用户已授权录音');
                          this.setData({
                            canRecord: true
                          });
                        }
                      }
                    });
                  }
                }
              });
            }
          });
        } else {
          this.setData({
            canRecord: true
          });
        }
      }
    });
  },
长按说话功能
touchstart(e) {
    console.log('开始---------------------');
    this.startRecording()
  },

  touchend(e) {
    console.log('结束-------------------');
    this.setData({
      longPress: 1,
      canRecord: true,
      isRecording: true
    })
    if (e.timeStamp - this.data.startTimeStamp < 1000) { //点击
      wx.showToast({
        title: '语音时间太短了',
        icon: 'none',
        mask: true, // 是否显示透明蒙层,防止触摸穿透
        duration: 1000
      })
    } else { //长按
      this.stopRecording()
    }
  },
 startRecording() {
    let that = this
    if (that.data.canRecord) {
      that.setData({
        isRecording: true,
        longPress: 2
      });
      that.data.recorderManager.start({
        timeout: 180,
        format: 'wav', // 音频格式
        success: (res) => {
          console.log('wx.startRecord================success', res)
        },
        fail: (err) => {
          console.log('wx.startRecord================fail', err)
        }
      });
    }
  },
stopRecording() {
    let that = this
    if (that.data.canRecord) {
      console.log('stop停止事件=>')
      this.data.recorderManager.onStop((res) => {
        this.setData({
          tempFilePath: res.tempFilePath,
          isRecording: true,
          canRecord: true,
          longPress: 1
        });
        // 停止录音后,上传文件
        this.uploadAudio(res.tempFilePath)
      });
      // 停止录音
      this.data.recorderManager.stop()
    }
  },
uploadAudio(filePath) {
    let that = this
    if (that.data.canRecord && that.data.tempFilePath) {
      console.log('wav文件=>', filePath)
      wx.showToast({
        title: "加载中",
        icon: 'loading',
        mask: true, // 是否显示透明蒙层,防止触摸穿透
        duration: 100000
      })
      wx.uploadFile({
        url: "服务器上传文件地址",
        filePath: filePath, // 文件路径
        name: 'audio', // 服务器接收的文件参数名
        header: {
          'Authorization': wx.getStorageSync('token_' + constant.version),
          'Content-Type': 'multipart/form-data'
        },
        formData: {
          'hotWords': that.data.resultInput,//可以去除,这个字段是后台需要的,根据自己的项目来
        },
        success(res) {
          wx.hideLoading()
          console.log('上传成功:', JSON.parse(res.data));
          that.setData({
            resultDetails: JSON.parse(res.data).data,//后台返回来的数据,用于页面展示
          })
          if(JSON.parse(res.data).data.status <=0){
            that.setData({
              tempFilePath: '',
            });
          }
        },
        fail(error) {
          setTimeout(() => {
            wx.hideLoading()
          }, 1000)
          console.error('上传失败:', error);
        }
      })
    }
  },
播放录音
playRecording() {
    let that = this
    if (this.data.canRecord && this.data.tempFilePath) {
      that.data.recorderManager.start()
      this.data.recorderManager.onStop()
      that.data.innerAudioContext.src = that.data.tempFilePath;
      console.log('播放url=>', that.data.innerAudioContext.src)
      console.log('播放事件=>', that.data.innerAudioContext)
      that.data.innerAudioContext.play();
      that.data.innerAudioContext.onPlay(() => {
        console.log('开始播放');
      });
      //return
      //if (!this.data.innerAudioContext) {
      //  this.setData({
      //    innerAudioContext: wx.createInnerAudioContext()
      //  })
      //}

      //this.data.innerAudioContext.src = this.data.tempFilePath;
      //console.log('播放=>', this.data.innerAudioContext)
      //this.data.innerAudioContext.play();

      // this.data.innerAudioContext.onPlay(() => {
      //   console.log('Playing audio...');
      // });
      // this.data.innerAudioContext.onError((err) => {
      //   console.error('Error playing audio:', err);
      // });
      // // 监听音频自然播放至结束的事件,播放结束,停止播放
      // this.data.innerAudioContext.onEnded(()=>{
      //   this.data.innerAudioContext.stop();
      // })

    }
  },

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2323692.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Web网页内嵌福昕OFD版式办公套件实现在线预览编辑PDF、OFD文档

PDF&#xff0c;即Portable Document Format&#xff0c;用于以一种独立于应用程序、硬件、操作系统的方式共享和查看文档&#xff1b;OFD&#xff0c;即Office Open Document Format for Document&#xff0c;是一种在政府公文和法律文件等领域广泛应用的电子文件格式&#xf…

ADZS-ICE-2000和AD-ICE2000仿真器在线升级固件

作者的话 近期发现有些兄弟的ICE-2000仿真器链接DSP报错&#xff0c;然后test第四步不通过&#xff0c;我就拿我的仿真器也试了一下&#xff0c;发现ADI悄咪咪的在线升级仿真器固件&#xff0c;有些兄弟不会操作&#xff0c;就会导致仿真器升级失败&#xff0c;连不上目标板&a…

第十一章:Python PIL库-图像处理

一、PIL库简介 PIL&#xff08;Python Imaging Library&#xff09;是一个功能强大的图像处理库&#xff0c;它提供了丰富的图像处理功能&#xff0c;包括图像的打开、处理和保存等操作。PIL支持多种图像文件格式&#xff0c;如JPEG、PNG、BMP等&#xff0c;并且可以完成对图像…

python项目整体文件和依赖打包

python项目整体文件和依赖打包 python项目整体文件和依赖打包 python项目整体文件和依赖打包 准备工作&#xff1a;扫描项目中必要的依赖包 pip install pipreqs pipreqs . 会有一些警告包&#xff0c;需要pip list进行版本修正,这里是三个包第一步&#xff1a;在虚拟环境中安…

logstash收集数据

防止ES的的I/O的压力过大&#xff0c;使用redis/kafka进行缓冲。 对redis的要求 Redis input plugin | Logstash Reference [8.17] | Elastic 一般企业要求的架构 我实现的架构 filebeat把数据传给logstash 配置好filebeat把收集到的数据输入到redis 然后执行命令&#xff0…

智能运维时代的网络拓扑管理:乐维监控的架构可视化实践

在数字化转型的浪潮中&#xff0c;企业IT基础设施正经历着前所未有的复杂化进程。当数以千计的网络设备、服务器、存储系统构成庞大网络体系时&#xff0c;如何实现全局可视化管理已成为企业数字化转型的关键命题。乐维监控网络拓扑系统作为新一代智能运维平台的核心组件&#…

CentOS 7 安装 EMQX (MQTT)

CentOS 7 安装 EMQX 通过 Yum 源安装 EMQX 支持通过 Yum 源安装&#xff0c;您可通过以下 Yum 命令从中自动下载和安装 EMQX。 通过以下命令配置 EMQX Yum 源&#xff1a; curl -s https://assets.emqx.com/scripts/install-emqx-rpm.sh | sudo bash安装以下依赖项&#xff…

人工智能:officeAI软件,如何调整AI对话界面的字体?

1、首先&#xff0c;随便打开一个excel&#xff08;使用wps&#xff09; 依次点击上方的【OfficeAI】—【右侧面板】 2、在弹出的面板中&#xff0c;输入&#xff1a;助手设置 &#xff0c; 然后按【回车】发送出去 3、之后会弹出界面&#xff0c;在【样式设定】中&#xff…

Qt之共享内存类QSharedMemory的使用及实现原理(全)

目录 1.简介 2.使用 3.实现原理 3.1.Windows内存映射 3.2.POSIX 共享内存 3.3.System V 共享内存 3.4.QSharedMemory的实现原理 4.总结 1.简介 QSharedMemory 是 Qt 框架提供的一个类&#xff0c;用于在不同进程或线程之间实现共享内存的管理。借助共享内存&#xff0c…

Problem A: 接口使用

1.题目问题 2.样例 3.代码实现 补充&#xff1a;注意空格 // 定义Vehicle接口 interface Vehicle {void start();void stop(); }// 实现Vehicle接口的Bike类 class Bike implements Vehicle {Overridepublic void start() {System.out.println("i am bike,i am running&…

用Python插入Excel表格到Word文档

在日常办公场景中&#xff0c;通过Python脚本自动化整合Excel数据与Word文档&#xff0c;能够实现表格的智能迁移&#xff0c;满足不同场景下数据呈现的专业性要求。直接提取表格内容插入Word适用于需要快速传递核心数据的场景&#xff0c;确保信息精准直达&#xff1b;完整复制…

合合信息TextIn大模型加速器 2.0来了:智能文档解析和图表解析能力全面升级

合合信息“TextIn大模型加速器 2.0”版本来了&#xff1a;文档解析和图表解析能力全面升级 背景 在日常工作中&#xff0c;我们常常遇到无法直接复制的文档内容或图片内容&#xff0c;这些内容通常需要进行识别和解析。一个典型的例子是&#xff0c;当我们需要将折线图转化为…

消息队列Message Queue

前面&#xff0c;我们在黑点点评中秒杀场景中&#xff0c;首次了解到消息队列MQ&#xff0c;它主要解决了秒杀场景中异步场景&#xff0c;提升了并发性&#xff0c;吞吐量。可是还是对消息队列又很多的疑惑&#xff1f; 消息队列是什么 消息队列是一种通信协议或中间件&#…

如何利用AI智能生成PPT提升工作效率

如何利用AI智能生成PPT提升工作效率&#xff1f;PPT制作曾经是每个人办公生活中的一大痛点。你有多久没有在制作PPT时感到焦头烂额&#xff0c;选模板、调整格式、插入图片&#xff0c;每一项都得花费大量的时间和精力&#xff0c;最后还未必能做出一份令人满意的效果。随着人工…

WIN11 企业版 部署Dify+Docker

Dify&#xff08;Do it for you&#xff09;是一款开源的大语言模型应用开发平台&#xff0c;旨在简化AI应用的创建、部署和管理过程&#xff0c;使开发者能够更快速、更轻松地构建和运营基于GPT等模型的AI应用。 Dify平台创建和运营一个AI chatbot应用&#xff0c;涉及到登录…

1.25-20GHz/500ns超快跳频!盛铂SWFA300国产捷变频频率综合器模块赋能雷达/5G/电子战高频精密控制 本振/频综模块

盛铂SWFA300捷变频频率综合器模块简述&#xff1a; 盛铂科技国产SWFA300捷变频频率综合器是一款在频率范围内任意两点频率的跳频时间在500nS以内的高速跳频源&#xff0c;其输出频率范围为1.25GHz至20GHz&#xff0c;频率的最小步进为10kHz。同时它拥有优秀的相位噪声特性&…

代理IP协议详解HTTP、HTTPS、SOCKS5分别适用于哪些场景

“代理IP协议在现代网络通信中扮演着至关重要的角色。它们通过提供中间层服务&#xff0c;帮助用户匿名访问网络、绕过地理限制、提高安全性和加速数据传输。HTTP、HTTPS和SOCKS5是三种最常见的代理IP协议&#xff0c;每种协议都有其特定的用途和适用场景。” HTTP代理及其适用…

AIGC工具平台-通用抠图换背景

本模块采用先进的大模型智能算法&#xff0c;精准识别并分割图像中的人物或物品主体&#xff0c;实现高效、精准、智能化的抠图处理。无论是人物肖像、产品展示&#xff0c;还是复杂场景&#xff0c;该工具均能准确提取主体&#xff0c;并自动适配至背景图像&#xff0c;实现自…

word快速创建虚拟文字

创建虚拟文字的作用&#xff1a;如培训新员工使用 Word&#xff0c;用虚拟文字演示如何设置段落格式。不需要你随便乱敲文字或者去复制一段文字过来。帮你节约了时间&#xff01; 两个函数的使用必须在段落的开头&#xff01;&#xff01;&#xff01; rand函数 在 Word 中…

win10下python脚本运行缺失ccache的问题处理

问题 python脚本运行时&#xff0c;会提醒参考 https://github.com/ccache/ccache/blob/master/doc/INSTALL.md 处理缺失ccache的问题。 下载编译 下载ccache主干版本&#xff0c; 例如 https://github.com/ccache/ccache/archive/refs/heads/master.zip 按照说明编译 mkd…