using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Windows;
using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework.Audio;

namespace WPRecordAndPlay
{
    public partial class MainPage : PhoneApplicationPage
    {
        Microphone microphoneDevice = Microphone.Default;
        MemoryStream microphoneDataStream = new MemoryStream();
        byte[] audioDataBuffer;
        SoundEffect recordedSoundEffect;
        bool isRecording = false;

        // Constructor
        public MainPage()
        {
            InitializeComponent();
            microphoneDevice.BufferDuration = TimeSpan.FromMilliseconds(1000);
            audioDataBuffer = 
                new byte[microphoneDevice.GetSampleSizeInBytes(
                    microphoneDevice.BufferDuration)];
            microphoneDevice.BufferReady += new EventHandler<EventArgs>(microphone_BufferReady);
        }

        void microphone_BufferReady(object sender, EventArgs e)
        {
            microphoneDevice.GetData(audioDataBuffer);
            if (isRecording)
            {
                microphoneDataStream.Write(audioDataBuffer, 0,
                    audioDataBuffer.Length);
            }

        }

        private void btRecordPause_Click(object sender, RoutedEventArgs e)
        {
            isRecording = !isRecording;

            if (!isRecording)
            {
                btRecordPause.Content = "Aufnahme";
                microphoneDevice.Stop();
                recordedSoundEffect = new SoundEffect(microphoneDataStream.ToArray(),
                    microphoneDevice.SampleRate, AudioChannels.Mono);
                btPlay.IsEnabled = true;
            }
            else
            {
                btRecordPause.Content = "Anhalten";
                microphoneDevice.Start();
                btPlay.IsEnabled = false;
            }
            microphoneDataStream.Dispose();
            microphoneDataStream = new MemoryStream();
        }

        private void btPlay_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                recordedSoundEffect.Play();
            }
            catch (Exception exc)
            {
                System.Diagnostics.Debug.WriteLine(exc.ToString());
            }
        }

    }
}