【前端 vue 或者麦克风,智能语音识别和播放功能】

news/2025/3/29 8:26:56/

前端 vue 或者麦克风,智能语音识别和播放功能

1. 终端安装
npm install recordrtc
2.引入
import RecordRTC from 'recordrtc'
3.html(根据自己业务更改)
<div class="Page"><el-form ref="mainFormRef" class="mainForm" :model="main_form" label-width="100px" label-position="top"><el-form-item :label="'热词设置:\n(一行一个关键字,空格隔开权重,如将1号屏和3号屏调换 20)'"><el-input type="textarea" v-model="main_form.hotWords" placeholder="请输入热词":autosize="{ minRows: 5, maxRows: 15 }"></el-input></el-form-item><el-form-item label="语音识别结果显示:"><div :class="resultDetails && resultDetails.status <= 0 ? 'result_content r_h_input_red' : 'result_content'">{{main_form.result }}</div></el-form-item><el-form-item label="声纹采集:" prop="file"><div class="voiceGather_btn"><el-select :disabled="voiceStatus" style="width: 100%" v-model="main_form.chooseMicDeviceId"placeholder="请选择麦克风"><el-option v-for="item in Mic" :key="item.deviceId" :label="item.label" :value="item.deviceId"></el-option></el-select><div class="voiceGather" v-if="main_form.chooseMicDeviceId != ''"><el-button style="margin-left: 20px" @click="voiceInput" :loading="startLoading">{{ voiceStatus ? "取消录音" :"开始录音" }}</el-button></div></div><div class="voiceGather_btn"><audio controls v-if="recordedBlob" :src="recordedBlob"></audio></div></el-form-item></el-form></div>
4.data初始化数据
data() {return {recorder: '',voiceStatus: false, // 是否正在录音main_form: {chooseMicDeviceId: '', // 选择的麦克风idhotWords: '', // 热词result: '', // 语音识别结果},Mic: [], // 可选择的麦克风RMSList: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0,],audioURL: null,file: null,resultDetails: {},//语音识别结果startLoading: false,recordedBlob: null, // Blob对象存储录制内容};},
5.mounted获取getMic
mounted() {this.getMic()
}
6.methods中开始录音和结束之后上传到后台服务器
methods() {getMic() {let that = this;if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {// 弹框获取麦克风navigator.mediaDevices.getUserMedia({ audio: true }).then((stream) => {navigator.mediaDevices.enumerateDevices().then(function (devices) {devices.forEach(function (device) {if (device.kind === 'audioinput') { // 麦克风if (device.deviceId != 'default' && device.deviceId != 'communications') {that.Mic.push(device)}}that.main_form.chooseMicDeviceId = that.Mic[0] ? that.Mic[0].deviceId : ''});})stream.getTracks().forEach(track => track.stop());})}},// 语音输入点击按钮事件voiceInput() {// 正在语音输入if (this.voiceStatus) {this.stopRecord() // 停止输入} else { // 开启语音输入this.resultDetails ={}this.main_form.result = ''this.recordedBlob = nullthis.startRecord()}},// 开始录音startRecord() {console.log('startRecord:鼠标摁下------------------------------')var that = thisthis.voiceStatus = true// mediaDevices可提供对相机和麦克风等媒体输入设备的连接访问window.navigator.mediaDevices.getUserMedia({ audio: { deviceId: this.main_form.chooseMicDeviceId } }).then((stream) => {this.stream = stream;this.getVoice()this.recorder = RecordRTC(stream, {type: 'audio',// 音频 或者videomimeType: 'audio/wav',recorderType: RecordRTC.StereoAudioRecorder,desiredSampRate: 16000,numberOfAudioChannels: 1, // 单声道timeSlice: 1000,// bufferSize: 4096, // 缓存大小ondataavailable: this.sendData,});this.recorder.startRecording();}).catch(function (err) {alert('当前浏览器不支持开启麦克风!');that.voiceStatus = false});},// 获取到文件流(没用到这个函数内容,可以忽略)sendData(blob) {return//var BB = new Blob([blob], { 'type': 'audio/wav; codecs=opus' })// var audioURL = window.URL.createObjectURL(BB)// 播放// const audio = document.createElement('audio')// audio.controls = true // 音频是否显示控件// audio.src = audioURL// audio.play()// 下载// let a = document.createElement("a");// a.href = audioURL;// a.download = '测试';// a.click();// // 释放这个临时的对象url// window.URL.revokeObjectURL(audioURL);// let file = new window.File([BB], '测试.wav')// this.file = file// console.log('录音已停止,文件已保存---------------------', this.file);},// 结束录音stopRecord() {console.log('stopRecord:鼠标放开------------------------------')if (this.recorder != null) {this.startLoading = truelet recorder = this.recorder// 处理停止事件recorder.stopRecording(() => {const blob = this.recorder.getBlob(); // 获取Blob对象this.recordedBlob = URL.createObjectURL(blob);// 创建URL对象,用于<audio>标签播放// console.log('录音已停止,文件已保存---------------------', this.recordedBlob);var BB = new Blob([blob], { 'type': 'audio/wav; codecs=opus' })let file = new window.File([BB], '测试.wav')this.file = fileconsole.log('获取到文件流上传到后台---------------------', this.file);this.uploadSubmit();});let stream = this.stream;clearInterval(this.timer1);stream.getAudioTracks().forEach(track => track.stop());}},// 上传到后台服务器uploadSubmit() {uploadAudio(this.file, this.main_form.hotWords).then(res => {this.resultDetails = res.data.data || {}this.main_form.result = res.data.data.result || ''this.voiceStatus = falsethis.startLoading = false}).catch(err => {this.voiceStatus = falsethis.startLoading = false})},// 获取音量值大小getVoice() {const audioContext = new (window.AudioContext || window.webkitAudioContext)()// 将麦克风的声音输入这个对象const mediaStreamSource = audioContext.createMediaStreamSource(this.stream)// 创建分析节点const analyserNode = audioContext.createAnalyser()// 连接节点mediaStreamSource.connect(analyserNode)// 可以实时听到麦克风采集的声音// analyserNode.connect(audioContext.destination)// 获取音量数据const dataArray = new Uint8Array(analyserNode.frequencyBinCount);function getVolume() {analyserNode.getByteFrequencyData(dataArray);let sum = 0;for (let i = 0; i < dataArray.length; i++) {sum += dataArray[i];}// 计算平均音量const averageVolume = sum / dataArray.length;return averageVolume;}// 每隔一段时间获取一次音量this.timer1 = setInterval(() => {const volume = getVolume();console.log('音量:', Math.round(volume));// this.RMSList.value.unshift(Math.round(volume));// this.RMSList.value.pop();// 在这里可以根据需要进行相应的处理}, 1000);},
}

http://www.ppmy.cn/news/1582819.html

相关文章

CE设备(Customer Edge device,用户边缘设备)

CE设备&#xff08;Customer Edge device&#xff0c;用户边缘设备&#xff09;是指在服务提供商网络与客户网络之间的边界设备&#xff0c;它属于客户所有并管理。CE设备的主要功能是连接客户网络到服务提供商的网络&#xff0c;如互联网服务提供商&#xff08;ISP&#xff09…

vue3怎么定义计算属性

在 Vue 3 中&#xff0c;你可以使用 computed 函数来定义计算属性。computed 函数来自 Vue 3 的组合式 API&#xff0c;它有两种使用方式&#xff1a;只读计算属性和可写计算属性&#xff0c;下面分别介绍这两种方式。 只读计算属性 只读计算属性是最常见的用法&#xff0c;它…

SQL Server 数据库引擎服务实例功能出错的解析与解决方案

SQL Server 是 Microsoft 开发的一款关系型数据库管理系统。虽然它的功能强大&#xff0c;但在实际使用过程中&#xff0c;用户可能会遇到“SQL Server 数据库引擎服务实例功能出错”的问题。本文将对此进行剖析&#xff0c;并提供相应的解决方案。 一、错误的常见原因 服务未启…

​ 《Keras 3 :开发人员指南 / 迁移学习和微调​》

​《Keras 3 &#xff1a;开发人员指南 / 迁移学习和微调​》 迁移学习和微调 作者&#xff1a;fchollet 创建日期&#xff1a;2020/04/15 最后修改时间&#xff1a;2023/06/25 描述&#xff1a;Keras迁移学习和微调的完整指南。 在 Colab 中查看 GitHub 源 设置 import numpy…

Go语言中context.Context的

context.Context 是 Go 语言中用于管理请求生命周期、传递请求范围数据以及控制超时和取消的核心接口。它在并发编程、网络请求、微服务等场景中非常重要。以下是对 context.Context 的详细解释&#xff1a; 1. context.Context 的作用 context.Context 的主要作用包括&#x…

微服务中的服务发现

微服务中的服务发现 什么是服务发现 服务发现是微服务架构中的关键机制&#xff0c;用于确定各个微服务的地址。例如&#xff0c;在一个 API Server 服务中&#xff0c;我们可能需要调用 User 服务来处理用户注册、登录和信息查询&#xff0c;也可能需要 Product 服务来获取商…

nt!KeWaitForMultipleObjects函数分析之一个例子ExpWorkerThreadBalanceManager

第一部分&#xff1a; 1: kd> dt kTHREAD 8999c8a0 0x02c State : 0x2 0x054 WaitBlockList : 0x8999c940 _KWAIT_BLOCK 第一个_KWAIT_BLOCK&#xff1a; 1: kd> dx -id 0,0,899a2278 -r1 ((CSRSRV!_KWAIT_BLOCK *)0x8999c940) ((CSRSRV!_KWAIT_BLO…

算法训练营第二十二天 | 回溯算法(四)

文章目录 前言一、Leetcode 491.递增子序列二、Leetcode 46.全排列三、Leetcode 47.全排列Ⅱ 前言 提示&#xff1a;这里可以添加本文要记录的大概内容&#xff1a; 例如&#xff1a;随着人工智能的不断发展&#xff0c;机器学习这门技术也越来越重要&#xff0c;很多人都开启…