# How to get the loudness of the real world environment using the device's microphone in Unity?

I am trying to create a game where the character's movement is dependent on the loudness of the real world environment. So if the person playing the game screams or do something loud the character will move accordingly.

What I need is a function returning the loudness of the real world environment and use it in the Update() to control the character.

Is there such a function or if not how can I make one?

• Are you already aware of the Microphone class? – Philipp Dec 8 '17 at 17:17
• I looked at the Microphone class, but it seems to me that it is only capable of recording AudioClips. – IronPig Dec 8 '17 at 17:19

As mentioned by Philipp, The Microphone class is indeed what you want to use.

The AudioClip that it produces is your audio buffer. When you call the Microphone.Start() method, you are opening the connection to the physical microphone, and the AudioClip is where the input is stored for you to access the sounds.

The Microphone.Start() method has a parameter loop which tells the Microphone to continue recording over the beginning of the AudioClip when the lengthSec is reached.

So as a quick and dirty example:

using UnityEngine;
using System.Collections;

public class MicrophonePoll : MonoBehavior {
private AudioClip clip;
private float[] samples;

void Start()
{
//Start recording 1 second blocks of audio from the default microphone, and loop the recording
clip = Microphone.Start(null,true,1,44100);
}

void Update()
{
if(clip!=null)
{
//Sample from the AudioClip to determine how loud the room was over the last second of recording
if(samples == null)
{
samples=new float[clip.samples*clip.channels];
}
clip.GetData(samples,0);
foreach(float sample in samples)
{
//do something with the value (ranges from -1.0f to 1.0f)
}
}
}
}

• I need help to improve this answer, and im away from a machine where i can test this. Will the Microphone continue to overwrite the buffer indefinitely, or dose the line in OnStart need to be moved to Update? – Stephan Dec 8 '17 at 17:44