Tommy Naidich
Tommy Naidich

Reputation: 762

Check For Microphone Input

I'm trying to figure out how can I test an input coming from a connected microphone, in order to see if it has passed a certain level of volume, using C#.

I've heard about NAudio but all I could find in its examples and demos is tools which record the user and then save the recording into a file, which can be tested later on. That's not quite what I'm looking for if to be honest.

Upvotes: 1

Views: 1787

Answers (1)

Rod Chen
Rod Chen

Reputation: 522

you can record voice when it exceeds a given volume by modifying function waveIn_DataAvailable in this

bool startRecording = false;
void waveIn_DataAvailable(object sender, WaveInEventArgs e)
{
    for (int index = 0; index < e.BytesRecorded; index += 2)
    {
        short sample = (short)((e.Buffer[index + 1] << 8) | 
                            e.Buffer[index + 0]);
        float sample32 = sample / 32768f;
        if (sample32 > 0.2)  //0.2 is desired volume; sample32 is 0~1
        {
            // Start recording
            startRecording = true;
        }            
    }
    if (startRecording)
    {
        waveFile.Write(e.Buffer, 0, e.BytesRecorded);
        waveFile.Flush();
    }
}

startRecording is a flag indicates input voice has exceeded given volume, so we start writing data to wave file.

Upvotes: 3

Related Questions