Reputation: 109
My purpose is just to get the voice input level
I searched and found this code - but it always return 0 whatever my voice input level - I keep shouting , but always return 0
here's the code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class mic : MonoBehaviour {
public float sens = 100;
public float loud = 0;
AudioSource audio;
void Start()
{
audio = GetComponent<AudioSource> ();
audio.clip = Microphone.Start (null, true, 10, 44100);
audio.loop = true;
audio.mute = true;
while (!(Microphone.GetPosition (null) > 0)) {}
audio.Play ();
}
void Update()
{
loud = GetAvgVol () * sens;
Debug.Log (loud); //always debug 0
}
float GetAvgVol()
{
float [] data = new float[256];
float a = 0;
audio.GetOutputData (data, 0);
foreach(float s in data)
{
a += Mathf.Abs (s);
}
return a / 256;
}
}
how to achieve my purpose inside unity?
Upvotes: 2
Views: 1002
Reputation: 125415
Assuming there are no errors thrown by Unity in the Editor, these are the reasons why AudioSource.GetOutputData
may return 0:
1.The AudioSource
volume is set 0
.
For example, AudioSourceInstance.volume = 0
.
2.The AudioSource
is muted is set true
.
For example, AudioSourceInstance.mute = true;
3.There is no audio playing in the AudioSource.
For example, AudioSourceInstance.Play ()
is not called, AudioSourceInstance.Pause()
is called or AudioSourceInstance.Stop()
has been called on that AudioSource
.
4.The audio file or mic is silent.
In your case, the cause is #2.
If you just want to capture data from the mic without playing it back live then see this answer that mentioned two ways to do this
Also, I suggest you replace return a / 256;
with return a / 256f;
in your GetAvgVol
function.
Upvotes: 2
Reputation: 427
I'm not on a machine with unity at the moment but your input level seems like its fine.
The problem might be
audio.clip = Microphone.Start (null, true, 10, 44100);
You are setting the deviceName to NULL, try putting in a device name that you can discover with Microphone.devices
https://docs.unity3d.com/ScriptReference/Microphone-devices.html
Upvotes: 1