How to use Microphone in XNA

Microphone support is new in XNA 4.0.It helps you to use Microphone in your games which adds interactivity in my opinion.But there isnt any example made using XNA so we will be using one of the Silverlight examples I have found on PeteOnSoftware(special thanks to Pete by the way)

Now we will be using it Step-By-Step by explaining how to do it:

First of all lets create a new project:

1.gif 

Now add these namespaces on your project:

using System.IO;
using System.IO.IsolatedStorage;

Yes we are using IsolatedStorage.Know that its not only used in Silverlight!

Then add a byte array to read from the Microphone:

byte[] bffr;

Add a MemoryStream:

MemoryStream stream;

Add a filename constant and a Microphone class:

private const string FILE_NAME = "xna.ibo";
private Microphone mc = Microphone.Default;

using mc variable we will access our Default plugged-in or integrated-on-device Microphone and using FileName we will save it on IsolatedStorage to access later.

Update your Game1 Constructor as seen below:

public Game1()
{
  graphics = new GraphicsDeviceManager(this);
  Content.RootDirectory = "Content";
  mc.BufferDuration = TimeSpan.FromSeconds(1); 
  bffr = new byte[mc.GetSampleSizeInBytes(mc.BufferDuration)];
  mc.BufferReady += handleBufferReady;
}

We are storing an array that defines our Microphone BufferDuration

Add an event we declared previously:

private void handleBufferReady(object sender, EventArgs e) 
{ 
  mc.GetData(bffr); 
  stream.Write(bffr, 0, bffr.Length); 
}

Here when the buffer is ready to record from microphone we are storing the bytes in our byte array named 'bffr'.Then write it on our MemoryStream.

Update your Initialize function as seen below:

protected override void Initialize()
{
  base.Initialize();
  stream = new MemoryStream(); 
  mc.Start();
}

Here when first the game run,we are creating a new instance of Memory Stream then starting our Microphone class.

Update Function will be like that:

protected override void Update(GameTime gameTime)
{
    KeyboardState stat = Keyboard.GetState();
    if(stat.IsKeyDown(Keys.Escape))
    {
        mc.Stop(); 
        writeFile(stream);
    }
    else if (stat.IsKeyDown(Keys.Space))
    {
        using (var userStore = IsolatedStorageFile.GetUserStoreForApplication()) 
        { 
            if (userStore.FileExists(FILE_NAME)) 
            { 
                var file = userStore.OpenFile(FILE_NAME, FileMode.Open, FileAccess.Read); 
                var bytes = new byte[file.Length]; 
                file.Read(bytes, 0, bytes.Length); 
                playFile(bytes); 
            } 
        }
    }
    base.Update(gameTime);
}

All right what actually we here do is when we press Escape button it will finish recording and save the buffer to our xna.ibo file.And when we press Space key it will play as a sound! Now that we used IsolatedStorage here in which you dont know the location of the file!

Lastly add 2 functions named WriteFile and PlayFile which interacts with IsolatedStorage

private void writeFile(MemoryStream s)
{
    using (var userStore = IsolatedStorageFile.GetUserStoreForApplication())
    {
        if (userStore.FileExists(FILE_NAME))
        {
            userStore.DeleteFile(FILE_NAME);
        }
        using (var file = userStore.OpenFile(FILE_NAME, FileMode.CreateNew))
        {
            s.WriteTo(file);                   
        }
    }
}
private void playFile(byte[] file) 
{ 
    if (file == null || file.Length == 0) return;  
    var se = new SoundEffect(file, mc.SampleRate, AudioChannels.Mono); 
    SoundEffect.MasterVolume = 0.7f; 
    se.Play(); 
} 

Ok. Everything is right.So lets run it and see what happens

2.gif 

We got "Unable to determine application identity of the caller" error in IsolatedStorageException.

The solution of this exception is: To Publish Your Xna Game! And you will be free to use IsolatedStorage.

3.gif
 
Choose Publish; a new Window will come.Just make Next...Finish! :)

It will publish it and a new Explorer Window will come. 

4.gif 

There run setup file and examine microphone there;

Say something on Microphone.When finished Press "ESCAPE" to run the sound you just spoke there Press "SPACE" key.

You will just hear what you have said :)

Making this way you have successfully imported Microphone support on XNA 4.0!

Well Done!

Hope to see you in our next articles!

Cheers

Up Next
    Ebook Download
    View all
    Learn
    View all
    Araf Global is a software consultancy company founded in 2016 focusing on cutting edge technologies.