├── .gitignore ├── Assets ├── MicControl │ ├── Editor │ │ ├── MicControlImporterC.cs │ │ └── VolumeBarC.cs │ └── Scripts │ │ └── MicControlC.cs └── Scripts │ ├── AudioControlled.cs │ └── ReadMe.txt.meta ├── LICENSE └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | *.meta -------------------------------------------------------------------------------- /Assets/MicControl/Editor/MicControlImporterC.cs: -------------------------------------------------------------------------------- 1 | /*using UnityEngine; 2 | using UnityEditor; 3 | using System.Collections; 4 | using System.IO; 5 | 6 | [CustomEditor(typeof(MicControlC))] 7 | public class MicControlImporter : Editor 8 | { 9 | //apply only to this audio source 10 | MicControlC CurrentMicController; 11 | 12 | void OnInspectorGUI () 13 | { 14 | CurrentMicController = (MicControlC)target; 15 | 16 | //Redirect 3D toggle 17 | CurrentMicController.GetComponent ().ThreeD = GUILayout.Toggle (CurrentMicController.ThreeD, new GUIContent ("3D sound", "Should the streamed audio be a 3D sound? (Only enable this if you are using the controller to stream sound (VOIP) ")); 18 | 19 | } 20 | }*/ -------------------------------------------------------------------------------- /Assets/MicControl/Editor/VolumeBarC.cs: -------------------------------------------------------------------------------- 1 | using UnityEditor; 2 | using UnityEngine; 3 | using System.Collections; 4 | 5 | [CustomEditor(typeof(MicControlC))] 6 | public class VolumeBarC : Editor 7 | { 8 | 9 | MicControlC ListenToMic; 10 | 11 | ///////////////////////////////////////////////////////////////////////////////////////////////// 12 | public override void OnInspectorGUI () 13 | { 14 | ListenToMic = (MicControlC)target; 15 | 16 | float micInputValue = MicControlC.loudness; 17 | ProgressBar (micInputValue, "Loudness"); 18 | 19 | //show other variables 20 | 21 | //Redirect 3D toggle 22 | ListenToMic.ThreeD = GUILayout.Toggle (ListenToMic.ThreeD, new GUIContent ("3D sound", "Should the streamed audio be a 3D sound? (Only enable this if you are using the controller to stream sound (VOIP) ")); 23 | 24 | //when 3D audio is enabled show the fall off settings 25 | if (ListenToMic.ThreeD) { 26 | ListenToMic.VolumeFallOff = EditorGUILayout.FloatField (new GUIContent ("Volume falloff", "Set the rate at wich audio volume gets lowered. A lower value will have a slower falloff and thus hearable from a greater distance, while a higher value will make the audio degrate faster and dissapear from a shorter distance"), ListenToMic.VolumeFallOff); 27 | ListenToMic.PanThreshold = EditorGUILayout.FloatField (new GUIContent ("PanThreshold", "Set the rate at wich audio PanThreshold gets switched between left or right ear. A lower value will have a faster transition and thus a faster switch, while a higher value will make the transition slower and smoothly switch between the ears. Don't go to smooth though as this will turn your audio to mono channel"), ListenToMic.PanThreshold); 28 | } 29 | 30 | //Redirect select ingame 31 | ListenToMic.SelectIngame = GUILayout.Toggle (ListenToMic.SelectIngame, new GUIContent ("Select in game", "select the audio source through a GUI ingame")); 32 | 33 | //Redirect Mute ingame 34 | ListenToMic.Mute = GUILayout.Toggle (ListenToMic.Mute, new GUIContent ("Mute", "when dissabled you can listen to a playback of the microphone")); 35 | 36 | //Redirect debug ingame 37 | ListenToMic.debug = GUILayout.Toggle (ListenToMic.debug, new GUIContent ("Debug", "This will write the gathered Loudness value to the console during playmode. This is handy if you want if statements to listen at a specific value.")); 38 | 39 | //Redirect ShozDeviceName ingame 40 | ListenToMic.ShowDeviceName = GUILayout.Toggle (ListenToMic.ShowDeviceName, new GUIContent ("Show Device name(s)", "When selected all detected devices will be written to the console during play mode")); 41 | 42 | EditorUtility.SetDirty (target); 43 | 44 | // Show default inspector property editor 45 | DrawDefaultInspector (); 46 | } 47 | 48 | // Custom GUILayout progress bar. 49 | void ProgressBar (float value, string label) 50 | { 51 | // Get a rect for the progress bar using the same margins as a textfield: 52 | Rect rect = GUILayoutUtility.GetRect (18, 18, "TextField"); 53 | EditorGUI.ProgressBar (rect, value, label); 54 | EditorGUILayout.Space (); 55 | } 56 | } -------------------------------------------------------------------------------- /Assets/MicControl/Scripts/MicControlC.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using System.Collections; 3 | 4 | //The GameObject requires a AudioSource component 5 | [RequireComponent (typeof(AudioSource))] 6 | 7 | public class MicControlC : MonoBehaviour 8 | { 9 | 10 | private string selectedDevice; 11 | private int minFreq = 0; 12 | private float ListenerDistance; 13 | private Vector3 ListenerPosition; 14 | private bool micSelected = false; 15 | private bool recording = true; 16 | private bool focused = false; 17 | private bool Initialised = false; 18 | 19 | private float[] freqData; 20 | private int nSamples = 1024; 21 | private float fMax; 22 | 23 | private int position = 0; 24 | private int sampleRate = 0; 25 | private float frequency = 440; 26 | private int fallbackMaxFreq = 44100; 27 | 28 | AudioSource audioSource; 29 | 30 | //if false the below will override and set the mic selected in the editor 31 | //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. 32 | public enum Devices 33 | { 34 | DefaultDevice, 35 | Second, 36 | Third, 37 | Fourth, 38 | Fifth, 39 | Sixth 40 | } 41 | 42 | public Devices InputDevice; 43 | public Transform audioListener; 44 | 45 | //The main entry point to the input signal 46 | public static float loudness = 0.0f; 47 | 48 | //The maximum amount of sample data that gets loaded in, best is to leave it on 256, unless you know what you are doing. 49 | //A higher number gives more accuracy but lowers performance alot, it is best to leave it at 256. 50 | public int amountSamples = 256; 51 | 52 | public int maxFreq = 44100;//48000; 53 | 54 | public float sensitivity = 0.4f; 55 | public float sourceVolume = 100f; 56 | 57 | //if true a menu will apear ingame with all the microphones 58 | [HideInInspector()] 59 | public bool 60 | SelectIngame = false; 61 | 62 | [HideInInspector()] 63 | public bool 64 | ThreeD = false; 65 | 66 | [HideInInspector()] 67 | public float 68 | VolumeFallOff = 1.0f; 69 | 70 | [HideInInspector()] 71 | public float 72 | PanThreshold = 1.0f; 73 | 74 | [HideInInspector()] 75 | public bool 76 | Mute = true; 77 | 78 | [HideInInspector()] 79 | public bool 80 | debug = false; 81 | 82 | [HideInInspector()] 83 | public bool 84 | ShowDeviceName = false; 85 | 86 | void Start () 87 | { 88 | //select audio source 89 | if (!audioSource) { 90 | audioSource = GetComponent (); 91 | //audioSource.mute = true; 92 | audioSource.playOnAwake = false; 93 | } 94 | 95 | InitMic (); 96 | Initialised = true; 97 | } 98 | 99 | 100 | /* 101 | * Apply the mic input data stream to a float. 102 | */ 103 | void Update () 104 | { 105 | //pause everything when not focused on the app and then re-initialize. 106 | // if (!focused) { 107 | // StopMicrophone (); 108 | // Initialised = false; 109 | // } 110 | if (!Application.isPlaying) { 111 | //don't stop the microphone if you are clicking inside the editor 112 | StopMicrophone (); 113 | Initialised = false; 114 | } else { 115 | if (!Initialised) { 116 | InitMic (); 117 | Initialised = true; 118 | } 119 | } 120 | 121 | if (Microphone.IsRecording (selectedDevice)) { 122 | loudness = GetDataStream () * sensitivity * (sourceVolume / 10); 123 | } 124 | 125 | if (debug) { 126 | Debug.Log (loudness); 127 | } 128 | 129 | //the source volume 130 | if (sourceVolume > 100) { 131 | sourceVolume = 100; 132 | } 133 | 134 | if (sourceVolume < 0) { 135 | sourceVolume = 0; 136 | } 137 | 138 | //when 3D is enabled adjust the volume based on distance. 139 | if (ThreeD) { 140 | ListenerDistance = Vector3.Distance (transform.position, audioListener.position); 141 | ListenerPosition = audioListener.InverseTransformPoint (transform.position); 142 | 143 | audioSource.volume = (sourceVolume / 100 / (ListenerDistance * VolumeFallOff)); 144 | audioSource.panStereo = (ListenerPosition.x / PanThreshold); 145 | 146 | } else { 147 | audioSource.volume = (sourceVolume / 100); 148 | } 149 | 150 | audioSource.mute = Mute; 151 | } 152 | 153 | /* 154 | * The main data stream from the microphone 155 | */ 156 | float GetDataStream () 157 | { 158 | if (Microphone.IsRecording (selectedDevice)) { 159 | float[] samples = new float[amountSamples]; //Converts to a float 160 | //float[] samples = new float[audioSource.clip.samples * audioSource.clip.channels]; 161 | 162 | audioSource.clip.GetData (samples, 0); 163 | return Sum (samples) / amountSamples; 164 | } else { 165 | Debug.Log ("The active microphone is not recording."); 166 | return 0.0f; 167 | } 168 | } 169 | 170 | 171 | private float Sum (params float[] samples) 172 | { 173 | float result = 0.0f; 174 | for (int i = 0; i < samples.Length; i++) { 175 | result += Mathf.Abs (samples [i]); 176 | } 177 | return result; 178 | } 179 | 180 | private float Average (params float[] samples) 181 | { 182 | float sum = Sum (samples); 183 | float result = (float)sum / samples.Length; 184 | return result; 185 | } 186 | 187 | /* 188 | * select device ingame 189 | */ 190 | void OnGUI () 191 | { 192 | if (SelectIngame == true) { 193 | //If there is more than one device, choose one. 194 | if (Microphone.devices.Length > 0 && micSelected == false) { 195 | for (int i = 0; i < Microphone.devices.Length; ++i) { 196 | if (GUI.Button (new Rect (400, 100 + (110 * i), 300, 100), Microphone.devices [i].ToString ())) { 197 | StopMicrophone (); 198 | selectedDevice = Microphone.devices [i].ToString (); 199 | GetMicCaps (); 200 | StartMicrophone (); 201 | micSelected = true; 202 | 203 | } 204 | } 205 | } 206 | if (Microphone.devices.Length < 1 && micSelected == false) {//If there is only 1 decive make it default 207 | selectedDevice = Microphone.devices [0].ToString (); 208 | GetMicCaps (); 209 | micSelected = true; 210 | } 211 | } 212 | 213 | } 214 | 215 | /* 216 | * 217 | * Initialize microphone! 218 | * 219 | */ 220 | private void InitMic () 221 | { 222 | //only Initialize microphone if a device is detected 223 | if (Microphone.devices.Length >= 0) { 224 | 225 | int i = 0; 226 | //count amount of devices connected 227 | foreach (string device in Microphone.devices) { 228 | i++; 229 | if (ShowDeviceName) { 230 | Debug.Log ("Devices number " + i + " Name" + "=" + device); 231 | } 232 | } 233 | 234 | if (SelectIngame == false) { 235 | //select the device if possible else give error 236 | if (InputDevice == Devices.DefaultDevice) { 237 | if (i >= 1) { 238 | selectedDevice = Microphone.devices [0]; 239 | } else { 240 | Debug.LogError ("No device detected on this slot. Check input connection"); 241 | } 242 | 243 | } 244 | 245 | if (InputDevice == Devices.Second) { 246 | if (i >= 2) { 247 | selectedDevice = Microphone.devices [1]; 248 | } else { 249 | Debug.LogError ("No device detected on this slot. Check input connection"); 250 | } 251 | 252 | } 253 | 254 | if (InputDevice == Devices.Third) { 255 | if (i >= 3) { 256 | selectedDevice = Microphone.devices [2]; 257 | } else { 258 | Debug.LogError ("No device detected on this slot. Check input connection"); 259 | } 260 | } 261 | 262 | 263 | if (InputDevice == Devices.Fourth) { 264 | if (i >= 4) { 265 | selectedDevice = Microphone.devices [2]; 266 | } else { 267 | Debug.LogError ("No device detected on this slot. Check input connection"); 268 | } 269 | } 270 | if (InputDevice == Devices.Fifth) { 271 | if (i >= 5) { 272 | selectedDevice = Microphone.devices [2]; 273 | } else { 274 | Debug.LogError ("No device detected on this slot. Check input connection"); 275 | } 276 | } 277 | 278 | if (InputDevice == Devices.Sixth) { 279 | if (i >= 6) { 280 | selectedDevice = Microphone.devices [2]; 281 | } else { 282 | Debug.LogError ("No device detected on this slot. Check input connection"); 283 | } 284 | } 285 | 286 | } 287 | 288 | //detect the selected microphone 289 | audioSource.clip = Microphone.Start (selectedDevice, true, 10, maxFreq); 290 | 291 | //loop the playing of the recording so it will be realtime 292 | audioSource.loop = true; 293 | //if you only need the data stream values check Mute, if you want to hear yourself ingame don't check Mute. 294 | audioSource.mute = Mute; 295 | 296 | 297 | //don't do anything until the microphone started up 298 | while (!(Microphone.GetPosition(selectedDevice) > 0)) { 299 | if (debug && Time.deltaTime >= 0.1f) { 300 | Debug.Log ("Awaiting connection"); 301 | } 302 | } 303 | if (debug) { 304 | Debug.Log ("Connected"); 305 | } 306 | 307 | //Put the clip on play so the data stream gets ingame on realtime 308 | audioSource.Play (); 309 | recording = true; 310 | } 311 | 312 | } 313 | /* End Microphone Initialization */ 314 | 315 | 316 | 317 | /* 318 | * For the above control the mic start or stop 319 | */ 320 | public void StartMicrophone () 321 | { 322 | //Starts recording 323 | audioSource.clip = Microphone.Start (selectedDevice, true, 10, maxFreq); 324 | 325 | if (debug) { 326 | Debug.Log ("Selected device: " + selectedDevice); 327 | } 328 | 329 | // Wait until the recording has started 330 | while (!(Microphone.GetPosition(selectedDevice) > 0)) { 331 | if (debug) { 332 | Debug.Log ("Waiting on recording to start..."); 333 | } 334 | } 335 | 336 | if (debug) { 337 | Debug.Log ("Playing the recorded audio..."); 338 | } 339 | // Play the audio recording 340 | audioSource.Play (); 341 | } 342 | 343 | public void StopMicrophone () 344 | { 345 | if (debug) { 346 | Debug.Log ("Stopping the microphone..."); 347 | } 348 | 349 | //Stops the audio 350 | audioSource.Stop (); 351 | 352 | //Stops the recording of the device 353 | Microphone.End (selectedDevice); 354 | 355 | } 356 | 357 | void GetMicCaps () 358 | { 359 | //Gets the frequency of the device 360 | Microphone.GetDeviceCaps (selectedDevice, out minFreq, out maxFreq); 361 | 362 | //These 2 lines of code are mainly for windows computers 363 | if ((minFreq + maxFreq) == 0) { 364 | maxFreq = fallbackMaxFreq; 365 | } 366 | } 367 | 368 | 369 | /* 370 | * Create a gui button in another script that calls to this script 371 | */ 372 | public void MicDeviceGUI (float left, float top, float width, float height, float buttonSpaceTop, float buttonSpaceLeft) 373 | { 374 | //If there is more than one device, choose one. 375 | if (Microphone.devices.Length > 1 && micSelected == false) { 376 | for (int i=0; i < Microphone.devices.Length; ++i) { 377 | if (GUI.Button (new Rect (left + (buttonSpaceLeft * i), top + (buttonSpaceTop * i), width, height), Microphone.devices [i].ToString ())) { 378 | StopMicrophone (); 379 | selectedDevice = Microphone.devices [i].ToString (); 380 | GetMicCaps (); 381 | StartMicrophone (); 382 | micSelected = true; 383 | } 384 | } 385 | } 386 | 387 | //If there is only 1 microphone make it default 388 | if (Microphone.devices.Length < 2 && micSelected == false) { 389 | selectedDevice = Microphone.devices [0].ToString (); 390 | GetMicCaps (); 391 | micSelected = true; 392 | } 393 | } 394 | 395 | /* 396 | * Flush the data through the custom created audio clip. This controls the data flow of that clip 397 | * Creates a 1 sec long audioclip, with a 440hz sinoid 398 | */ 399 | void OnAudioFilterRead (float[] data, int channels) 400 | { 401 | //audioSource.spatialBlend 402 | /*for (int count = 0; count < data.Length; count++) { 403 | data [count] = Mathf.Sign (Mathf.Sin (2 * Mathf.PI * frequency * position / sampleRate)); 404 | position++; 405 | }*/ 406 | //Debug.Log ("OnAudioFilterRead(): " + data + " : " + channels); 407 | //Debug.Log (data); 408 | } 409 | 410 | void PCMReaderCallback (float[] data) 411 | { 412 | if (debug) { 413 | Debug.Log ("PCMReaderCallback()"); 414 | Debug.Log (data); 415 | Debug.Log ("-----"); 416 | } 417 | } 418 | 419 | void PCMSetPositionCallback (int newPosition) 420 | { 421 | if (debug) { 422 | Debug.Log ("PCMSetPositionCallback()"); 423 | Debug.Log (newPosition); 424 | Debug.Log ("====="); 425 | } 426 | position = newPosition; 427 | } 428 | 429 | /* 430 | * Start or stop the script from running when the state is paused or not. 431 | */ 432 | void OnApplicationFocus (bool focus) 433 | { 434 | focused = focus; 435 | } 436 | 437 | void OnApplicationPause (bool focus) 438 | { 439 | focused = focus; 440 | } 441 | 442 | } -------------------------------------------------------------------------------- /Assets/Scripts/AudioControlled.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using System.Collections; 3 | 4 | public class AudioControlled : MonoBehaviour 5 | { 6 | 7 | public MicControlC micControl; 8 | public float speed = 0.1f; 9 | 10 | // Use this for initialization 11 | void Start () 12 | { 13 | 14 | } 15 | 16 | // Update is called once per frame 17 | void Update () 18 | { 19 | if (MicControlC.loudness > 0.0f) { 20 | Vector3 toRotation = new Vector3 (1.0f, MicControlC.loudness, 1.0f); 21 | Quaternion.Lerp(transform.rotation, toRotation,Time.time * speed); 22 | //Debug.Log (MicControlC.loudness); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Assets/Scripts/ReadMe.txt.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 91abbd2b10d1b4d76b7c809fe690282b 3 | timeCreated: 1431069808 4 | licenseType: Free 5 | TextScriptImporter: 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Rob Sawyer 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Unity 3D Mic Control (C#) 2 | > This is heavily based on the scripts provided in the [Mic Control](https://www.assetstore.unity3d.com/en/#!/content/12518) asset package located in the Asset Store. I've basically just converted the latest Javascript version to C#. 3 | 4 | ## Original source code (java) created by Mark Duisters. 5 | 6 | **For the WebPlayer build you need to add this code ** 7 | 8 | This is not included because it troubles the normal machines builds. 9 | 10 | - [Chapter 1](#chapter-1-user-accessible-variables-and-functions): User accessible variables and functions 11 | - [Chapter 2](#chapter-2-explanation-of-all-the-variables-and-functions-used-in-the-script): Explanation of the script variables and functions (how the script works). 12 | - [Chapter 3](#chapter-3-examples): Examples. 13 | - [Chapter 4](#chapter-4-webplayer-setup): WebPLayer setup. 14 | 15 | - Newest video tutorial: 16 | - Webplayer tutorial: 17 | - Older video tutorial: 18 | 19 | ### Functionality Overview 20 | 21 | 1. This script allows you to call information from a selected microphone. 22 | 2. The script can detect every microphone attached. 23 | 3. There is a GUI function to select the microphone ingame. 24 | 4. The script finds the volume of sound going through ONLY the microphone. 25 | 5. The volume of the AudioSource directly affects the loudness variable (can be set in script. 26 | 6. If only 1 microphone is connected, that device is made default. 27 | 7. Can call the input loudness from outside the script. 28 | 8. Create a GUI from any script with a build in gui function. 29 | 30 | A script that allows you to call information from the computers microphone from any script. 31 | 32 | - It can recognize up to six different mic's. 33 | - The user can set the Sensitivity and choose to show debug information. Furthermore is it possible to print the device number and name of all mic's into the console, this way the user knows which slot to select for streaming, then the script knows to which device it should listen. 34 | - The maximum spectrum data that gets streamed is by default 256, there is no need to change this value unless you really know what you are doing (increasing may cause performance issues). 35 | 36 | ## How To Setup 37 | 38 | 1. Place script on player or empty gameObject. Note: This has to be done in order to call it from any other script 39 | 2. Done 40 | 41 | Once placed on a player or empty gameObject all its public functions and variables can be called from any script. See the call functions below. 42 | 43 | 44 | ### [Chapter 1](Chapter-1): User accessible variables and functions 45 | 46 | All of these functions can be called from external Java or C# scripts. 47 | 48 | #### Main function 49 | **MicControl.loudness;** 50 | [This call's the volume data from your microphone in any script and converts it to the loudness value.] 51 | 52 | #### Sub functions 53 | **MicControl.StartMicrophone();** 54 | [This will force the microphone to start recording when called from an external script or a custom mod script that detects microphones.] 55 | 56 | **MicControl.StopMicrophone();** 57 | [This will force stop the microphone from anything recording/listening. This is useful when your player dies and is not allowed to use the MicControl functions anymore.] 58 | 59 | **MicControl.MicDeviceGUI (left:float , top:float, width:float, height:float, buttonSpaceTop:float, buttonSpaceLeft:float)**: This lets you create a GUI element which you can use to give you a selection of the different microphones. Both buttonSpaceTop and buttonSpaceLeft need to be, the left or top, add the space you want between each button. 60 | 61 | 62 | ### [Chapter 2](Chapter-2): Explanation of all the variables and functions used in the script 63 | 64 | #### Public Variables 65 | > All variables shown in the editor are to control the input volume/data (you cannot edit the audio, only use it as a control value). 66 | 67 | - **SelectIngame:** With this variable you can decide if an ingame menu should show to select your microphone or not. If not selected it will use the default microphone, unless changed in the editor slot. 68 | 69 | - **ThreeD:** This will enable/dissable the 3D audio function. Note that a Microphone can only be 2D and that this effect is achieved by dynamically altering of the AudioSource volume through scripting. 70 | 71 | - **VolumeFallOff:** This component will be unlocked when ThreeD is active. Since the the microphone can only handle 2D audio (as mentioned above), the 3D effect is mimiced by dynamically altering the volume, with the VolumeFallOff parameter you can set how heavy this effect is. A lower value means the audio can be heard from a greater distance and a higher value means it will dissapear much faster. 72 | 73 | - **PanThreshold:** This component will be unlocked when ThreeD is active. As with VolumeFallOff this creates another part of the 3D illusion. This value will determine how smooth the transition from the left speaker to the right speaker will be. 74 | 75 | - **InputDevice:** Select the microphone you want to use (supported up to 6 to choose from). If the device has number 1 in the console, you just select default as it is the first device to be found. 76 | 77 | - **audioSource:** Here the script will place its AudioSource, which it generates by itself. 78 | 79 | - **amountSamples:** 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. 80 | 81 | - **sensitivity:** How sensitive should the input be? 0 will detect nothing, a higher number will give a bigger loudness value. 82 | 83 | - **sourceVolume:** How load should the script receive my voice/Input? A lower value will result in a smaller loudness value. This also influence the hearable audio (from the microphone) ingame if turned on. 84 | 85 | - **Mute:** This values determine if the user can hear himself or not. With this the user could write a script for multiplayer. So that for himself the mute is on but for other players it is not, thus creating a push to talk (this is not Included in the script, as the script is created for input 'value's only). 86 | 87 | - **debug:** Writes the loudness value to the console, this can be used to see when higher pitches are used or whether the device is receiving input or not. 88 | 89 | - **ShowDeviceName:** When turned on the console will spit out each single device detected and its number. This can be used to find out which slot should be selected in the editor. 90 | 91 | 92 | #### Private Variables 93 | 94 | - **selectedDevice:** This refers to the slot in 'enum Devices' and should be left untouched. 95 | 96 | - **minFreq:** Both these values are used to detect the frequency of your device. If no frequency can be detected it will use a default of 44100. These values should be left untouched. 97 | 98 | - **maxFreq:** The maximum frequency to use. 99 | 100 | - **micSelected:** This value should be left untouched as it is only used to show the GUI of 'SelectIngame'. 101 | 102 | - **recording:** This value tells the script if the mic is streaming or not. 103 | 104 | - **ListenerDistance:** this value works together with VolumeFallOff to create the correct volume drop if the MicController source is farther away from the listerener. 105 | 106 | - **ListenerPosition:** this value works with PanThreshold to place the audio in the correct speaker. 107 | 108 | - **focused:** Here we have a very important piece, with this the MicController can detect if the application is in use or not. If not it will stop the stream when the application is not in use and restart/initialize the microphone when the aplication is back in use. This is very important as it prevents data lag (sound playing seconds to late) and keeps the stream 'realtime'. 109 | 110 | - **Initialised:** Checks if the microphone is initialized, if not it will do so. 111 | 112 | 113 | #### Static Variables 114 | 115 | - **loudness:** This value can be called from any script. It is read only and it gives you a single float value based on the input data (No actual audio). This can be used to create interactive objects or to change objects, basically everything that uses float values can be changed with this. 116 | 117 | Example: 118 | 119 | ``` 120 | transform.position.x = MicControl.loudness. 121 | ``` 122 | 123 | This will move the object over the X axis based on the input gathered from the microphone. 124 | 125 | 126 | #### Functions 127 | 128 | Create a standard gui button from any script that is automatically hooked up to the Microphone selection function. 129 | **public function MicDeviceGUI:** This creates a function to create microphone gui buttons on the fly. 130 | 131 | Called only inside the script, do not touch or change anything in this function! It is it's core setup. 132 | **private function InitMic():** Sets up and initializes the microphone. 133 | 134 | Call these functions in external scripts to start or stop the microphone (not recommended as it may distort your data stream). 135 | **public functions StartMicrophone ():** This starts the listening of audio from your microphone. 136 | 137 | **public functions StopMicrophone ():** This stops the playing of audio from your microphone. 138 | 139 | **function OnApplicationFocus(focus: boolean):** This will switch the 'focused' boolean to true if the application is active. 140 | 141 | **function OnApplicationPause(focus: boolean):** This will switch the 'focused' boolean to false if the application is not active. 142 | 143 | 144 | ### [Chapter 3](Chapter-3): Examples 145 | 146 | This example will scale an object based on the values received trough the microphone. The object will scale with the strength of your voice. 147 | 148 | ``` 149 | void Update(){ 150 | Vector3 Scale = Vector3(1,MicControl.loudness,1); 151 | transform.localScale = Scale; 152 | } 153 | ``` 154 | 155 | This script will force shut down the selected microphone on start of the level and then proceeds to start it up again, this can be used on a respawn. 156 | 157 | ``` 158 | void Start(){ 159 | //stop current mic 160 | MicControl.StopMicrophone(); 161 | //start fresh input. 162 | MicControl.StartMicrophone(); 163 | } 164 | 165 | //create a gui button that selects a microphone 166 | MicControl.MicDeviceGUI(400, 100, 300, 100, 110, 0); 167 | ``` 168 | 169 | 170 | ### [Chapter 4](Chapter-4): WebPlayer Setup 171 | 172 | To use this script in the web player do not switch the platform to webplayer mode! As of this writing 31-07-2014 the unity editor crashes when initializing the microphone in the editors 'webplayer' playmode. 173 | 174 | Instead setup your microphone script trough the standalone build platform (PC, Mac, Linux). These modes will correctly initialize the microphones. When your script is setup to your likings and all the other scripts that call to your script are working as they should do. Build to the webplayer and open the html link generated by Unity to view your webplayer build. In here you will now see a request to use your mic, accept it and there you go a functional microphone control inside your web player. 175 | 176 | Webplayer Tutorial: 177 | 178 | 179 | ## Contributors 180 | 181 | - Mark Duisters 182 | 183 | 184 | 185 | --------------------------------------------------------------------------------