Search Unity

Audio No microphone input on first run of the android app.

Discussion in 'Audio & Video' started by Nurdo, Jan 4, 2024.

  1. Nurdo

    Nurdo

    Joined:
    Apr 19, 2014
    Posts:
    2
    Hello, i have a problem.
    I'm working on a decibel meter app for android.
    So it needs to use the mic of the android device. I did add the uses permission RECORD_AUDIO in the androidmanifest.xml file.
    The first (clean) install on my phone, the mic request works, but the microphone is not starting. Now when i exit and start the app again, the microphone works. This is the script i'm using:

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.Android;
    3. using System.Collections;
    4.  
    5. public class DecibelMeter : MonoBehaviour
    6. {
    7.     private AudioClip recordedClip;
    8.     private AudioSource audioSource;
    9.     private bool isRecording = false;
    10.  
    11.     IEnumerator Start()
    12.     {
    13.         // Check if a microphone is available
    14.         if (Microphone.devices.Length == 0)
    15.         {
    16.             Debug.LogError("No microphone detected.");
    17.             yield break;
    18.         }
    19.  
    20.         // Request and check microphone permissions
    21.         RequestMicrophonePermission();
    22.         yield return StartCoroutine(WaitForMicrophonePermission());
    23.  
    24.         Debug.Log("Microphone access granted.");
    25.  
    26.         // Add an AudioSource component to this GameObject
    27.         audioSource = gameObject.AddComponent<AudioSource>();
    28.  
    29.         // Wait for a short delay before proceeding
    30.         yield return new WaitForSeconds(1);
    31.  
    32.         // Start recording
    33.         StartRecording();
    34.     }
    35.  
    36.     void RequestMicrophonePermission()
    37.     {
    38.         if (!Permission.HasUserAuthorizedPermission(Permission.Microphone))
    39.         {
    40.             Permission.RequestUserPermission(Permission.Microphone);
    41.         }
    42.     }
    43.  
    44.     IEnumerator WaitForMicrophonePermission()
    45.     {
    46.         // Wait until the user grants or denies permission
    47.         while (!Permission.HasUserAuthorizedPermission(Permission.Microphone))
    48.         {
    49.             yield return null;
    50.         }
    51.     }
    52.  
    53.     // Start recording audio (changed to public)
    54.     public void StartRecording()
    55.     {
    56.         if (Microphone.IsRecording(null))
    57.         {
    58.             Debug.LogWarning("Already recording.");
    59.             return;
    60.         }
    61.  
    62.         int frequency = 44100; // Sample rate
    63.         int seconds = 10; // Maximum recording duration
    64.  
    65.         recordedClip = Microphone.Start(null, true, seconds, frequency);
    66.         isRecording = true;
    67.     }
    68.  
    69.     // Stop recording audio
    70.     public void StopRecording()
    71.     {
    72.         if (Microphone.IsRecording(null))
    73.         {
    74.             Microphone.End(null);
    75.             isRecording = false;
    76.         }
    77.         else
    78.         {
    79.             Debug.LogWarning("Not currently recording.");
    80.         }
    81.     }
    82.  
    83.     // Get the current decibel level and play the recorded audio
    84.     public float GetDecibelLevel()
    85.     {
    86.         if (isRecording && recordedClip != null)
    87.         {
    88.             float[] samples = new float[recordedClip.samples * recordedClip.channels];
    89.             recordedClip.GetData(samples, 0);
    90.  
    91.             float sum = 0f;
    92.  
    93.             foreach (float sample in samples)
    94.             {
    95.                 sum += Mathf.Abs(sample);
    96.             }
    97.  
    98.             // Calculate average amplitude
    99.             float averageAmplitude = sum / samples.Length;
    100.  
    101.             // Convert average amplitude to decibels
    102.             float dbValue = 20 * Mathf.Log10(averageAmplitude + Mathf.Epsilon);  // Add epsilon to prevent log of zero
    103.  
    104.             // Play the recorded audio if it's not already playing
    105.             if (!audioSource.isPlaying)
    106.             {
    107.                 audioSource.clip = recordedClip;
    108.                 audioSource.Play();
    109.             }
    110.  
    111.             return dbValue;
    112.         }
    113.  
    114.         return 0f; // Return 0 if not recording or no recorded audio
    115.     }
    116. }
    117. class DecibelMeter : MonoBehaviour
    118. {
    119.     private AudioClip recordedClip;
    120.     private AudioSource audioSource;
    121.     private bool isRecording = false;
    122.  
    123.     IEnumerator Start()
    124.     {
    125.         // Check if a microphone is available
    126.         if (Microphone.devices.Length == 0)
    127.         {
    128.             Debug.LogError("No microphone detected.");
    129.             yield break;
    130.         }
    131.  
    132.         // Request and check microphone permissions
    133.         RequestMicrophonePermission();
    134.         yield return StartCoroutine(WaitForMicrophonePermission());
    135.  
    136.         Debug.Log("Microphone access granted.");
    137.  
    138.         // Add an AudioSource component to this GameObject
    139.         audioSource = gameObject.AddComponent<AudioSource>();
    140.  
    141.         // Wait for a short delay before proceeding
    142.         yield return new WaitForSeconds(1);
    143.  
    144.         // Start recording
    145.         StartRecording();
    146.     }
    147.  
    148.     void RequestMicrophonePermission()
    149.     {
    150.         if (!Permission.HasUserAuthorizedPermission(Permission.Microphone))
    151.         {
    152.             Permission.RequestUserPermission(Permission.Microphone);
    153.         }
    154.     }
    155.  
    156.     IEnumerator WaitForMicrophonePermission()
    157.     {
    158.         // Wait until the user grants or denies permission
    159.         while (!Permission.HasUserAuthorizedPermission(Permission.Microphone))
    160.         {
    161.             yield return null;
    162.         }
    163.     }
    164.  
    165.     // Start recording audio (changed to public)
    166.     public void StartRecording()
    167.     {
    168.         if (Microphone.IsRecording(null))
    169.         {
    170.             Debug.LogWarning("Already recording.");
    171.             return;
    172.         }
    173.  
    174.         int frequency = 44100; // Sample rate
    175.         int seconds = 10; // Maximum recording duration
    176.  
    177.         recordedClip = Microphone.Start(null, true, seconds, frequency);
    178.         isRecording = true;
    179.     }
    180.  
    181.     // Stop recording audio
    182.     public void StopRecording()
    183.     {
    184.         if (Microphone.IsRecording(null))
    185.         {
    186.             Microphone.End(null);
    187.             isRecording = false;
    188.         }
    189.         else
    190.         {
    191.             Debug.LogWarning("Not currently recording.");
    192.         }
    193.     }
    194.  
    195.     // Get the current decibel level and play the recorded audio
    196.     public float GetDecibelLevel()
    197.     {
    198.         if (isRecording && recordedClip != null)
    199.         {
    200.             float[] samples = new float[recordedClip.samples * recordedClip.channels];
    201.             recordedClip.GetData(samples, 0);
    202.  
    203.             float sum = 0f;
    204.  
    205.             foreach (float sample in samples)
    206.             {
    207.                 sum += Mathf.Abs(sample);
    208.             }
    209.  
    210.             // Calculate average amplitude
    211.             float averageAmplitude = sum / samples.Length;
    212.  
    213.             // Convert average amplitude to decibels
    214.             float dbValue = 20 * Mathf.Log10(averageAmplitude + Mathf.Epsilon);  // Add epsilon to prevent log of zero
    215.  
    216.             // Play the recorded audio if it's not already playing
    217.             if (!audioSource.isPlaying)
    218.             {
    219.                 audioSource.clip = recordedClip;
    220.                 audioSource.Play();
    221.             }
    222.  
    223.             return dbValue;
    224.         }
    225.  
    226.         return 0f; // Return 0 if not recording or no recorded audio
    227.     }
    228. }
    Unity 2019.4
    Btw. It does work immidiately in unity Editor.
    Can someone help me out?
    What am i doing wrong?
    And yes, i'm a noob.
     
  2. SeventhString

    SeventhString

    Unity Technologies

    Joined:
    Jan 12, 2023
    Posts:
    410
    [mmm... déjà vu...]

    I've experienced this myself but didn't have much time to get into it... mobile permission stuff can be super tricky.

    You could try to stop/start the microphone in `StartRecording()` by calling `Microphone.End(null);` before `Microphone.Start(...);`.

    Also, instead of a second corountine polling for when the permission has been granted, your could try using the PermissionCallbacks.