Search code examples
iosunity-game-enginemicrophone

Unity Microphone.End() mutes all game audio on iOS


This happens if iPhone silent mode is on. I have a button that records the microphone in the game. When the game starts background music and SFX play just fine. When I stop recording, all game audio is muted until I turn iPhone silent mode off. There is no problem if silent mode was off to begin with.

HERE ARE THE FUNCTIONS:

public void RecordAudio()
{
    recordedClip = Microphone.Start(null, false, 20, 44100);
}

//the audio gets muted when I run this.

public void StopRecordingAudio()
{

    tempPath = Path.Combine(Application.persistentDataPath, "Audio");
    tempPath = Path.Combine(tempPath, "audio_clip.wav");
    Microphone.End(null);
    SaveWav.Save(tempPath, recordedClip);

}

I am using this to save the audio clip.


Solution

  • The solution is to check Prepare iOS For Recording and Force iOS Speakers Speakers When Recording in Player Settings/iOS.

    Checking Prepare iOS For Recording caused a different error where the microphone failed to initialize. This is fixed by adding the following to UnityViewControllerBase.mm in the Xcode Project/Classes/UI in (void)viewWillAppear;

    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
             [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
             [audioSession setActive:YES error:nil];
    

    Don't forget: #import "AVFoundation/AVFoundation.h"

    There's also a bug in Unity that forces audio to play from the earpiece even if you check Force Speakers when Recording in Player Settings. This only happens when you check Prepare iOS For Recording. The issue can be tracked here at Unity Issue Tracker. I used this GitHub project as a temporary fix for that even though it's quite old but works - in the meantime as Unity fixes the bug.

    EDIT: I am using Unity 2021.3.9f1 LTS now and can confirm that it doesn't have the bug.