Mic Input

From Unify Community Wiki
(Difference between revisions)
Jump to: navigation, search
Line 19: Line 19:
 
-Added ShowDeviceName toggle. If true it wil print the device name and slot number to the console.
 
-Added ShowDeviceName toggle. If true it wil print the device name and slot number to the console.
  
 +
UnityScript (java) features:
  
 +
1: A menu so as the player can pick the microphone they wish to use (handy if hey have a web-cam microphone, and a headset microphone).
 +
 +
2: (in development) The player can now adjust the volume of their microphone, it will also affect the loudness variable proportionally.
 +
 +
3: (in development) The player can choose for the microphone to be "Push to talk", or to just be contently on.
 +
 +
4: If there is only 1 device detected it will make that device default.
 +
 +
5: Call input data from any script trough MicInput.loudness.
  
 
Example: var Myfloat:float=MicInput.loudness;
 
Example: var Myfloat:float=MicInput.loudness;
Line 175: Line 185:
  
 
}
 
}
 +
</syntaxhighlight>
 +
 +
 +
djfucnky did an excelent job in converting the script to C#. Thanks to him even more people can take advantage of the microphone ingame.
 +
http://forum.unity3d.com/members/118660-djfunkey
 +
 +
C# features:
 +
 +
1: A menu so as the player can pick the microphone they wish to use (handy if hey have a web-cam microphone, and a headset microphone)
 +
 +
2: The player can now adjust the volume of their microphone, it will also affect the loudness variable proportionally.
 +
 +
3: The player can choose for the microphone to be "Push to talk", or to just be contently on
 +
 +
4: If there is only 1 device detected it will make that device default.
 +
 +
5: Call microphone data from any script with MicrophoneInput.loudness.
 +
 +
 +
<syntaxhighlight lang="javascript">
 +
 +
public class MicrophoneInput : MonoBehaviour {
 +
 +
   
 +
 +
    public string selectedDevice = "";
 +
 +
    public int amountSamples = 256;//increase to get better average, but will decrease performance. Best to leave it
 +
 +
    public float sensitivity = 100;
 +
 +
    public float loudness = 0;//dont touch
 +
 +
    public float sourceVolume = 80;//Between 0 and 100
 +
 +
    public bool buttonToSpeak = false;
 +
 +
    //
 +
 +
    private int minFreq, maxFreq;
 +
 +
    private bool micSelected = false;
 +
 +
   
 +
 +
    void Start() {
 +
 +
        audio.loop = true; // Set the AudioClip to loop
 +
 +
        audio.mute = false; // Mute the sound, we don't want the player to hear it
 +
 +
        selectedDevice = Microphone.devices[0].ToString();
 +
 +
        GetMicCaps();
 +
 +
    }
 +
 +
   
 +
 +
    void OnGUI () {
 +
 +
        if (Microphone.devices.Length > 1 && micSelected == false)//If there is more than one device, choose one.
 +
 +
            for (int i = 0; i < Microphone.devices.Length; ++i)
 +
 +
                if (GUI.Button(new Rect(400, 100 + (110 * i), 300, 100), Microphone.devices[i].ToString())) {
 +
 +
                    StopMicrophone();
 +
 +
                    selectedDevice = Microphone.devices[i].ToString();
 +
 +
                    GetMicCaps();
 +
 +
                    StartMicrophone();
 +
 +
                    micSelected = true;
 +
 +
                }
 +
 +
        if (Microphone.devices.Length < 2 && micSelected == false) {//If there is only 1 decive make it default
 +
 +
            selectedDevice = Microphone.devices[0].ToString();
 +
 +
            GetMicCaps();
 +
 +
            micSelected = true;
 +
 +
        }
 +
 +
    }
 +
 +
   
 +
 +
    void GetMicCaps () {
 +
 +
        Microphone.GetDeviceCaps(selectedDevice, out minFreq, out maxFreq);//Gets the frequency of the device
 +
 +
        if ((minFreq + maxFreq) == 0)//These 2 lines of code are mainly for windows computers
 +
 +
            maxFreq = 44100;
 +
 +
    }
 +
 +
   
 +
 +
    void StartMicrophone () {
 +
 +
        audio.clip = Microphone.Start(selectedDevice, true, 10, maxFreq);//Starts recording
 +
 +
        while (!(Microphone.GetPosition(selectedDevice) > 0)){} // Wait until the recording has started
 +
 +
        audio.Play(); // Play the audio source!
 +
 +
    }
 +
 +
   
 +
 +
    void StopMicrophone () {
 +
 +
        audio.Stop();//Stops the audio
 +
 +
        Microphone.End(selectedDevice);//Stops the recording of the device 
 +
 +
    }
 +
 +
   
 +
 +
    void AudioVolume () {
 +
 +
        if (sourceVolume > 100)
 +
 +
            sourceVolume = 100;
 +
 +
        if (sourceVolume < 0)
 +
 +
            sourceVolume = 0;
 +
 +
        audio.volume = (sourceVolume/100);
 +
 +
    }
 +
 +
 +
 +
    void Update() {
 +
 +
        AudioVolume();
 +
 +
        loudness = GetAveragedVolume() * sensitivity * (sourceVolume/10);
 +
 +
        if (buttonToSpeak == true && micSelected == true) {
 +
 +
            if (Input.GetKeyDown(KeyCode.T)) {//On this key stop or start the recording
 +
 +
                Debug.Log ("keypressed");
 +
 +
                if (!Microphone.IsRecording(selectedDevice))
 +
 +
                    StartMicrophone();
 +
 +
                else
 +
 +
                    StopMicrophone();
 +
 +
            }
 +
 +
        }
 +
 +
        if (buttonToSpeak == false && micSelected == true && !Microphone.IsRecording(selectedDevice))
 +
 +
            StartMicrophone();
 +
 +
        if (Input.GetKeyDown(KeyCode.G))
 +
 +
            micSelected = false;
 +
 +
    }
 +
 +
 +
 +
    float GetAveragedVolume() {
 +
 +
        float[] data = new float[amountSamples];
 +
 +
        float a = 0;
 +
 +
        audio.GetOutputData(data,0);
 +
 +
        foreach(float s in data) {
 +
 +
            a += Mathf.Abs(s);
 +
 +
        }
 +
 +
        return a/amountSamples;
 +
 +
    }
 +
 +
}
 +
 
</syntaxhighlight>
 
</syntaxhighlight>

Revision as of 10:46, 31 October 2013

Hello my name is Mark Duisters and I came across allot of people having problems with getting audio from the machines microphone.

I have made a ready to use script, just place it on an empty GameObject and you are good to go. Call MicInput.loudness to get the audio data in a float format.

To use this script across all languages place it in the standard assets folder (not your own asset folder).

You are free to use this script under the creative commons restriction policy handled by the unify community.

This script can also be downloaded from the asset store.

Update Log:

-Fixed some bugs pointed out by djfunkey from the community: http://forum.unity3d.com/members/118660-djfunkey

-Expanded the editor functionality: now you can choose the audio device which you want to use. Up to 6 devices are supported. If no device is found at the selected slot then the script will spit out an error message.

-Added ShowDeviceName toggle. If true it wil print the device name and slot number to the console.

UnityScript (java) features:

1: A menu so as the player can pick the microphone they wish to use (handy if hey have a web-cam microphone, and a headset microphone).

2: (in development) The player can now adjust the volume of their microphone, it will also affect the loudness variable proportionally.

3: (in development) The player can choose for the microphone to be "Push to talk", or to just be contently on.

4: If there is only 1 device detected it will make that device default.

5: Call input data from any script trough MicInput.loudness.

Example: var Myfloat:float=MicInput.loudness; This could be used to detect when a player is speaking, breathing or to implement interactive environments. Good luck and have fun.

#pragma strict
@script RequireComponent (AudioSource);
@script ExecuteInEditMode;
 
 //Select the microphone you want to use (supported up to 6 to choose from). If the device has number 1 in the console, you should select default as it is the first defice to be found.
enum Devices {DefaultDevice, Second, Third, Fourth, Fifth, Sixth}
 
var InputDevice : Devices;
private var selectedDevice:String;
 
 
 
 
var audioSource:AudioSource;
//The maximum amount of spectrum data that gets loaded in, best is to leave it on 256, unless you know what you are doing.
var spectrumMax:float=256;
static var loudness:float;
var sensitivity:float=1;
var Mute:boolean=false;
var debug:boolean=false;
var ShowDeviceName:boolean=false;
 
function Start () {
 
if(!audioSource){
  audioSource = GetComponent(AudioSource);
	} 
 
var i=0;
//count amount of devices connected
for(device in Microphone.devices){
i++;
if(ShowDeviceName){
Debug.Log ("Devices number "+i+" Name"+"="+device);
 
}
}
 
//select the device if possible else give error
if(InputDevice==Devices.DefaultDevice){
if(i>=1){
selectedDevice= Microphone.devices[0];
}
else{
Debug.LogError ("No device detected on this slot");
}
 
}
 
 
if(InputDevice==Devices.Second){
if(i>=2){
selectedDevice= Microphone.devices[1];
}
else{
Debug.LogError ("No device detected on this slot");
}
 
}
 
 
 
if(InputDevice==Devices.Third){
if(i>=3){
selectedDevice= Microphone.devices[2];
}
else{
Debug.LogError ("No device detected on this slot");
return;
}
}
 
 
if(InputDevice==Devices.Fourth){
if(i>=4){
selectedDevice= Microphone.devices[2];
}
else{
Debug.LogError ("No device detected on this slot");
return;
}
}
if(InputDevice==Devices.Fifth){
if(i>=5){
selectedDevice= Microphone.devices[2];
}
else{
Debug.LogError ("No device detected on this slot");
return;
}
}
 
if(InputDevice==Devices.Sixth){
if(i>=6){
selectedDevice= Microphone.devices[2];
}
else{
Debug.LogError ("No device detected on this slot");
return;
}
}
 
 
 
 
 
//detect the default microphone
audio.clip = Microphone.Start(selectedDevice, true, 10, 44100);
//loop the playing of the recording so it will be realtime
audio.loop = true;
//if you only need the data stream values  check Mute, if you want to hear yourself ingame don't check Mute. 
audio.mute = Mute;
//don't do anything until the microphone started up
while (!(Microphone.GetPosition(selectedDevice) > 0)){
 
}
//Put the clip on play so the data stream gets ingame on realtime
audio.Play();
 
}
 
 
 
//apply the mic input data stream to a float;
function Update () {
if(Microphone.IsRecording(selectedDevice)){
  loudness = GetDataStream()*sensitivity;
  if(debug){
  Debug.Log(loudness);
  }
  }
}
 
 
function GetDataStream(){
if(Microphone.IsRecording(selectedDevice)){
 
   var dataStream: float[]  = new float[spectrumMax];
       var audioValue: float = 0;
        audio.GetOutputData(dataStream,0);
 
        for(var i in dataStream){
            audioValue += Mathf.Abs(i);
        }
        return audioValue/spectrumMax;
        }
 
}


djfucnky did an excelent job in converting the script to C#. Thanks to him even more people can take advantage of the microphone ingame. http://forum.unity3d.com/members/118660-djfunkey

C# features:

1: A menu so as the player can pick the microphone they wish to use (handy if hey have a web-cam microphone, and a headset microphone)

2: The player can now adjust the volume of their microphone, it will also affect the loudness variable proportionally.

3: The player can choose for the microphone to be "Push to talk", or to just be contently on

4: If there is only 1 device detected it will make that device default.

5: Call microphone data from any script with MicrophoneInput.loudness.


public class MicrophoneInput : MonoBehaviour {
 
 
 
    public string selectedDevice = "";
 
    public int amountSamples = 256;//increase to get better average, but will decrease performance. Best to leave it
 
    public float sensitivity = 100;
 
    public float loudness = 0;//dont touch
 
    public float sourceVolume = 80;//Between 0 and 100
 
    public bool buttonToSpeak = false;
 
    //
 
    private int minFreq, maxFreq;
 
    private bool micSelected = false;
 
 
 
    void Start() {
 
        audio.loop = true; // Set the AudioClip to loop
 
        audio.mute = false; // Mute the sound, we don't want the player to hear it
 
        selectedDevice = Microphone.devices[0].ToString();
 
        GetMicCaps();
 
    }
 
 
 
    void OnGUI () {
 
        if (Microphone.devices.Length > 1 && micSelected == false)//If there is more than one device, choose one.
 
            for (int i = 0; i < Microphone.devices.Length; ++i)
 
                if (GUI.Button(new Rect(400, 100 + (110 * i), 300, 100), Microphone.devices[i].ToString())) {
 
                    StopMicrophone();
 
                    selectedDevice = Microphone.devices[i].ToString();
 
                    GetMicCaps();
 
                    StartMicrophone();
 
                    micSelected = true;
 
                }
 
        if (Microphone.devices.Length < 2 && micSelected == false) {//If there is only 1 decive make it default
 
            selectedDevice = Microphone.devices[0].ToString();
 
            GetMicCaps();
 
            micSelected = true;
 
        }
 
    }
 
 
 
    void GetMicCaps () {
 
        Microphone.GetDeviceCaps(selectedDevice, out minFreq, out maxFreq);//Gets the frequency of the device
 
        if ((minFreq + maxFreq) == 0)//These 2 lines of code are mainly for windows computers
 
            maxFreq = 44100;
 
    }
 
 
 
    void StartMicrophone () {
 
        audio.clip = Microphone.Start(selectedDevice, true, 10, maxFreq);//Starts recording
 
        while (!(Microphone.GetPosition(selectedDevice) > 0)){} // Wait until the recording has started
 
        audio.Play(); // Play the audio source!
 
    }
 
 
 
    void StopMicrophone () {
 
        audio.Stop();//Stops the audio
 
        Microphone.End(selectedDevice);//Stops the recording of the device  
 
    }
 
 
 
    void AudioVolume () {
 
        if (sourceVolume > 100)
 
            sourceVolume = 100;
 
        if (sourceVolume < 0)
 
            sourceVolume = 0;
 
        audio.volume = (sourceVolume/100);
 
    }
 
 
 
    void Update() {
 
        AudioVolume();
 
        loudness = GetAveragedVolume() * sensitivity * (sourceVolume/10);
 
        if (buttonToSpeak == true && micSelected == true) {
 
            if (Input.GetKeyDown(KeyCode.T)) {//On this key stop or start the recording
 
                Debug.Log ("keypressed");
 
                if (!Microphone.IsRecording(selectedDevice))
 
                    StartMicrophone();
 
                else 
 
                    StopMicrophone();
 
            }
 
        }
 
        if (buttonToSpeak == false && micSelected == true && !Microphone.IsRecording(selectedDevice))
 
            StartMicrophone();
 
        if (Input.GetKeyDown(KeyCode.G))
 
            micSelected = false;
 
    }
 
 
 
    float GetAveragedVolume() {
 
        float[] data = new float[amountSamples];
 
        float a = 0;
 
        audio.GetOutputData(data,0);
 
        foreach(float s in data) {
 
            a += Mathf.Abs(s);
 
        }
 
        return a/amountSamples;
 
    }
 
}
Personal tools
Namespaces

Variants
Actions
Navigation
Extras
Toolbox