Windows 10 Universal Windows Platform – Audio Recorder

Step 1

Download Visual Studio Community 2015 and install it onto your computer, if it’s already downloaded and installed select Launch to start Visual Studio Community 2015 or if it has already been downloaded and installed then start the application you may also need to Enable your device for development.

10-home

Step 2

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

10-file-new-project

Step 3

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

10-new-project

Step 4

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

10-project-add-new-item

Step 5

From the Add New Item window select Visual C# 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

10-add-new-item-library

Step 6

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 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:

10-library-audiorecorder

Step 7

From the Solution Explorer select MainPage.xaml

10-mainpage

Step 8

Select from the Menu, View then Designer

10-designer

Step 9

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>
	<AppBar IsOpen="True" IsSticky="True">
		<StackPanel Orientation="Horizontal">
			<AppBarButton Name="Record" Icon="Memo" Label="Record" Click="Record_Click"/>
			<AppBarButton Name="Play" Icon="Play" Label="Play" Click="Play_Click"/>
		</StackPanel>
	</AppBar>
</Page.BottomAppBar>

It should appear as such:

10-xaml-audiorecorder

Step 10

Select from the Menu, View then Code

10-code

Step 11

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

public 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);
}

It should then appear as such:

10-code-audiorecorder

Step 12

Then from the Solution Explorer select Package.appxmanifest

10-package

Step 13

Select from the Menu, View then Code

10-code

Step 14

The Code View will be displayed for the Package.appxmanifest and in this below <Capability Name=”internetClient” /> enter the following XML:

<DeviceCapability Name="microphone" />

It should appear as such:

10-package-audiorecorder

Step 15

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

10-localmachine

Step 16

Once the Application has started the following should then appear

10-localmachine-run-audiorecorder

Step 17

After the Application 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

10-localmachine-ran-audiorecorder

Step 18

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

10-stop

Step 19

Another option is to run as a Windows Phone application, select Debug and select Emulator 10.0.1.0 WVGA 4 inch 512MB option to run the Application

10-emulator

Step 20

Once the Emulator has started the Application should then appear

10-emulator-run-audiorecorder

Step 21

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

10-emulator-ran-audiorecorder

Step 22

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

10-stop

Creative Commons License

Advertisements

8 thoughts on “Windows 10 Universal Windows Platform – Audio Recorder

  1. Tutorial not tested yet, but is it possible to record microphone and the speaker to separate tracks in one audio file?
    Example: Speaker has channel left, mic has channel right.
    Thank you.

    Like

    • I’m not sure, you might be able to record multiple channels, left and right anyway if the source provides this but I’ve not done any stereo recording before so can’t test this

      Like

  2. Sorry for question, I’m a litte bit confused:
    Is this app only for PC and Phone or PC only?
    I tried the tutorial, but it is only a WUA project for PC but in my view I see only for Windows PC and not for both PC and Phone. In this tutorial it is for both, PC and Phone…

    Like

    • This application will work on PC and Mobile, all the examples in this set of tutorials work for both PC and Mobile – if the project created is a UWP Project type you should be able to run it on a phone or the emulators if they’re installed

      Like

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s