收藏 分销(赏)

我学院:Unity麦克风录制声音脚本.docx

上传人:xrp****65 文档编号:7481605 上传时间:2025-01-06 格式:DOCX 页数:12 大小:28.37KB 下载积分:10 金币
下载 相关 举报
我学院:Unity麦克风录制声音脚本.docx_第1页
第1页 / 共12页
我学院:Unity麦克风录制声音脚本.docx_第2页
第2页 / 共12页


点击查看更多>>
资源描述
学游戏就上我学院 Unity麦克风录制声音脚本 //使用麦克风可以录制音频流,但是如何将录制的音频流通过代码的形式改成3d音效如果有知道的朋友情不吝赐教 using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using UnityEngine; using System.Collections; using System.Net; [RequireComponent (typeof(AudioSource))] public class MicroPhoneInput : MonoBehaviour {                 private static MicroPhoneInput m_instance;                 public float sensitivity=100;         public float loudness=0;                 private static string[] micArray=null;                 const int HEADER_SIZE = 44;                 const int RECORD_TIME = 10;                 // Use this for initialization         void Start () {         }                 public static MicroPhoneInput getInstance()         {                 if (m_instance == null)                 {                         micArray = Microphone.devices;                         if (micArray.Length == 0)                         {                                 Debug.LogError ("Microphone.devices is null");                         }                         foreach (string deviceStr in Microphone.devices)                         {                                 Debug.Log("device name = " + deviceStr);                         }                         if(micArray.Length==0)                         {                                 Debug.LogError("no mic device");                         }                                                 GameObject MicObj=new GameObject("MicObj");                         m_instance= MicObj.AddComponent<MicroPhoneInput>();                 }                 return m_instance;         }                 void OnGUI(){                 //GUI.Label(new Rect(10,10,200,100),"loudness = "+loudness);                 //GUI.Label(new Rect(10,210,200,100),"Microphone.GetPosition = "+Microphone.GetPosition(null));         }         public void StartRecord()         {                 audio.Stop();                 if (micArray.Length == 0)                 {                         Debug.Log("No Record Device!");                         return;                 }                 audio.loop = false;                 audio.mute = true;                 audio.clip = Microphone.Start(null, false, RECORD_TIME, 44100); //22050                 while (!(Microphone.GetPosition(null)>0)) {                 }                 audio.Play ();                 Debug.Log("StartRecord");                 //倒计时                 StartCoroutine(TimeDown());                         }         public  void StopRecord()         {                 if (micArray.Length == 0)                 {                         Debug.Log("No Record Device!");                         return;                 }                 if (!Microphone.IsRecording(null))                 {                         return;                 }                 Microphone.End (null);                 audio.Stop();                                 Debug.Log("StopRecord");                 // PlayRecord();                                 //调试Int16[] 数据的转化与播放                 //PlayClipData(GetClipData());                         }         public Byte[] GetClipData()         {                 if (audio.clip == null)                 {                         Debug.Log("GetClipData audio.clip is null");                         return null;                 }                                 float[] samples = new float[audio.clip.samples];                                 audio.clip.GetData(samples, 0);                                                 Byte[] outData = new byte[samples.Length * 2];                 //Int16[] intData = new Int16[samples.Length];                 //converting in 2 float[] steps to Int16[], //then Int16[] to Byte[]                                 int rescaleFactor = 32767; //to convert float to Int16                                 for (int i = 0; i < samples.Length; i++)                 {                         short temshort = (short)(samples[i] * rescaleFactor);                                                 Byte[] temdata=System.BitConverter.GetBytes(temshort);                                                 outData[i*2]=temdata[0];                         outData[i*2+1]=temdata[1];                                                                 }                 if (outData == null || outData.Length <= 0)                 {                         Debug.Log("GetClipData intData is null");                         return null;                 }                 //return intData;                 return outData;         }         /// <summary>         /// 调用GOOLE语音识别引擎         /// </summary>         /// <returns></returns>         private string GoogleSTT(byte[] voice)         {                 string result = string.Empty;                 try                 {                         /**string inFile = "audio.wav";                         FileStream fs = new FileStream(inFile, FileMode.Open);                         byte[] voice = new byte[fs.Length];                         fs.Read(voice, 0, voice.Length);                         fs.Close(); */                         HttpWebRequest request = null;                         string url = "                         Uri uri = new Uri(url);                         request = (HttpWebRequest)WebRequest.Create(uri);                         request.Method = "POST";                         request.ContentType = "audio/x-flac; rate=16000";                         request.ContentLength = voice.Length;                         using (Stream writeStream = request.GetRequestStream())                         {                                 writeStream.Write(voice, 0, voice.Length);                         }                                                 using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())                         {                                 using (Stream responseStream = response.GetResponseStream())                                 {                                         using (StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8))                                         {                                                 result = readStream.ReadToEnd();                                                 Debug.Log("result="+result);                                         }                                 }                         }                 }                 catch (Exception ex)                 {                         //Console.WriteLine(ex.StackTrace);                         Debug.Log(ex.StackTrace);                 }                 return result;         }         public void PlayClipData(Int16[] intArr)         {                                 string aaastr = intArr.ToString();                 long  aaalength=aaastr.Length;                 Debug.LogError("aaalength=" + aaalength);                                 string aaastr1 = Convert.ToString (intArr);                 aaalength = aaastr1.Length;                 Debug.LogError("aaalength=" + aaalength);                                 if (intArr.Length == 0)                 {                         Debug.Log("get intarr clipdata is null");                         return;                 }                 //从Int16[]到float[]                 float[] samples = new float[intArr.Length];                 int rescaleFactor = 32767;                 for (int i = 0; i < intArr.Length; i++)                 {                         samples[i] = (float)intArr[i] / rescaleFactor;                 }                                 //从float[]到Clip                 AudioSource audioSource = this.GetComponent<AudioSource>();                 if (audioSource.clip == null)                 {                         audioSource.clip = AudioClip.Create("playRecordClip", intArr.Length, 1, 44100, false, false);                 }                 audioSource.clip.SetData(samples, 0);                 audioSource.mute = false;                 audioSource.Play();         }         public void PlayRecord()         {                 if (audio.clip == null)                 {                         Debug.Log("audio.clip=null");                         return;                 }                 audio.mute = false;                 audio.loop = false;                 audio.Play ();                 Debug.Log("PlayRecord");                         }         public void LoadAndPlayRecord()         {                 string recordPath ="your path";                                 //SavWav.LoadAndPlay (recordPath);         }         public  float GetAveragedVolume()         {                 float[] data=new float[256];                 float a=0;                 audio.GetOutputData(data,0);                 foreach(float s in data)                 {                         a+=Mathf.Abs(s);                 }                 return a/256;         }         // Update is called once per frame         void Update ()         {                 loudness = GetAveragedVolume () * sensitivity;                 if (loudness > 1)                 {                         Debug.Log("loudness = "+loudness);                 }         }         private IEnumerator TimeDown()         {                 Debug.Log(" IEnumerator TimeDown()");                                 int time = 0;                 while (time < RECORD_TIME)                 {                         if (!Microphone.IsRecording (null))                         { //如果没有录制                                 Debug.Log ("IsRecording false");                                 yield break;                         }                         Debug.Log("yield return new WaitForSeconds "+time);                         yield return new WaitForSeconds(1);                         time++;                 }                 if (time >= 10)                 {                         Debug.Log("RECORD_TIME is out! stop record!");                         StopRecord();                 }                 yield return 0;         } } 更多参考资料见我学院在线平台: Unity3D|Cocos|php|HTML5|Java|ios|Android|C#|AS3|UI设计|原画设计|动漫美术|游戏策划
展开阅读全文

开通  VIP会员、SVIP会员  优惠大
下载10份以上建议开通VIP会员
下载20份以上建议开通SVIP会员


开通VIP      成为共赢上传

当前位置:首页 > 应用文书 > 其他

移动网页_全站_页脚广告1

关于我们      便捷服务       自信AI       AI导航        抽奖活动

©2010-2026 宁波自信网络信息技术有限公司  版权所有

客服电话:0574-28810668  投诉电话:18658249818

gongan.png浙公网安备33021202000488号   

icp.png浙ICP备2021020529号-1  |  浙B2-20240490  

关注我们 :微信公众号    抖音    微博    LOFTER 

客服