Mic Input

From Unify Community Wiki
(Difference between revisions)
Jump to: navigation, search
Line 1: Line 1:
 +
'''ATTENTION! THIS PAGE WILL NO LONGER BE UPDATED! THE LATEST UPDATED VERSION CAN BE FOUND ON ''[https://www.assetstore.unity3d.com/#/content/12518 The AssetStore]'''''
 +
 
Hello my name is Mark Duisters and I came across allot of people having problems with getting audio from the machines microphone.
 
Hello my name is Mark Duisters and I came across allot of people having problems with getting audio from the machines microphone.
  

Revision as of 10:42, 22 February 2014

ATTENTION! THIS PAGE WILL NO LONGER BE UPDATED! THE LATEST UPDATED VERSION CAN BE FOUND ON The AssetStore

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.

from external scripts:

Call MicInput.loudness to get the audio data in a float format. (this can be used for scaling objects, chaning color, etc...).

Call gameObject.Find("MicInput").SendMessage("StopMicrophone"); This will terminate any data coming trough the mic in-game.

Call gameObject.Find("MicInput").SendMessage("StartMicrophone"); to start the mic from an external script (you don't need to call this as it is already running by default).

Note! StartMicrophone can only be called in the start function of a script (as that is the point where the mic is selected).

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 under the name Mic Control (still pending for clearance).

Note that some functions are script depended, for instance the java version does not have a push to talk option.

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.

-C# version of the script by djfunkey

-Changed naming of several inputs to be more clear.

-Added Source volume selection.(converted from djfunkey).

-Added ingame menu (selected by user whether he wants to use it or not).(converted from djfunkey).

-Added memory cleaning to prevent audio lag, both in java and C#(djfunkey).


UnityScript (java) features:

1: An Editor menu and an ingame menu so the user/player can pick the microphone they wish to use (handy if hey have a web-cam microphone, and a headset microphone).

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

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

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

5: Option for showing all device names in the console + debugging option for visually reading the input data.

6: Option to listen to your audio input by toggling the mute button.

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);
//if true a menu will apear ingame with all the microphones
var SelectIngame:boolean=false;
//if false the below will override and set the mic selected in the editor
 //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 Devices2 {DefaultDevice, Second, Third, Fourth, Fifth, Sixth}
 
var InputDevice : Devices2;
private var selectedDevice:String;
 
 
 
 
var audioSource:AudioSource;
//The maximum amount of sample data that gets loaded in, best is to leave it on 256, unless you know what you are doing. A higher number gives more accuracy but 
//lowers performance allot, it is best to leave it at 256.
var amountSamples:float=256;
static var loudness:float;
var sensitivity:float=1;
var sourceVolume:float=100;
private var minFreq: int;
private var maxFreq: int;
 
var Mute:boolean=true;
var debug:boolean=false;
var ShowDeviceName:boolean=false;
private var micSelected:boolean=false; 
 
private var mTimer:float=10;
private var mRefTime:float=10; 
 
 
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);
 
}
}
if(SelectIngame==false){
//select the device if possible else give error
if(InputDevice==Devices2.DefaultDevice){
if(i>=1){
selectedDevice= Microphone.devices[0];
}
else{
Debug.LogError ("No device detected on this slot");
}
 
}
 
 
if(InputDevice==Devices2.Second){
if(i>=2){
selectedDevice= Microphone.devices[1];
}
else{
Debug.LogError ("No device detected on this slot");
}
 
}
 
 
 
if(InputDevice==Devices2.Third){
if(i>=3){
selectedDevice= Microphone.devices[2];
}
else{
Debug.LogError ("No device detected on this slot");
return;
}
}
 
 
if(InputDevice==Devices2.Fourth){
if(i>=4){
selectedDevice= Microphone.devices[2];
}
else{
Debug.LogError ("No device detected on this slot");
return;
}
}
if(InputDevice==Devices2.Fifth){
if(i>=5){
selectedDevice= Microphone.devices[2];
}
else{
Debug.LogError ("No device detected on this slot");
return;
}
}
 
if(InputDevice==Devices2.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 () {
//set timer for refreshing memory.
 mTimer += Time.deltaTime;
 //refresh the memory
if (micSelected == true){
 if (mTimer >= mRefTime) {
				StopMicrophone();
				StartMicrophone();
				mTimer = 0;
			}
		   }	
 
 
if(Microphone.IsRecording(selectedDevice)){
  loudness = GetDataStream()*sensitivity*(sourceVolume/10);
  if(debug){
  Debug.Log(loudness);
  }
  }
 
  //the source volume
  if (sourceVolume > 100){
       sourceVolume = 100;
 }
 
  if (sourceVolume < 0){
   sourceVolume = 0;
   }
  audio.volume = (sourceVolume/100);
 
 
}
 
 
function GetDataStream(){
if(Microphone.IsRecording(selectedDevice)){
 
   var dataStream: float[]  = new float[amountSamples];
       var audioValue: float = 0;
        audio.GetOutputData(dataStream,0);
 
        for(var i in dataStream){
            audioValue += Mathf.Abs(i);
        }
        return audioValue/amountSamples;
        }
 
 
 
 
 
 
}
 
 
 
 
 
//select device ingame
 
    function OnGUI () {
 if(SelectIngame==true){
        if (Microphone.devices.Length > 1 && micSelected == false)//If there is more than one device, choose one.
             for (var i:int= 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;
 
        }
 }
    }
 
 
 
    //for the above control the mic start or stop
 
 
 public function 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!
 
    }
 
 
 
 public function StopMicrophone () {
         audio.Stop();//Stops the audio
         Microphone.End(selectedDevice);//Stops the recording of the device  
 
    }
 
 
      function GetMicCaps () {
         Microphone.GetDeviceCaps(selectedDevice,  minFreq,  maxFreq);//Gets the frequency of the device
         if ((minFreq + maxFreq) == 0)//These 2 lines of code are mainly for windows computers
             maxFreq = 44100;
 
    }
 
 
 
 
 
 
    //Create a gui button in another script that calls to this script
        public function MicDeviceGUI (left:float , top:float, width:float, height:float, buttonSpaceTop:float, buttonSpaceLeft:float) {
	if (Microphone.devices.Length > 1 && micSelected == false)//If there is more than one device, choose one.
		for (var i:int=0; i < Microphone.devices.Length; ++i)
			if (GUI.Button(new Rect(left + (buttonSpaceLeft * i), top + (buttonSpaceTop * i), width, height), 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;
	}
    }


djfunkey 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 that the user can pick the microphone they wish to use (handy if hey have a web-cam microphone, and a headset microphone)

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

3: The user can choose for the microphone to be "Push to talk", or to just be constently 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.


using UnityEngine;
using System.Collections;
 
[RequireComponent(typeof(AudioSource))]
public class MicrophoneInput : MonoBehaviour {
 
	public string selectedDevice = "";
    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;
	private float mTimer, mRefTime = 10;
	private int amountSamples = 256;//increase to get better average, but will decrease performance. Best to leave it
 
    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() {
		MicDeviceGUI(10,10, 300, 150, 160, 0);
	}
 
	public void MicDeviceGUI (float left, float top, float width, float height, float buttonSpaceTop, float buttonSpaceLeft) {
		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(left + (buttonSpaceLeft * i), top + (buttonSpaceTop * i), width, height), 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;
	}
 
	public 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!
	}
 
	public 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() {
		mTimer += Time.deltaTime;
		AudioVolume();
        loudness = GetAveragedVolume() * sensitivity * (sourceVolume/10);
		if (buttonToSpeak == true) {
			if (Input.GetKeyDown(KeyCode.T)) //Push to talk
				StartMicrophone();
			if (Input.GetKey(KeyCode.T)) { //Cleans ram while being able to talk
				if (mTimer >= mRefTime) {
					StopMicrophone();
					StartMicrophone();
					mTimer = 0;
				}
			}
			if (Input.GetKeyUp(KeyCode.T))
					StopMicrophone();	
		}
		if (buttonToSpeak == false && micSelected == true && !Microphone.IsRecording(selectedDevice))
			StartMicrophone();
		if (buttonToSpeak == false && micSelected == true) {//Cleans the ram 
			if (mTimer >= mRefTime) {
				StopMicrophone();
				StartMicrophone();
				mTimer = 0;
			}
		}
		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