- Home /
Unity 5 and using a microphone
Hey everyone, been losing my mind with this. What I'm trying to do is have the player hold the space button, and while its being held his voice is recorded. So as soon as the player lets go of space, that ends the recording, and the resulting audio clip is of the length that the player held the space button. This clip will then be used to analyze the volume vs. a set value, but for now I simply cannot figure out how to get this recording to work. The Microphone.Start function specifically wants an int value for length of recording. Any help would be greatly appreciated, as information on this topic seems rather sparse. Thanks in advance!
Answer by zach-r-d · Jul 25, 2015 at 01:40 PM
Unfortunately, the only way to do this with the current API is a huge pain since resizing AudioClips isn't allowed:
When space is pressed, call Microphone.Start(), passing some maximum length of time for a recording as the length. Start a real-time timer of some sort.
When space is released, call Microphone.End(), and stop the timer.
If the maximum length was reached, use it as is. Otherwise, continue on:
Create a new array of size clip.frequency*clip.channels*realTimedSeconds.
Call GetData() on the clip with the array and an offset of 0.
Create a new AudioClip using AudioClip.Create with the same sample rate and number of channels, and with number of samples equal to the length of the array.
Call SetData() on the new clip with the array and an offset of 0.
Destroy the old clip.
Return the new clip.
Tested with 5.1.2f1.
Thank you so much for your answer! It's a shame all this microphone stuff is such a mess in Unity :/ Would you by any chance know how the check the dB of the created audio clip? The goal is to have the player scream something and check how loud it is compared to "x" value? I suppose the GetOutputData might have something to do with it but I'm completely lost :/
For that, it's probably best to just use the array with all the sample data in it acquired with GetData. $$anonymous$$ight not even need to create the second clip at all unless it's going to be played back later. The floats in the array are in the range [-1,1] and operate basically on a linear volume scale, so a sample at -1 OR 1 is at -0 dB, whereas a sample at 0 is at -inf dB. I'm not entirely sure how to convert between linear and dB, though.
But it could be that linear volume works for your needs, anyway. Try looping through the array to find the maximum value of a sample. It'll be between 0 and 1. 0 means perfect silence, 1 means the maximum volume the mic can handle without clipping.
Your answer
Follow this Question
Related Questions
Delay with Microphone.Start 1 Answer
Guys i need help with audio! 0 Answers
Voice Recording issue ?? 0 Answers
Microphone Failed Result=33 0 Answers