news 2026/3/6 0:23:03

实现Unity录音、百度云语音转文字

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
实现Unity录音、百度云语音转文字
在unity中录制声音,调用百度云-语音转文字标准版接口,获取转换后的文字内容 调用示例: BtnStartVoice.onClick.AddListener(()=>{//开始录音MicrophoneRecorderManager.Instance.StartRecording();});BtnEndVoice.onClick.AddListener(()=>{//结束录音MicrophoneRecorderManager.Instance.StopRecording(strContent=>{InputChat.text=strContent;});});

百度云-语音识别API及代码示例地址:
百度智能云-语音识别

以下为相关代码实现:

usingSystem;usingSystem.Collections;usingSystem.Collections.Generic;usingQFramework;usingUnityEngine;//麦克风录音管理器publicclassMicrophoneRecorderManager:MonoSingleton<MicrophoneRecorderManager>{publicoverridevoidOnSingletonInit(){Init();base.OnSingletonInit();}privateAudioClipcurrentRecording;privatestring_selectedDevice;privateAudioSource_audioSource;//播放录音,用于测试是否录音成功privateintsampleRate=16000;//固定采样率privateintmaxRecordingTime=60;// 最大录音时长(秒)//是否正在录音privateboolisRecording;voidInit(){// 获取所有麦克风设备string[]devices=Microphone.devices;if(devices.Length==0){Debug.LogError("没有检测到麦克风设备");return;}devices.ForEach(x=>Debug.Log($"devices:{x}"));// 选择第一个可用设备_selectedDevice=devices[0];Debug.Log($"已选择麦克风设备:{_selectedDevice}");/* // 添加并配置AudioSource组件,用于测试是否录音成功 _audioSource = gameObject.AddComponent<AudioSource>(); _audioSource.loop = false; // 不循环播放 */}// 开始录音publicvoidStartRecording(){if(string.IsNullOrEmpty(_selectedDevice)){Debug.LogError("没有可用的麦克风设备");return;}//如果正在录音if(Microphone.IsRecording(_selectedDevice)){return;}/* // 停止之前可能正在播放的音频,用于测试录音时使用 if (_audioSource.isPlaying) { _audioSource.Stop(); } */// 开始录音,采样率44100Hz,时长10秒currentRecording=Microphone.Start(_selectedDevice,false,maxRecordingTime,sampleRate);isRecording=true;Debug.Log("录音已开始");}// 停止录音publicvoidStopRecording(Action<string>callBack){if(!isRecording)return;// 获取当前录音位置intrecordingLength=Microphone.GetPosition(_selectedDevice);// 停止录音Microphone.End(_selectedDevice);isRecording=false;Debug.Log("录音已停止");// 创建新的AudioClip,只包含实际录音的部分if(recordingLength>0){AudioCliprecordedClip=AudioClip.Create("Recording",recordingLength,currentRecording.channels,sampleRate,false);// 获取录音数据float[]samples=newfloat[recordingLength*currentRecording.channels];currentRecording.GetData(samples,0);recordedClip.SetData(samples,0);// 保存并播放currentRecording=recordedClip;LogUtilits.LogWarning($"采样率:{currentRecording.frequency}");byte[]audioData=WavUtility.ConvertAudioClipToPCM(currentRecording);StartCoroutine(BDSmartManager.Instance.SpeechToText(audioData,callBack,null));//PlayRecording();Debug.Log("播放录音中...");;}else{Debug.LogError("录音失败或时长太短");;}}/// <summary>/// 播放录音,用于测试是否正确录音成功/// </summary>privatevoidPlayRecording(){if(currentRecording==null){Debug.LogWarning("没有可播放的录音");return;}// 设置音频源并播放_audioSource.clip=currentRecording;_audioSource.Play();}// 在组件被销毁时停止录音privatevoidOnDestroy(){if(Microphone.IsRecording(_selectedDevice)){Microphone.End(_selectedDevice);}if(_audioSource!=null&&_audioSource.isPlaying){_audioSource.Stop();}}}
usingNewtonsoft.Json;usingQFramework;usingSystem;usingSystem.Collections;usingSystem.Collections.Generic;usingSystem.Net.NetworkInformation;usingUnity.Burst.Intrinsics;usingUnityEngine;usingUnityEngine.Networking;//百度智能语音publicclassBDSmartManager:MonoSingleton<BDSmartManager>{privatestringaccessToken;//http通信的请求tokenprivateboolisTokenValid=false;//是否有效token#region获取token/// <summary>/// 使用 AK, SK 生成鉴权签名(Access Token)/// </summary>/// <returns>鉴权签名信息(Access Token)</returns>publicIEnumeratorGetAccessToken(){stringapiKey=BDInterfaceDefine.ApiKey;stringsecretKey=BDInterfaceDefine.SecretKey;stringurl=$"https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={apiKey}&client_secret={secretKey}";usingUnityWebRequestrequest=UnityWebRequest.Post(url,newWWWForm());request.timeout=-1;yieldreturnrequest.SendWebRequest();if(request.result==UnityWebRequest.Result.Success){stringresponseContent=request.downloadHandler.text;Debug.Log($"responseContent:{responseContent}");BaiduTokenResponseresult=JsonConvert.DeserializeObject<BaiduTokenResponse>(responseContent);accessToken=result.access_token;isTokenValid=true;// 这里可以返回token或者执行其他操作Debug.Log($"获取Token成功:{accessToken}");}else{Debug.LogError($"获取Token失败:{request.error}");}}#endregion#region语音识别-标准版/// <summary>/// 语音识别-标准版/// </summary>publicIEnumeratorSpeechToText(byte[]audioData,Action<string>onSuccess,Action<string>onError){if(!isTokenValid){Debug.LogWarning("Token无效,正在重新获取...");yieldreturnStartCoroutine(GetAccessToken());}// 准备请求数据varrequestData=newDictionary<string,object>{{"format","pcm"},//语音文件的格式,pcm/wav/amr/m4a。不区分大小写。推荐pcm文件{"rate",16000},//采样率,16000、8000,固定值{"channel",1},//声道数,仅支持单声道,请填写固定值 1{"token",accessToken},{"cuid",SystemInfo.deviceUniqueIdentifier},//用户唯一标识,用来区分用户,计算UV值。建议填写能区分用户的机器 MAC 地址或 IMEI 码,长度为60字符以内。{"len",audioData.Length},//本地语音文件的的字节数,单位字节{"speech",Convert.ToBase64String(audioData)}//本地语音文件的二进制语音数据 ,需要进行base64 编码。与len参数连一起使用。};stringjsonData=JsonConvert.SerializeObject(requestData);LogUtilits.LogMsg($"requestData:{jsonData}");byte[]postData=System.Text.Encoding.UTF8.GetBytes(jsonData);// 发送请求//string url = "https://vop.baidu.com/server_api";stringurl=BDInterfaceDefine.SpeechRecognition_Standard;UnityWebRequestrequest=UnityWebRequest.Post(url,newWWWForm());request.timeout=-1;request.SetRequestHeader("Content-Type","application/json");request.SetRequestHeader("Accept","application/json");//request.uploadHandler=newUploadHandlerRaw(postData);request.downloadHandler=newDownloadHandlerBuffer();yieldreturnrequest.SendWebRequest();if(request.result==UnityWebRequest.Result.Success){LogUtilits.LogMsg($"识别结果:{request.downloadHandler.text}");varresponse=JsonConvert.DeserializeObject<BaiduASRResponse>(request.downloadHandler.text);if(response.err_no==0&&response.result!=null&&response.result.Length>0){stringrecognizedText=response.result[0];onSuccess?.Invoke(recognizedText);Debug.Log($"识别成功:{recognizedText}");}else{stringerrorMsg=$"err_msg识别失败:{response.err_msg}(err_no错误码:{response.err_no})";onError?.Invoke(errorMsg);Debug.LogError(errorMsg);}}else{stringerrorMsg=$"网络请求失败:{request.error}";onError?.Invoke(errorMsg);Debug.LogError(errorMsg);}}#endregion}
//百度云接口定义publicstaticclassBDInterfaceDefine{publicconststringApiKey="替换为自己的ApiKey";publicconststringSecretKey="替换为自己的SecretKey";/// <summary>/// 短语音识别标准版/// </summary>publicconststringSpeechRecognition_Standard="https://vop.baidu.com/server_api";}// 百度智能云API响应数据结构[System.Serializable]publicclassBaiduASRResponse{publicstringcorpus_no;publicstringerr_msg;publicinterr_no;publicstring[]result;publicstringsn;}// Token获取响应[System.Serializable]publicclassBaiduTokenResponse{publicstringrefresh_token;publicintexpires_in;publicstringsession_key;publicstringaccess_token;publicstringscope;publicstringsession_secret;}
usingSystem;usingUnityEngine;//录音数据转换工具类publicstaticclassRecordAudioUtility{publicstaticbyte[]ConvertAudioClipToPCM(AudioClipclip){// 获取音频数据float[]samples=newfloat[clip.samples*clip.channels];clip.GetData(samples,0);// 转换为16位PCMbyte[]pcmData=ConvertFloatToPCM16(samples);// 如果是立体声,转换为单声道if(clip.channels==2){pcmData=ConvertStereoToMono(pcmData);}returnpcmData;}privatestaticbyte[]ConvertStereoToMono(byte[]stereoData){// 16位PCM,每个采样2字节intsampleCount=stereoData.Length/4;// 每个通道的采样数byte[]monoData=newbyte[sampleCount*2];for(inti=0;i<sampleCount;i++){intstereoPos=i*4;intmonoPos=i*2;// 获取左右声道采样shortleft=BitConverter.ToInt16(stereoData,stereoPos);shortright=BitConverter.ToInt16(stereoData,stereoPos+2);// 计算平均值shortmono=(short)((left+right)/2);// 写入单声道数据byte[]monoBytes=BitConverter.GetBytes(mono);monoData[monoPos]=monoBytes[0];monoData[monoPos+1]=monoBytes[1];}returnmonoData;}privatestaticbyte[]ConvertFloatToPCM16(float[]samples){byte[]pcmBytes=newbyte[samples.Length*2];intposition=0;for(inti=0;i<samples.Length;i++){// 限制在[-1, 1]范围内floatsample=Mathf.Clamp(samples[i],-1f,1f);// 转换为16位整型shortintSample=(short)(sample*32767f);// 小端字节序pcmBytes[position++]=(byte)(intSample&0xFF);pcmBytes[position++]=(byte)((intSample>>8)&0xFF);}returnpcmBytes;}}
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/3/4 23:06:43

IP地址与端口号

IP地址及编址方式 IP地址基础概念 IP地址的本质 定义&#xff1a;用于唯一标识互联网上设备的逻辑地址结构&#xff1a;采用两级结构&#xff08;网络号 主机号&#xff09;唯一性&#xff1a;在整个互联网范围内是唯一的表示方法&#xff1a;点分十进制记法&#xff08;如…

作者头像 李华
网站建设 2026/3/5 15:07:36

(新卷,200分)- 任务调度(Java JS Python)

(新卷,200分)- 任务调度&#xff08;Java & JS & Python&#xff09;题目描述现有一个CPU和一些任务需要处理&#xff0c;已提前获知每个任务的任务ID、优先级、所需执行时间和到达时间。 CPU同时只能运行一个任务&#xff0c;请编写一个任务调度程序&#xff0c;采用“…

作者头像 李华
网站建设 2026/3/5 18:03:11

(新卷,200分)- 探索地块建立(Java JS Python)

(新卷,200分)- 探索地块建立&#xff08;Java & JS & Python&#xff09; 题目描述 给一块n*m的地块&#xff0c;相当于n*m的二维数组&#xff0c;每个元素的值表示这个小地块的发电量&#xff1b; 求在这块地上建立正方形的边长为c的发电站&#xff0c;发电量满足目…

作者头像 李华
网站建设 2026/3/4 18:18:21

dswave.dll文件丢失找不到 免费下载方法分享

在使用电脑系统时经常会出现丢失找不到某些文件的情况&#xff0c;由于很多常用软件都是采用 Microsoft Visual Studio 编写的&#xff0c;所以这类软件的运行需要依赖微软Visual C运行库&#xff0c;比如像 QQ、迅雷、Adobe 软件等等&#xff0c;如果没有安装VC运行库或者安装…

作者头像 李华
网站建设 2026/3/5 14:20:39

亲测好用!9款AI论文平台测评:本科生毕业论文必备工具

亲测好用&#xff01;9款AI论文平台测评&#xff1a;本科生毕业论文必备工具 2026年AI论文工具测评&#xff1a;为什么你需要这份指南 随着人工智能技术的不断进步&#xff0c;越来越多的本科生开始依赖AI论文平台来提升写作效率、优化内容质量。然而&#xff0c;面对市场上琳琅…

作者头像 李华
网站建设 2026/3/4 10:39:02

Flutter for HarmonyOS 开发指南(一):环境搭建与项目创建

前言 在开始之前&#xff0c;我们需要明白&#xff1a;标准的 Flutter SDK&#xff08;Google 官方版&#xff09;目前并不直接支持 ohos 平台。 我们需要使用由华为和社区定制的 Flutter 鸿蒙专用版 SDK&#xff0c;它在引擎层&#xff08;Engine&#xff09;增加了对鸿蒙系统…

作者头像 李华