The XNA Microphone
class allows you to capture audio data from the phone’s microphone. Microphone
resides in the Microsoft.Xna.Framework.Audio namespace.
To use the Microphone
class you need to create a GameTimer
to pump the XNA FrameworkDispatcher
. XNA components usually rely on initialization of the XNA environment before they can be used, and the Microphone
class is no exception. Creating a GameTimer
to pump the XNA FrameworkDispatcher
normally involves adding some code to your App
class that creates a GameTimer
and subscribes to its FrameAction
event. For more information on initializing the XNA environment, see Chapter 7, “Employing Media and Web Elements.”
Microphone
does not have a public constructor; an instance is retrieved using the static Microphone.Default
property, as shown:
Microphone microphone = Microphone.Default;
Microphone
uses an event driven approach to periodically deliver audio data while it is recording. The Microphone.BufferReady
event is raised as soon as the Microphone
instance’s buffer is full. The size of the buffer is specified using the Microphone.BufferDuration
property, like so:
microphone.BufferDuration = TimeSpan.FromSeconds(1);
The Microphone.GetSampleSizeInBytes
can be used to determine the space requirements for reading the sample data when the BufferReady
event is raised.
int sampleSizeInBytes
= microphone.GetSampleSizeInBytes(microphone.BufferDuration);
This provides the opportunity to create a byte array for storing the sample bytes when the buffer has been filled:
byte[] buffer = new byte[sampleSizeInBytes];
The buffer can later be copied to a stream and saved in isolated storage, as shown:
void HandleBufferReady(object sender, EventArgs e)
{
microphone.GetData(buffer);
stream.Write(buffer, 0, buffer.Length);
}
The next section looks at putting this together to create a page that allows the user to record and play back audio.
13.59.92.234