Recording And Saving Audio File In Windows 10 Application

Introduction 

Here are the instructions to add the capabilities.

Go to package.appxmanifest file, then Capabilities and check on Microphone and Music Library.

After adding the capabilities to use Microphone and Music Library to record and save the data, respectively we will now move on to adding the code which will be added in the XAML file of the application that is-

<ComboBox x:Name="AudioFormat" Width="250" Height="46" Margin="245,213,0,0" HorizontalAlignment="Left" VerticalAlignment="Top" ItemsSource="{Binding}" PlaceholderText="Select Audio Format" SelectionChanged="AudioFormat_SelectionChanged" />    
<ComboBox x:Name="AudioQuality" Width="250" Height="50" Margin="245,301,0,0" HorizontalAlignment="Left" VerticalAlignment="Top" ItemsSource="{Binding}" PlaceholderText="Select Audio Quality" SelectionChanged="AudioQuality_SelectionChanged" />    
<AppBarButton x:Name="Record" Margin="620,342,0,0" HorizontalAlignment="Left" VerticalAlignment="Top" Click="Record_click" Icon="Accept" Label="Record" />    
<AppBarButton x:Name="Stop" Margin="772,342,0,0" HorizontalAlignment="Left" VerticalAlignment="Top" Click="Stop_Click" Icon="Accept" Label="Stop" />    
<AppBarButton x:Name="Save" Margin="936,342,0,0" HorizontalAlignment="Left" VerticalAlignment="Top" Click="Save_click" Icon="Accept" Label="save" />    
<TextBlock x:Name="Duration" Width="354" Height="98" Margin="671,219,0,0" HorizontalAlignment="Left" VerticalAlignment="Top" Text="{Binding}" TextWrapping="Wrap" />    

After adding the code in the XAML file, we will add the code for the functionalities of the buttons: Save, Stop and Record. But before adding any code in the. CS file of the page, we will add a few namespaces which we will be utilized in the application for recording and saving the audio. These namespaces are the following:

using System.Threading.Tasks;    
using Windows.Media.Capture;    
using Windows.Media.MediaProperties;    
using Windows.Storage;    
using Windows.Storage.Pickers;    
using Windows.Storage.Streams;    
using Windows.UI.Popups; 

Now we will create enumeration type for utilizing audio formats and audio quality in which to save the audio. This enumeration will help to save recorded audio in the specified format. The code to declare enum type is the following:

public enum AudioEncodingFormat {    
    Mp3,    
    M4a,    
    Wav,    
    Wma    
}; 

Now we will add a static class 'AudioEncodingFormatExtensions' to utilize the enum type we declared above. The class is static because we don't need to use any object for it, rather we just need to utilize a method to be executed throughout the application.

The code for the class is:

public static class AudioEncodingFormatExtensions {    
    public static string ToFileExtension(this AudioEncodingFormat encodingFormat) {    
        switch (encodingFormat) {    
            case AudioEncodingFormat.Mp3:    
                return ".mp3";    
            case AudioEncodingFormat.Mp4:    
                return ".mp4";    
            case AudioEncodingFormat.Avi:    
                return ".avi";    
            case AudioEncodingFormat.Wma:    
                return ".wma";    
            default:    
                throw new ArgumentOutOfRangeException("encodingFormat"); // to show that no format is being selected.      
        }    
    }    
}

Now we will declare the variables which we are required to use during the span of the application.

The declarations are as follows:

private MediaCapture CaptureMedia; // To record the audio in this object    
private IRandomAccessStream AudioStream; // To save audio in this stream so that it can be saved at a particular location    
private FileSavePicker FileSave; // To open the file save picker option    
private DispatcherTimer DishTImer; // For timer and using it    
private TimeSpan SpanTime; // To count the time for which the timer is working    
private AudioEncodingFormat selectedFormat; // Enum type to check for the format    
private AudioEncodingQuality SelectedQuality; // Declaring a pre defined enum to go for quality of audio being caputed.   

As we have declared all the variables to be used, now, we will start defining methods and adding the functionalities to the methods. At first, we will add some code to the OnNavigatedToevent of the page. The code being added is the one which gets executed when the page is loaded the first time, this code is:

protected async override void OnNavigatedTo(NavigationEventArgs e) {    
    await InitMediaCapture();    
    LoadAudioEncodings();    
    LoadAudioQualities();    
    InitTimer(); // Initializing the timer      
    
}

Now, the methods which are called in the code above are as follows:

// Method for Initializing components for recording and saving audio.      
private async Task InitMediaCapture() {    
    CaptureMedia = new MediaCapture();    
    var captureSettings = new MediaCaptureInitializationSettings();    
    captureSettings.StreamingCaptureMode = StreamingCaptureMode.Audio;    
    await CaptureMedia.InitializeAsync(captureSettings);    
    CaptureMedia.Failed += CaptureMedia_Failed;    
    CaptureMedia.RecordLimitationExceeded += CaptureMedia_RecordLimitationExceeded;    
}    
    
// Method for loading the Audio Encodings to the combo box we initialized for audio encodings in Xaml file      
    
private void LoadAudioEncodings() {    
    var audioEncodingFormats = Enum.GetValues(typeof(AudioEncodingFormat)).Cast < AudioEncodingFormat > ();    
    AudioFormat.ItemsSource = audioEncodingFormats;    
    AudioFormat.SelectedItem = AudioEncodingFormat.Mp3; // Defining a by default selection in case nothing is selected      
}    
    
// Method for loading the Audio Quality to the Combobox we initialized for audio quality in Xaml file      
    
private void LoadAudioQualities() {    
    var audioQualities = Enum.GetValues(typeof(AudioEncodingQuality)).Cast < AudioEncodingQuality > ();    
    AudioQuality.ItemsSource = audioQualities;    
    AudioQuality.SelectedItem = AudioEncodingQuality.Auto; // Defining a by-default selection in case nothing is selected      
}

Now, we will be adding the code to initialize the timer and associate it with an event that will be called for the timer ticking/counting. Here's the code:

private void InitTimer() {    
    DishTImer = new DispatcherTimer();    
    DishTImer.Interval = new TimeSpan(0, 0, 0, 0, 100);    
    DishTImer.Tick += DishTImer_Tick; // Adding the event to the DishTImer object while it hits tick event      
}    
    
// Event for counting the ticks or time      
    
private void DishTImer_Tick(object sender, object e) {    
    SpanTimeSpanTime = SpanTime.Add(DishTImer.Interval);    
    Duration.DataContext = SpanTime;    
}

If the audio getting recorded exceeds the limit of the audio capture, we should be able to handle such situations. For handling such a situation, we had added a declaration to call an event when the media capture limit is exceeded. The code for that event is as in the following code snippet:

private async void CaptureMedia_RecordLimitationExceeded(MediaCapture sender) {    
    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() => {    
        await sender.StopRecordAsync();    
        var warningMessage = new MessageDialog("The media recording has been stopper as you have exceeded the maximum length", "Recording Stopped");    
        await warningMessage.ShowAsync();    
    
    });    
}

Now, we will add code for Media capture fail event which will be called when there is any failure during the capturing of audio. Here's the code:

private async void CaptureMedia_Failed(MediaCapture sender, MediaCaptureFailedEventArgs errorEventArgs) {    
    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() => {    
        var warningMessage = new MessageDialog("The media recording Failed " + errorEventArgs.Message, "Capture Failed");    
        await warningMessage.ShowAsync();    
    });    
}

As of now, we have defined all the functionalities which will be working in the back end to capture the media. Now, we will add the code to the button which on clicking will call these events and starts capturing the audio. The code for audio recording button click event is:

private async void Record_click(object sender, RoutedEventArgs e) {    
    MediaEncodingProfile encodingProfile = null;    
    switch (selectedFormat) {    
        case AudioEncodingFormat.Mp3:    
            encodingProfile = MediaEncodingProfile.CreateMp3(SelectedQuality);    
            break;    
        case AudioEncodingFormat.Mp4:    
            encodingProfile = MediaEncodingProfile.CreateMp3(SelectedQuality);    
            break;    
        case AudioEncodingFormat.Wma:    
            encodingProfile = MediaEncodingProfile.CreateWav(SelectedQuality);    
            break;    
        case AudioEncodingFormat.Avi:    
            encodingProfile = MediaEncodingProfile.CreateMp3(SelectedQuality);    
            break;    
        default:    
            throw new ArgumentOutOfRangeException();    
    
    }    
    
    AudioStream = new InMemoryRandomAccessStream();    
    await CaptureMedia.StartRecordToStreamAsync(encodingProfile, AudioStream);    
    DishTImer.Start();    
    
} 

After we have added the functionality for the record click event, now, we will be adding functionality for Stop button click event along with the functionality for Save button which will open a Save File Dialog box to save the file at a particular location in the system (here the default is set to the ). Here's the code:

private async void Stop_Click(object sender, RoutedEventArgs e) {    
    await CaptureMedia.StopRecordAsync();    
    DishTImer.Stop();    
}    
    
private async void Save_click(object sender, RoutedEventArgs e) {    
    var mediaFile = await FileSave.PickSaveFileAsync();    
    if (mediaFile != null) {    
        using(var dataReader = new DataReader(AudioStream.GetInputStreamAt(0))) {    
            await dataReader.LoadAsync((uint) AudioStream.Size);    
            byte[] buffer = new byte[(int) AudioStream.Size];    
            dataReader.ReadBytes(buffer);    
            await FileIO.WriteBytesAsync(mediaFile, buffer);    
        }    
    }    
}

We have added the combo boxes for selecting which format we will be using and which quality the audio will be saved into. Now, here is the code for the selected item method for those combo boxes:

private void AudioQuality_SelectionChanged(object sender, SelectionChangedEventArgs e) {    
    SelectedQuality = (AudioEncodingQuality) AudioQuality.SelectedItem;    
}    
    
private void AudioFormat_SelectionChanged(object sender, SelectionChangedEventArgs e) {    
    selectedFormat = (AudioEncodingFormat) AudioFormat.SelectedItem;    
    InitFileSavePicker();    
}

Here, in the above code, we have called a method InitFileSavePicker() that is used to initialize the variables for file save dialog box and it's options. The code for this method is as in the following screenshot:

private void InitFileSavePicker() {    
    FileSave = new FileSavePicker();    
    FileSave.FileTypeChoices.Add("Encoding", new List < string > () {    
        selectedFormat.ToFileExtension()    
    });    
    FileSave.SuggestedStartLocation = PickerLocationId.MusicLibrary;    
    
}

Now, we are done with coding our simple Audio Recorder Application.

Run the application and enjoy it!

Summary

In this article, we learned about Recording And Saving Audio File In Windows 10 Application.  


Similar Articles