- Home /
Question by
kimn_unity · Jun 28, 2021 at 05:12 PM ·
scripting problemscripting beginnersoundmicrophone
How can i find loudness of microphone from code? (code not working)
I followed a tutorial on how to move an object by your voice and there is this line of code which is important that doesn't work. Whats the problem? video
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class gun : MonoBehaviour
{
public float sensitivity = 100;
public float loudness = 0;
AudioSource _audio;
public float damage = 10f;
public float range = 100f;
public float force = 700f;
public GameObject hitEffect;
public ParticleSystem muzzle;
public Camera fpsCam;
private 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();
}
// Update is called once per frame
void Update()
{
loudness = Volume() * sensitivity;
if (loudness > 9)
{
Shoot();
}
}
void Shoot()
{
muzzle.Play();
RaycastHit hit;
if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range))
{
Debug.Log(hit.transform.name);
}
if (hit.rigidbody != null)
{
hit.rigidbody.AddForce(-hit.normal * force);
}
Instantiate(hitEffect, hit.point, Quaternion.LookRotation(hit.normal));
}
float Volume()
{
float[] data = new float[256];
float a = 0;
_audio.GetOutputData(data, 0);
foreach (float s in data)
{
a += Mathf.Abs(s);
}
}
}
Comment
Answer by kimn_unity · Jun 28, 2021 at 05:15 PM
also the line that doesn't work is
float Volume()
{
float[] data = new float[256];
float a = 0;
_audio.GetOutputData(data, 0);
foreach (float s in data)
{
a += Mathf.Abs(s);
}
}
Answer by Gearmaster_ · Jun 28, 2021 at 05:18 PM
@kimn_unity try this idk https://www.youtube.com/watch?v=GHc9RF258VA
Your answer
Follow this Question
Related Questions
Problem Using Microphone Input to Control Player 1 Answer
How would i trigger sound on collision? 1 Answer
Is there a way to see what scripts are no longer being used in a Unity2D project? 0 Answers
AudioSource.PlayClipAtPoint creating unlimited AudioOneShot 1 Answer
The volume does not reduce when master volume is lowered using volume slider 3 Answers