It’s fairly easy to record PCM audio data directly from the phone’s microphone in Windows Phone 7, but there are a few things to remember.
Firstly, the phone runs Silverlight 3. Audio recording support only came to Silverlight in version 4, so there is no direct support for it in WP7 Silverlight apps. The good news is that XNA does support recording audio for games, and we can still make use of the XNA libraries even though we’re in Silverlight.
So start by adding a reference to:
Microsoft.Xna.Framework
Then add a using statement for
using Microsoft.Xna.Framework.Audio;
Once this is done you can use the Microphone.Default class to begin recording audio, by handling the BufferReady event. The BufferReady event fires when ever the buffer has been filled with audio data.
Since our buffer duration here is 300ms the BufferReady event will fire every 300ms. This can be adjusted as required. There is still a problem however. If you run the code above as is you will get this helpful FrameworkDispatcher.Update has not been called exception. http://cisforcoder.files.wordpress.com/2010/08/image_thumb1.png?w=321&h=225
This is because unlike Silverlight, the XNA framework is not event driven. It is built for games and rather than using eventing as Silverlight does, games implement what is called a ‘game loop’, where the game is essentially operates in an infinite while loop. What does this mean? It means we need to mimic the game loop in our Silverlight application in order to use some of the XNA framework APIs. Fortunately this is easy enough, we can simply set up a timer to periodically tell XNA to update, just as it would with each iteration of a game loop. Here is anXNAAsyncDispatcher class takes care of this for us.
public class XNAAsyncDispatcher : IApplicationService
This class implements a service which will mimic the game loop for XNA and tell the framework to update itself periodically. To use this class simply add an instance of it to the phone appsApp.ApplicationLifetimeObjects collection in the App constructor as follows
You can even test your code using the emulator, as it supports recording through the host PC’s microphone input, although, in Beta1 at least, the results are a bit choppy.