Recording And Saving Audio File In Windows 10 Application

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:

  1. <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" />  
  2. <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" />  
  3. <AppBarButton x:Name="Record" Margin="620,342,0,0" HorizontalAlignment="Left" VerticalAlignment="Top" Click="Record_click" Icon="Accept" Label="Record" />  
  4. <AppBarButton x:Name="Stop" Margin="772,342,0,0" HorizontalAlignment="Left" VerticalAlignment="Top" Click="Stop_Click" Icon="Accept" Label="Stop" />  
  5. <AppBarButton x:Name="Save" Margin="936,342,0,0" HorizontalAlignment="Left" VerticalAlignment="Top" Click="Save_click" Icon="Accept" Label="save" />  
  6. <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 few namespaces which we will be utilized in the application for recording and saving the audio. These namespaces are the following:
  1. using System.Threading.Tasks;    
  2. using Windows.Media.Capture;    
  3. using Windows.Media.MediaProperties;    
  4. using Windows.Storage;    
  5. using Windows.Storage.Pickers;    
  6. using Windows.Storage.Streams;    
  7. 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:
  1. public enum AudioEncodingFormat {  
  2.     Mp3,  
  3.     M4a,  
  4.     Wav,  
  5.     Wma  
  6. };  
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:
  1. public static class AudioEncodingFormatExtensions {  
  2.     public static string ToFileExtension(this AudioEncodingFormat encodingFormat) {  
  3.         switch (encodingFormat) {  
  4.             case AudioEncodingFormat.Mp3:  
  5.                 return ".mp3";  
  6.             case AudioEncodingFormat.Mp4:  
  7.                 return ".mp4";  
  8.             case AudioEncodingFormat.Avi:  
  9.                 return ".avi";  
  10.             case AudioEncodingFormat.Wma:  
  11.                 return ".wma";  
  12.             default:  
  13.                 throw new ArgumentOutOfRangeException("encodingFormat"); // to show that no format is being selected.    
  14.         }  
  15.     }  
  16. }  
Now we will declare the variables which we are required to use during the span of the application.

The declarations are as follows:
  1. private MediaCapture CaptureMedia; // To record the audio in this object    
  2. private IRandomAccessStream AudioStream; // To save audio in this stream so that it can be saved at a particular location    
  3. private FileSavePicker FileSave; // To open the file save picker option    
  4. private DispatcherTimer DishTImer; // For timer and using it    
  5. private TimeSpan SpanTime; // To count the time for which the timer is working    
  6. private AudioEncodingFormat selectedFormat; // Enum type to check for the format    
  7. 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 first time, this code is:
  1. protected async override void OnNavigatedTo(NavigationEventArgs e) {  
  2.     await InitMediaCapture();  
  3.     LoadAudioEncodings();  
  4.     LoadAudioQualities();  
  5.     InitTimer(); // Initializing the timer    
  6.   
  7. }  
Now, the methods which are called in the code above are as follows:
  1. // Method for Initializing components for recording and saving an audio.    
  2. private async Task InitMediaCapture() {  
  3.     CaptureMedia = new MediaCapture();  
  4.     var captureSettings = new MediaCaptureInitializationSettings();  
  5.     captureSettings.StreamingCaptureMode = StreamingCaptureMode.Audio;  
  6.     await CaptureMedia.InitializeAsync(captureSettings);  
  7.     CaptureMedia.Failed += CaptureMedia_Failed;  
  8.     CaptureMedia.RecordLimitationExceeded += CaptureMedia_RecordLimitationExceeded;  
  9. }  
  10.   
  11. // Method for loading the Audio Encodings to the combobox we intialized for audio encodings in Xaml file    
  12.   
  13. private void LoadAudioEncodings() {  
  14.     var audioEncodingFormats = Enum.GetValues(typeof(AudioEncodingFormat)).Cast < AudioEncodingFormat > ();  
  15.     AudioFormat.ItemsSource = audioEncodingFormats;  
  16.     AudioFormat.SelectedItem = AudioEncodingFormat.Mp3; // Defining a by default selection in case nothing is selected    
  17. }  
  18.   
  19. // Method for loading the Audio Quality to the combobox we intialized for audio quality in Xaml file    
  20.   
  21. private void LoadAudioQualities() {  
  22.     var audioQualities = Enum.GetValues(typeof(AudioEncodingQuality)).Cast < AudioEncodingQuality > ();  
  23.     AudioQuality.ItemsSource = audioQualities;  
  24.     AudioQuality.SelectedItem = AudioEncodingQuality.Auto; // Defining a by default selection in case nothing is selected    
  25. }  
Now, we will be adding the code to initialize timer and associate it with an event which will be called for the timer ticking/counting. Here's the code:
  1. private void InitTimer() {  
  2.     DishTImer = new DispatcherTimer();  
  3.     DishTImer.Interval = new TimeSpan(0, 0, 0, 0, 100);  
  4.     DishTImer.Tick += DishTImer_Tick; // Adding the event to the DishTImer object while it hits tick event    
  5. }  
  6.   
  7. // Event for counting the ticks or time    
  8.   
  9. private void DishTImer_Tick(object sender, object e) {  
  10.     SpanTime = SpanTime.Add(DishTImer.Interval);  
  11.     Duration.DataContext = SpanTime;  
  12. }  
If the audio getting recorded exceeds the limit of the audio capture, we should be able to handle such situations. For handling such situation, we had added a declaration to call an event when media capture limit is exceeded. The code for that event is as in the following code snippet:
  1. private async void CaptureMedia_RecordLimitationExceeded(MediaCapture sender) {  
  2.     await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() => {  
  3.         await sender.StopRecordAsync();  
  4.         var warningMessage = new MessageDialog("The media recording has been stopper as you have exceeded the maximum length""Recording Stopped");  
  5.         await warningMessage.ShowAsync();  
  6.   
  7.     });  
  8. }  
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:
  1. private async void CaptureMedia_Failed(MediaCapture sender, MediaCaptureFailedEventArgs errorEventArgs) {  
  2.     await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async() => {  
  3.         var warningMessage = new MessageDialog("The media recording Failed " + errorEventArgs.Message, "Capture Failed");  
  4.         await warningMessage.ShowAsync();  
  5.     });  
  6. }  
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:
  1. private async void Record_click(object sender, RoutedEventArgs e) {  
  2.     MediaEncodingProfile encodingProfile = null;  
  3.     switch (selectedFormat) {  
  4.         case AudioEncodingFormat.Mp3:  
  5.             encodingProfile = MediaEncodingProfile.CreateMp3(SelectedQuality);  
  6.             break;  
  7.         case AudioEncodingFormat.Mp4:  
  8.             encodingProfile = MediaEncodingProfile.CreateMp3(SelectedQuality);  
  9.             break;  
  10.         case AudioEncodingFormat.Wma:  
  11.             encodingProfile = MediaEncodingProfile.CreateWav(SelectedQuality);  
  12.             break;  
  13.         case AudioEncodingFormat.Avi:  
  14.             encodingProfile = MediaEncodingProfile.CreateMp3(SelectedQuality);  
  15.             break;  
  16.         default:  
  17.             throw new ArgumentOutOfRangeException();  
  18.   
  19.     }  
  20.   
  21.     AudioStream = new InMemoryRandomAccessStream();  
  22.     await CaptureMedia.StartRecordToStreamAsync(encodingProfile, AudioStream);  
  23.     DishTImer.Start();  
  24.   
  25. }  
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:
  1. private async void Stop_Click(object sender, RoutedEventArgs e) {  
  2.     await CaptureMedia.StopRecordAsync();  
  3.     DishTImer.Stop();  
  4. }  
  5.   
  6. private async void Save_click(object sender, RoutedEventArgs e) {  
  7.     var mediaFile = await FileSave.PickSaveFileAsync();  
  8.     if (mediaFile != null) {  
  9.         using(var dataReader = new DataReader(AudioStream.GetInputStreamAt(0))) {  
  10.             await dataReader.LoadAsync((uint) AudioStream.Size);  
  11.             byte[] buffer = new byte[(int) AudioStream.Size];  
  12.             dataReader.ReadBytes(buffer);  
  13.             await FileIO.WriteBytesAsync(mediaFile, buffer);  
  14.         }  
  15.     }  
  16. }  
We have added the comboboxes 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 comboboxes:
  1. private void AudioQuality_SelectionChanged(object sender, SelectionChangedEventArgs e) {  
  2.     SelectedQuality = (AudioEncodingQuality) AudioQuality.SelectedItem;  
  3. }  
  4.   
  5. private void AudioFormat_SelectionChanged(object sender, SelectionChangedEventArgs e) {  
  6.     selectedFormat = (AudioEncodingFormat) AudioFormat.SelectedItem;  
  7.     InitFileSavePicker();  
  8. }  
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:
  1. private void InitFileSavePicker() {  
  2.     FileSave = new FileSavePicker();  
  3.     FileSave.FileTypeChoices.Add("Encoding"new List < string > () {  
  4.         selectedFormat.ToFileExtension()  
  5.     });  
  6.     FileSave.SuggestedStartLocation = PickerLocationId.MusicLibrary;  
  7.   
  8. }  
Now, we are done with coding our simple Audio Recorder Application.

Run the application and enjoy!

Up Next
    Ebook Download
    View all
    Learn
    View all