Universal Windows Platform – Audio Recorder

Audio Recorder demonstrates how to use MediaCapture to record sound

Step 1

If not already, follow Setup and Start on how to Install and get Started with Visual Studio 2017 or in Windows 10 choose Start, and then from the Start Menu find and select Visual Studio 2017.

vs2017

Step 2

Once Visual Studio Community 2017 has started, from the Menu choose File, then New then Project…

vs2017-file-new-project

Step 3

From New Project choose Visual C# from Installed, Templates then choose Blank App (Universal Windows) and then type in a Name and select a Location and then select Ok to create the Project
vs2017-new-project-window

Step 4

Then in New Universal Windows Project you need to select the Target Version this should be at least the Windows 10 Fall Creators Update (10.0; Build 16299) and the Minimum Version to be the same.

vs2017-target-platform

The Target Version will control what features your application can use in Windows 10 so by picking the most recent version you’ll be able to take advantage of those features. To make sure you always have the most recent version, in Visual Studio 2017 select Tools Extensions and Updates… then and then see if there are any Updates

Step 5

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

vs2017-project-add-new-item

Step 6

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

vs2017-add-new-item-library

Step 7

Once in the Code View for Library.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 Library
{
    private const string file_name = "audio.m4a";

    private string _filename;
    private MediaCapture _capture;
    private InMemoryRandomAccessStream _buffer;

    public 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 execute two recordings 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(file_name, 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();
        });
    }
}

In the Library.cs there are using statements to include the necessary functionality. MediaCapture is used to capture the sound by the application, the Init Method sets up the recording including configuring the necessary Events for any issues including RecordLimitationExceeded and Failed. The Record Method is used to start recording the audio using StartRecordToStreamAsync of MediaCapture. Play is used to playback any recorded sound using a MediaElement Control set to the file source that was recorded to.

Step 8

In the Solution Explorer select MainPage.xaml

vs2017-mainpage

Step 9

From the Menu choose View and then Designer

vs2017-view-designer

Step 10

The Design View will be displayed along with the XAML View and in this between the Grid and /Grid elements, enter the following XAML:

<CommandBar VerticalAlignment="Bottom">
	<AppBarButton Name="Record" Icon="Memo" Label="Record" Click="Record_Click"/>
	<AppBarButton Name="Play" Icon="Play" Label="Play" Click="Play_Click"/>
</CommandBar>

The first block of XAML is the CommandBar which contains the Record and Play commands to perform the actions of the Audio Recorder.

Step 11

From the Menu choose View and then Code

vs2017-view-code

Step 12

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

Library library = new Library();

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

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

Below the MainPage() Method an instance of the Library Class is created. Record_Click is used to start an Audio recording or if the Recording flag is set it will Stop the recording, Play_Click is used to playback any recording.

Step 13

In the Solution Explorer select Package.appxmanifest

vs2017-mainpage

Step 14

From the Menu choose View and then Designer

vs2017-view-designer

Step 15

Finally in the Package.appxmanifest select Capabilities and then make sure the Microphone option is checked

vs2017-manifest-audio-recorder

Step 16

That completes the Universal Windows Platform Application so Save the Project then in Visual Studio select the Local Machine to run the Application

vs2017-local-machine

Step 17

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

ran-audio-recorder

Step 18

To Exit the Application select the Close button in the top right of the Application

vs2017-close

Creative Commons License

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s