Windows 8.1 and Windows Phone 8.1 Universal Application – Audio Recorder

Step 1

Download Visual Studio Community 2013 and install it onto your computer, if it’s already downloaded and installed select Launch to start Visual Studio Community 2013 or if it has already been downloaded and installed then start the application.

Visual Studio Community 2013

Step 2

Once Visual Studio Community 2013 has started select File, then New, then Project… from the Menu.

vs-file-new-project

Step 3

From the New Project window select Visual C# then Store Apps from Installed Templates then select Blank App (Universal Apps) from the list, then type in a Name and select a Location to save to before selecting Ok to create the Project.

vs-new-project

Step 4

Once the Project is created from the Solution Explorer select the Project ending with .Shared

vs-shared

Step 5

Once done select from the Menu, Project, then Add New Item…

vs-add-new-item

Step 6

From the Add New Item window select Visual C# from Installed then select Code File from the list, then type in the Name as Shared.cs before selecting Add to add the file to the Project

vs-shared-code-file

Step 7

Once in the Code View for Shared.cs the following should be entered:

using System;
using System.Threading.Tasks;
using Windows.Media.Capture;
using Windows.Media.MediaProperties;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Core;
using Windows.UI.Xaml.Controls;

public class Shared
{
    private const string audioFilename = "audio.m4a";
    private string filename;
    private MediaCapture capture;
    private InMemoryRandomAccessStream buffer;

    public static bool Recording;

    private async Task<bool> init()
    {
        if (buffer != null)
        {
            buffer.Dispose();
        }
        buffer = new InMemoryRandomAccessStream();
        if (capture != null)
        {
            capture.Dispose();
        }
        try
        {
            MediaCaptureInitializationSettings settings = new MediaCaptureInitializationSettings 
            { 
                StreamingCaptureMode = StreamingCaptureMode.Audio 
            };
            capture = new MediaCapture();
            await capture.InitializeAsync(settings);
            capture.RecordLimitationExceeded += (MediaCapture sender) =>
            {
                Stop();
                throw new Exception("Exceeded Record Limitation");
            };
            capture.Failed += (MediaCapture sender, MediaCaptureFailedEventArgs errorEventArgs) =>
            {
                Recording = false;
                throw new Exception(string.Format("Code: {0}. {1}", errorEventArgs.Code, errorEventArgs.Message));
            };
        }
        catch (Exception ex)
        {
            if (ex.InnerException != null && ex.InnerException.GetType() == typeof(UnauthorizedAccessException))
            {
                throw ex.InnerException;
            }
            throw;
        }
        return true;
    }

    public async void Record()
    {
        await init();
        await capture.StartRecordToStreamAsync(MediaEncodingProfile.CreateM4a(AudioEncodingQuality.Auto), buffer);
        if (Recording) throw new InvalidOperationException("cannot excute two records at the same time");
        Recording = true;
    }

    public async void Stop()
    {
        await capture.StopRecordAsync();
        Recording = false;
    }

    public async Task Play(CoreDispatcher dispatcher)
    {
        MediaElement playback = new MediaElement();
        IRandomAccessStream audio = buffer.CloneStream();
        if (audio == null) throw new ArgumentNullException("buffer");
        StorageFolder storageFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
        if (!string.IsNullOrEmpty(filename))
        {
            StorageFile original = await storageFolder.GetFileAsync(filename);
            await original.DeleteAsync();
        }
        await dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
        {
            StorageFile storageFile = await storageFolder.CreateFileAsync(audioFilename, CreationCollisionOption.GenerateUniqueName);
            filename = storageFile.Name;
            using (IRandomAccessStream fileStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                await RandomAccessStream.CopyAndCloseAsync(audio.GetInputStreamAt(0), fileStream.GetOutputStreamAt(0));
                await audio.FlushAsync();
                audio.Dispose();
            }
            IRandomAccessStream stream = await storageFile.OpenAsync(FileAccessMode.Read);
            playback.SetSource(stream, storageFile.FileType);
            playback.Play();
        });
    }
}

It should then appear as such:

vs-shared-audiorecorder

Step 8

From the Solution Explorer select the MainPage.xaml from the Project ending with .Windows

vs-windows-mainpage

Step 9

Select from the Menu, View then Designer

vs-designer

Step 10

The Design View will be displayed along with the XAML View and in this above <Grid Background=”{ThemeResource ApplicationPageBackgroundThemeBrush}”> enter the following XAML:

<Page.BottomAppBar>
	<CommandBar IsSticky="True" IsOpen="True">
		<AppBarButton Name="Record" Icon="Memo" Label="Record" Click="Record_Click"/>
		<AppBarButton Name="Play" Icon="Play" Label="Play" Click="Play_Click"/>
	</CommandBar>
</Page.BottomAppBar>

It should appear as such:

vs-windows-xaml-audiorecorder

Step 11

Select from the Menu, View then Code

vs-code

Step 12

Once in the Code View below the public MainPage() { … } the following should be entered:

public Shared Shared = new Shared();

private void Record_Click(object sender, RoutedEventArgs e)
{
	if (Shared.Recording)
	{
		Shared.Stop();
		Record.Icon = new SymbolIcon(Symbol.Memo);
	}
	else
	{
		Shared.Record();
		Record.Icon = new SymbolIcon(Symbol.Microphone);
	}
}

private async void Play_Click(object sender, RoutedEventArgs e)
{
	await Shared.Play(Dispatcher);
}

It should then appear as such:

vs-code-audiorecorder

Step 13

From the Solution Explorer select the Package.appxmanifest from the Project ending with .Windows

vs-windows-package

Step 14

Select from the Menu, View then Designer

vs-designer

Step 15

The Design View will be displayed for Package.appxmanifest then select the Capabilities tab and tick the Microphone option

vs-windows-package-capabilities-audioplayer

Step 16

That completes the Windows Application part so Save the Project then select the Debug and Local Machine option to run the Application

vs-windows-debug-local

Step 17

Once the Application has started the following should then appear

vs-windows-run-audiorecorder

Step 18

After it has started running if your Local Machine has access to a Microphone you can use the Record option to capture audio then use Play to listen back to the recording

vs-windows-ran-audiorecorder

Step 19

To Exit the application select Stop Debugging in Visual Studio Community 2013

vs-stop

Step 20

Another part is the Windows Phone application so from the Solution Explorer select the MainPage.xaml from the Project ending with .WindowsPhone

vs-phone-mainpage

Step 21

Select from the Menu, Project then Set as StartUp Project

vs-startup-project

Step 22

Select from the Menu, View then Designer

vs-designer

Step 23

The Design View will be displayed along with the XAML View and in this above <Grid> enter the following XAML:

<Page.BottomAppBar>
	<CommandBar IsSticky="True" IsOpen="True">
		<AppBarButton Name="Record" Icon="Memo" Label="Record" Click="Record_Click"/>
		<AppBarButton Name="Play" Icon="Play" Label="Play" Click="Play_Click"/>
	</CommandBar>
</Page.BottomAppBar>

It should appear as such:

vs-phone-xaml-audiorecorder

Step 24

Select from the Menu, View then Code

vs-code

Step 25

Once in the Code View below the protected override void OnNavigatedTo(NavigationEventArgs e) { … } the following should be entered:

public Shared Shared = new Shared();

private void Record_Click(object sender, RoutedEventArgs e)
{
	if (Shared.Recording)
	{
		Shared.Stop();
		Record.Icon = new SymbolIcon(Symbol.Memo);
	}
	else
	{
		Shared.Record();
		Record.Icon = new SymbolIcon(Symbol.Microphone);
	}
}

private async void Play_Click(object sender, RoutedEventArgs e)
{
	await Shared.Play(Dispatcher);
}

It should then appear as such:

vs-code-audiorecorder

Step 26

From the Solution Explorer select the Package.appxmanifest from the Project ending with .WindowsPhone

vs-phone-package

Step 27

Select from the Menu, View then Designer

vs-designer

Step 28

The Design View will be displayed for Package.appxmanifest then select the Capabilities tab and tick the Microphone option

vs-phone-package-capabilities-audioplayer

Step 29

That completes the Windows Phone Application part so Save the Project then connect a Windows Phone 8.1 Device and then select the Debug and select the Device option to run the Application

vs-phone-debug-device

Step 30

Once the Application has started the following should then appear

vs-phone-run-audiorecorder

Step 31

After it has started running if your Device has access to a Microphone you can use the Record option to capture audio then use Play to listen back to the recording

vs-phone-ran-audiorecorder

Step 32

To Exit the application select Stop Debugging in Visual Studio Community 2013

vs-stop

Creative Commons License

One thought on “Windows 8.1 and Windows Phone 8.1 Universal Application – Audio Recorder

Leave a comment