Audio Recorder In Windows 10 Universal Windows Platform

We can easily record the audio in Windows 10 universal app using media MediaCapture class.

Let’s see the steps,

Create new Windows 10 universal app project and go to design page to design the UI as you want. Here I will create application bar with three buttons: one for record, one is for stop and another one is for playing the recorded audio.

Use the following XAML Code for design.
  1. <Page.BottomAppBar>  
  2.     <AppBar IsOpen="True" IsSticky="True">  
  3.         <StackPanel Orientation="Horizontal">  
  4.             <AppBarButton x:Name="recordBtn" Label="Record" Icon="Microphone" Click="recordBtn_Click"></AppBarButton>  
  5.             <AppBarButton x:Name="stopBtn" Label="Stop" Icon="Stop" Click="stopBtn_Click"></AppBarButton>  
  6.             <AppBarButton x:Name="playBtn" Label="Play" Icon="Play" Click="playBtn_Click"></AppBarButton>  
  7.         </StackPanel>  
  8.     </AppBar>  
  9. </Page.BottomAppBar>  
Firstly, we need to enable capabilities of Microphone in “Package.appxmanifest” file like the following image.

application
 
Now go to code behind and write the following code.

Create instance for MediaCapture and memory stream then set media capture settings to record audio or video.

Finally, start the record using StartRecordToStreamAsync method by passing media profile and buffer.

You can stop the recording by using StopRecordAsync method.

For playing this recording file we use MediaElement Control.

C# code
  1. public sealed partial class MainPage: Page  
  2. {  
  3.     MediaCapture capture;  
  4.     InMemoryRandomAccessStream buffer;  
  5.     bool record;  
  6.     string filename;  
  7.     string audioFile = ".MP3";  
  8.     public MainPage()  
  9.     {  
  10.         this.InitializeComponent();  
  11.     }  
  12.   
  13.     private async Task < bool > RecordProcess()  
  14.     {  
  15.         if (buffer != null)  
  16.         {  
  17.             buffer.Dispose();  
  18.         }  
  19.         buffer = new InMemoryRandomAccessStream();  
  20.         if (capture != null)  
  21.         {  
  22.             capture.Dispose();  
  23.         }  
  24.         try   
  25.         {  
  26.             MediaCaptureInitializationSettings settings = new MediaCaptureInitializationSettings  
  27.             {  
  28.                 StreamingCaptureMode = StreamingCaptureMode.Audio  
  29.             };  
  30.             capture = new MediaCapture();  
  31.             await capture.InitializeAsync(settings);  
  32.             capture.RecordLimitationExceeded += (MediaCapture sender) =>   
  33.             {  
  34.                 //Stop  
  35.                 // await capture.StopRecordAsync();  
  36.                 record = false;  
  37.                 throw new Exception("Record Limitation Exceeded ");  
  38.             };  
  39.             capture.Failed += (MediaCapture sender, MediaCaptureFailedEventArgs errorEventArgs) =>  
  40.             {  
  41.                 record = false;  
  42.                 throw new Exception(string.Format("Code: {0}. {1}", errorEventArgs.Code, errorEventArgs.Message));  
  43.             };  
  44.         } catch (Exception ex)  
  45.         {  
  46.             if (ex.InnerException != null && ex.InnerException.GetType() == typeof(UnauthorizedAccessException)) {  
  47.                 throw ex.InnerException;  
  48.             }  
  49.             throw;  
  50.         }  
  51.         return true;  
  52.     }  
  53.     public async Task PlayRecordedAudio(CoreDispatcher UiDispatcher)  
  54.     {  
  55.         MediaElement playback = new MediaElement();  
  56.         IRandomAccessStream audio = buffer.CloneStream();  
  57.   
  58.         if (audio == null)  
  59.             throw new ArgumentNullException("buffer");  
  60.         StorageFolder storageFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;  
  61.         if (!string.IsNullOrEmpty(filename))  
  62.         {  
  63.             StorageFile original = await storageFolder.GetFileAsync(filename);  
  64.             await original.DeleteAsync();  
  65.         }  
  66.         await UiDispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>  
  67.        {  
  68.             StorageFile storageFile = await storageFolder.CreateFileAsync(audioFile, CreationCollisionOption.GenerateUniqueName);  
  69.             filename = storageFile.Name;  
  70.             using(IRandomAccessStream fileStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite)) {  
  71.                 await RandomAccessStream.CopyAndCloseAsync(audio.GetInputStreamAt(0), fileStream.GetOutputStreamAt(0));  
  72.                 await audio.FlushAsync();  
  73.                 audio.Dispose();  
  74.             }  
  75.             IRandomAccessStream stream = await storageFile.OpenAsync(FileAccessMode.Read);  
  76.             playback.SetSource(stream, storageFile.FileType);  
  77.             playback.Play();  
  78.         });  
  79.     }  
  80.     private async void recordBtn_Click(object sender, RoutedEventArgs e)  
  81.     {  
  82.         if (record)  
  83.         {  
  84.             //already recored process  
  85.         } else  
  86.         {  
  87.             await RecordProcess();  
  88.             await capture.StartRecordToStreamAsync(MediaEncodingProfile.CreateMp3(AudioEncodingQuality.Auto), buffer);  
  89.             if (record)   
  90.             {  
  91.                 throw new InvalidOperationException();  
  92.             }  
  93.             record = true;  
  94.         }  
  95.   
  96.     }  
  97.   
  98.     private async void stopBtn_Click(object sender, RoutedEventArgs e)  
  99.     {  
  100.         await capture.StopRecordAsync();  
  101.         record = false;  
  102.     }  
  103.   
  104.     private async void playBtn_Click(object sender, RoutedEventArgs e)  
  105.     {  
  106.         await PlayRecordedAudio(Dispatcher);  
  107.     }  
  108. }  
Now run the app and see the expected output like the following image.

output

For Source Code.


Similar Articles