There are a lot of sensors on the Windows Phone. We’ve got:
- GPS Location
- Camera (front & back)
- Gyroscope / Accelerometer
- Magnetometer / Compass
I suppose we could also say the touch panel is a sensor, but it is so ubiquitous that we just assume it’s there anymore – yes, it’s that world we live in now, the “of course it’s touch enabled” world. Wonderful.
But how do you use the Microphone?
The Windows Phone microphone is in the Microsoft.Xna.Framework.Audio namespace. This means in order to access the microphone, you need to add a reference to Microsoft.Xna.Framework. Easy enough, I know – but you definitely have to do it.
The microphone is a mono input device. To “listen” with the microphone, you Start() the microphone and fill its buffer. Then while handling the BufferReady event, you read the buffer and append it to some stream (like a MemoryStream). It’s the stream that contains the audio; it’s the stream you can save to a file. The microphone’s state will remain Started until you call Stop().
In the video linked above, we build a full application that will record from the microphone and play back whatever you record. (I know in the video you cannot hear the playback but it worked!)
Note: One important part of the code in the video is calling the FrameworkDispatcher.Update() method. This method is called automatically in XNA game classes. However, this is a Silverlight class so we must call it manually. The purpose of the method is to dispatch events that update XNA components and bring them to a ready (or other) state – this includes the microphone. 33 milliseconds is a recommended tick value.
You can get the raw code from the video here.
Building an application in Windows Phone is fast. The pieces you need are at arms reach, and the necessary plumbing is mostly built for you. The microphone is another way to let your user interact with your application – and another way to bring value from your application – and another way to fight against the UNINSTALL button. It may be simple, but is is very powerful.
Warning: every application on the Windows Phone has a memory limit of 90MB. As you are putting the chunks of sound into a MemoryStream (for example) be sure and anticipate if your application hits its memory threshold. Do you need to cache to disk (here’s how)? You are developer, you need to decide. But, in any case, plan for the worst scenario.
Best of luck!