6
\$\begingroup\$

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?

\$\endgroup\$
2
  • \$\begingroup\$ Are you already aware of the Microphone class? \$\endgroup\$
    – Philipp
    Dec 8, 2017 at 17:17
  • \$\begingroup\$ I looked at the Microphone class, but it seems to me that it is only capable of recording AudioClips. \$\endgroup\$
    – xuwenbuwer
    Dec 8, 2017 at 17:19

1 Answer 1

4
\$\begingroup\$

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)
            }
        }
    }
}
\$\endgroup\$
1
  • \$\begingroup\$ 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? \$\endgroup\$
    – Stephan
    Dec 8, 2017 at 17:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .