找回密码
 立即注册
查看: 6142|回复: 75

[脚本] 麦克风录制声音

[复制链接]
发表于 2014-6-27 13:32 | 显示全部楼层 |阅读模式
//使用麦克风可以录制音频流,但是如何将录制的音频流通过代码的形式改成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 = "http://www.google.com/speech-api/v1/recognize?xjerr=1&client=chromium&lang=zh-CN";
                        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;
        }
}

发表于 2017-4-7 19:14 | 显示全部楼层
很不错
发表于 2017-4-7 18:36 | 显示全部楼层
楼主是超人
发表于 2017-4-7 19:01 | 显示全部楼层
好帖就是要顶
发表于 2017-4-7 18:39 | 显示全部楼层
顶顶多好
发表于 2017-4-7 19:17 | 显示全部楼层
LZ真是人才
发表于 2017-4-15 07:50 | 显示全部楼层
真心顶
发表于 2017-4-15 07:42 | 显示全部楼层
难得一见的好帖
发表于 2017-4-15 08:03 | 显示全部楼层
说的非常好
发表于 2017-4-15 08:12 | 显示全部楼层
很好哦
懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Unity开发者联盟 ( 粤ICP备20003399号 )

GMT+8, 2024-4-29 12:39 , Processed in 0.137111 second(s), 26 queries .

Powered by Discuz! X3.5 Licensed

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表