The XNA Framework libraries make the Microphone available programmatically to applications. Add a reference to Microsoft.Xna.Framework assembly and a using clause for the Microsoft.Xna.Framework.Audio. The class of interest is the Microphone class that provides access to available microphones on the device.
The audio produced by the Microphone is 16-bit raw PCM. The audio can be played using the SoundEffect object without issue. To play recorded audio in a MediaElement control, the raw audio needs to be put into a .wmv file format.
For the sample project named MicrophoneWithSilverlight in the Ch03_HandlingInput_Part2 solution file the code uses the SoundEffect object to playback the audio.
App.xaml.cs is modified to include the XNAAsyncDispatcher class and add an instance to this.ApplicationLifetimeObjects.
With the boiler code in place, the application builds out a simple UI
to record, stop, and play microphone audio. A slider is configured as a
pitch selector so that you make your voice sound like Darth Vader or a
Chipmunk. Figure 1 shows the UI.
Listing 1 shows the source code.
Example 1. MainPage.xaml.cs Code File
using System;
using System.IO;
using System.Windows;
using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework.Audio;
namespace MicrophoneWithSilverlight
{
public partial class MainPage : PhoneApplicationPage
{
Microphone microphone = Microphone.Default;
MemoryStream audioStream;
// Constructor
public MainPage()
{
InitializeComponent();
microphone.BufferReady +=
new EventHandler<EventArgs>(microphone_BufferReady);
SoundEffect.MasterVolume = 1.0f;
MicrophoneStatus.Text = microphone.State.ToString();
}
void microphone_BufferReady(object sender, EventArgs e)
{
byte[] audioBuffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = microphone.GetData(audioBuffer, 0, audioBuffer.Length)) > 0)
audioStream.Write(audioBuffer, 0, bytesRead);
MicrophoneStatus.Text = microphone.State.ToString();
}
private void recordButton_Click(object sender, RoutedEventArgs e)
{
if (microphone != null)
microphone.Stop();
audioStream = new MemoryStream();
microphone.Start();
MicrophoneStatus.Text = microphone.State.ToString();
}
private void stopRecordingButton_Click(object sender, RoutedEventArgs e)
{
if (microphone.State != MicrophoneState.Stopped)
microphone.Stop();
audioStream.Position = 0;
MicrophoneStatus.Text = microphone.State.ToString();
}
private void playButton_Click(object sender, RoutedEventArgs e)
{
SoundEffect recordedAudio =
new SoundEffect(audioStream.ToArray(), microphone.SampleRate,
AudioChannels.Mono);
recordedAudio.Play(1f, (float)pitchSlider.Value, 0f);
}
}
}
|
With the Microphone class, developers can create fun applications that allow a user to record and playback recorded audio with pitch modifications.