Search Unity

Audio Having issues with the microphone not recording anything.

Discussion in 'Audio & Video' started by slykrooper, Sep 14, 2020.

  1. slykrooper

    slykrooper

    Joined:
    Oct 27, 2018
    Posts:
    10
    So i'm trying to get the microphone to record and play back sound to me while the game is playing. After a little bit of research I found some code online that does exactly that! But for whatever reason no audio is played back to me no matter what I change, no errors pop up either. If anybody could give me possible recommendations on how to fix this id greatly appreciate it. ill include the code below.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class MicrophoneTest : MonoBehaviour
    6. {
    7.     AudioClip clip;
    8.     AudioSource aud;
    9.     private bool micConnected = false;
    10.     private int minFreq;
    11.     private int maxFreq;
    12.  
    13.     // Start is called before the first frame update
    14.     void Start()
    15.     {
    16.         if(Microphone.devices.Length <= 0)
    17.         {
    18.             Debug.LogWarning("Microphone Not Connected!");
    19.         }
    20.         else
    21.         {
    22.             micConnected = true;
    23.  
    24.             Microphone.GetDeviceCaps(null, out minFreq, out maxFreq);
    25.  
    26.             if(minFreq == 0 && maxFreq == 0)
    27.             {
    28.                 maxFreq = 44100;
    29.             }
    30.  
    31.             aud = this.GetComponent<AudioSource>();
    32.         }
    33.     }
    34.  
    35.     void OnGUI()
    36.     {
    37.         if(micConnected)
    38.         {
    39.             if(!Microphone.IsRecording(null))
    40.             {
    41.                 if (GUI.Button(new Rect(Screen.width / 2 - 100, Screen.height / 2 - 25, 200, 50), "Record"))
    42.                 {
    43.                     aud.clip = Microphone.Start(null, true, 20, maxFreq);
    44.                 }
    45.             }
    46.             else
    47.             {
    48.                 if (GUI.Button(new Rect(Screen.width / 2 - 100, Screen.height / 2 - 25, 200, 50), "Stop and Play!"))
    49.                 {
    50.                     Microphone.End(null); //Stop the audio recording
    51.                     aud.Play(); //Playback the recorded audio
    52.                 }
    53.  
    54.                 GUI.Label(new Rect(Screen.width / 2 - 100, Screen.height / 2 + 25, 200, 50), "Recording in progress...");
    55.             }
    56.         }
    57.         else
    58.         {
    59.             GUI.contentColor = Color.red;
    60.             GUI.Label(new Rect(Screen.width / 2 - 100, Screen.height / 2 - 25, 200, 50), "Microphone not connected!");
    61.         }
    62.     }
    63.