using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Windows;
using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework.Audio;
namespace SoundRecorder
{
public partial class MainPage : PhoneApplicationPage
{
private Microphone mic = Microphone.Default;
private MemoryStream stream;
private const string FILE_NAME = "recording.ps";
byte[] buffer;
public MainPage()
{
InitializeComponent();
SupportedOrientations = SupportedPageOrientation.Portrait | SupportedPageOrientation.Landscape;
// Some necessary setup for our Microsoft.Xna.Framework.Audio.Microphone
mic.BufferDuration = TimeSpan.FromSeconds(1);
buffer = new byte[mic.GetSampleSizeInBytes(mic.BufferDuration)];
// Create the event handler. I could have done an anonymous
// delegate here if I had so desired.
mic.BufferReady += handleBufferReady;
}
/// This is called every "buffer duration" (in our case 1 second) and copies out what the mic has
/// in the buffer array to the memory stream.
private void handleBufferReady(object sender, EventArgs e)
{
mic.GetData(buffer);
stream.Write(buffer, 0, buffer.Length);
}
/// Initializes a new memory stream for new playtime. Starts the mic.
private void startButton_Click(object sender, RoutedEventArgs e)
{
stream = new MemoryStream();
mic.Start();
startButton.IsEnabled = false;
}
/// Stops the mic and writes out the file.
private void stopButton_Click(object sender, RoutedEventArgs e)
{
mic.Stop();
writeFile(stream);
startButton.IsEnabled = true;
}
/// Writes our the file, using isolated storage.
private void writeFile(MemoryStream s)
{
using (var userStore = IsolatedStorageFile.GetUserStoreForApplication())
{
if (userStore.FileExists(FILE_NAME))
{
userStore.DeleteFile(FILE_NAME);
}
using (var file = userStore.OpenFile(FILE_NAME, FileMode.CreateNew))
{
s.WriteTo(file);
playButton.IsEnabled = true;
}
}
}
/// Playing our file with another piece of the Xna Framework
private void playFile(byte[] file)
{
if (file == null || file.Length == 0) return;
var se = new SoundEffect(file, mic.SampleRate, AudioChannels.Mono);
SoundEffect.MasterVolume = 0.7f;
se.Play();
}
/// A play is requested. Get the file from isolated storage and send
/// its bytes to the playFile method.
private void playButton_Click(object sender, RoutedEventArgs e)
{
using (var userStore = IsolatedStorageFile.GetUserStoreForApplication())
{
if (userStore.FileExists(FILE_NAME))
{
var file = userStore.OpenFile(FILE_NAME, FileMode.Open, FileAccess.Read);
var bytes = new byte[file.Length];
file.Read(bytes, 0, bytes.Length);
playFile(bytes);
}
}
}
}
}