1. 程式人生 > >unity遊戲開發入門-聲音控制遊戲

unity遊戲開發入門-聲音控制遊戲

聲音控制遊戲中人物的移動,關鍵在於聲音的傳入,這裡關機鍵在於使用了Microphone 怎麼使用呢?下面給一段我編寫的聲音傳入的程式碼:(關鍵處已被標識) using System.Collections; using System.Collections.Generic; using UnityEngine;

public class vioce : MonoBehaviour { public static float volumm; AudioClip aud;//錄製的資訊 string device;//裝置名字

// Use this for initialization
void Start () {
    device = Microphone.devices[0];//獲取錄製裝置的名字,預設為0
    aud = Microphone.Start(device, true,999, 44100);//true表示迴圈、999表示錄的長度、44100為預設取樣率。
}

// Update is called once per frame
void Update () {
    volumm = getMaxVoice();
	
}


float getMaxVoice()//獲取最大音量
{
    float getvolue = 0f;
    float[] volue = new float[128];//儲存聲音資料
    int offset = Microphone.GetPosition(device) - 128 + 1;//獲取data開始的位置,GetPosition獲取麥克風的錄取終止位置
    if (offset < 0)
    {
        return 0;
    }
    aud.GetData(volue, offset);//錄製的聲音獲取資料的方法
    for (int i = 0; i < 128; i++)//保持陣列中儲存的都是最大音量
    {
        float temp = volue[i];
        if (temp > getvolue)
        {
            getvolue = temp;
        }
    }
    return getvolue;
}

}