- Home /
How to use the Microphone class to record multiple AudioClip's
I have an iOS application and I want to let the user record audio whenever they push a button, and stop recording on a second press. I don't know if I'm using the Microphone class correctly, but there isn't any detailed information about it on the documentation page. My code is as follows:
public static class MicRecorder
{
public static AudioClip StartRecording(string deviceName = null)
{
var audioClip = UnityEngine.Microphone.Start(deviceName, true, 15, 44100);
while (UnityEngine.Microphone.GetPosition(deviceName) <= 0) ;
return audioClip;
}
public static void StopRecording(string deviceName = null)
{
UnityEngine.Microphone.End(deviceName);
}
}
The first time I press the button, the audio clip turns out fine. However, after I stop recording and then press the button again, I get an error with message:
Starting Microphone failed. result=70 (An error occured trying to initialize the recording device. )
I searched for this error code but no one seems to have gotten it, or asked about it anywhere.
What is the correct way to use the Microphone API? Should Microphone.Start() be called just once in the lifecycle of my app? If so, how can I create multiple AudioClip's?
Edit: So I searched around a bit more and turns out this error comes from FMOD, the audio engine Unity uses. Unfortunately, it's not an open source project, so I don't know what causes this error.
Answer by halilkayim · Jun 04, 2018 at 07:38 AM
The problem seems to be gone after unchecking Prepare iOS for Recording in Player Settings.
EDIT: This is a really bad solution. If this setting is unchecked, the error goes away, but every time you use Microphone.Start()
and Microphone.Stop()
, a significant overhead (0.5 ms for me on iPhone SE, iOS 11.3) is added to the drawing of the frame at that instant, because iOS needs to prepare itself for recording every time.
To handle this error in a much better way, you do need to check Prepare iOS for Recording in Player Settings and call
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord)
from the native side of your application before using any Microphone API on the Unity side.