Aug 17

Recording Audio isn’t the most well documented part of the Windows Phone Tools beta  for Windows Phone 7 developers, mostly because you have to integrate both XNA and and Silverlight into your program solution.. There were also changes between earlier CTPs and the current betas..

XNA provides a Microphone class that you would almost think that it would be just  enough to work for you, but most people use Silverlight events (such as a button press event) so it is necessary to sync both of those to work together.

If you are a designer you might get a little lost in the documentation let’s try to make this a little easier for you..

Let’s look at what is necessary to make this work. This first code belongs in your App.xaml.cs file. First make sure these references are in your project..

Microsoft.Phone.dll

Microsoft.Xna.Framework.dll

mscorlib.dll

system.dll

System.Core.Dll

System.Net.dll

System.Windows.dll

System.Xml.dll

You also have to make sure that these references are also in your code..

using Microsoft.Xna.Framework;

using Microsoft.Xna.Framework.Audio;

using Microsoft.Xna.Framework.Media;

using System.Windows.Threading;

Note the XNA and threading options I have highlighted in blue..

Next we have to rev up the XNA dispatcher to get things in sync.. We do this in the code below using the ApplicationLifetimeObjects functionality of the application itself. Notice in the event handler code in the constructor as well..

 

public partial class App : Application
{
public App()
{
UnhandledException += new EventHandler<ApplicationUnhandledExceptionEventArgs>(Application_UnhandledException);

InitializeComponent();
this.ApplicationLifetimeObjects.Add(new XNAAsyncDispatcher(TimeSpan.FromMilliseconds(50)));
}

 

Next we need to put in the code to handle the XNA dispatcher..

 

public class XNAAsyncDispatcher : IApplicationService
{
private DispatcherTimer frameworkDispatcherTimer;

public XNAAsyncDispatcher(TimeSpan dispatchInterval)
{
this.frameworkDispatcherTimer = new DispatcherTimer();
this.frameworkDispatcherTimer.Tick += new EventHandler(frameworkDispatcherTimer_Tick);
this.frameworkDispatcherTimer.Interval = dispatchInterval;
}

void IApplicationService.StartService(ApplicationServiceContext context)
{
this.frameworkDispatcherTimer.Start();
}
void IApplicationService.StopService()
{
this.frameworkDispatcherTimer.Stop();
}
void frameworkDispatcherTimer_Tick(object sender, EventArgs e)
{
FrameworkDispatcher.Update();
}
}


After you have done this you should find no problems what so ever recording audio on devices or the emulator itself.. This was a huge issue and there was lack of information when I was initially working with this..

 

UPDATE:  If you want a great more complete example of this I recommend this one at the CESPAGE.com site.. They have a lot of great tutorial in the form of a Windows Audio Recorder sample with complete with a step by step walk through..

http://cespage.com/silverlight/wp7tut20.html