How do I Record Audio using Xamarin.Forms (Android and iOS)?

Grime 786 Reputation points
2021-07-20T06:40:11.703+00:00

I have successfully utilised NateRickard's three year old Nuget Plugin.AudioRecorder to make short audio recordings (e.g. "This is a test"), but it fails when I try to record audio for longer (a minute or more).
I wonder if there is something else out there that I should be using. A pointer to potential examples or tutorials would be excellent.
My end game is to potentially capture a few recordings that may each be a few minutes long, then e-mail them.

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,310 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,450 questions
0 comments No comments
{count} votes

Accepted answer
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 70,391 Reputation points Microsoft Vendor
    2021-07-21T03:20:28.957+00:00

    Hello,​

    Welcome to our Microsoft Q&A platform!

    I used Plugin.AudioRecorder to make long audio recordings, then I use Plugin.MediaManager to play the audio. When I click the record button to record the audio, click again to stop it, then click Get record button to stop it like following screenshot.

    Please double check the value of TotalAudioTimeout. the default value is 30 seconds.

       recorder = new AudioRecorderService  
       {  
       StopRecordingOnSilence = true, //will stop recording after 2 seconds (default)  
       StopRecordingAfterTimeout = true,  //stop recording after a max timeout (defined below)  
       TotalAudioTimeout = TimeSpan.FromSeconds(180) //audio will stop recording after 3 minutes  
       };  
    

    I think you can use dependence service to achieve the record function, such as AVAudioRecorder on iOS or MediaRecorder on Android.

    When you achieve it with dependenceService, you can refer to following native demos.

    Xamarin.Android achieve it demo: https://github.com/xamarin/docs-archive/tree/master/Recipes/android/media/audio/record_audio

    Xamarin.iOS achieve it demo: https://github.com/xamarin/docs-archive/tree/master/Recipes/ios/media/sound/record_sound

    116584-image.png

    For android, I add following code to MainActivity.cs

       public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity  
           {  
               protected override void OnCreate(Bundle savedInstanceState)  
               {  
                   base.OnCreate(savedInstanceState);  
         
       //add following code to   
                   if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.RecordAudio) != Permission.Granted)  
                   {  
                       ActivityCompat.RequestPermissions(this, new String[] { Manifest.Permission.RecordAudio }, 1);  
                   }  
                   CrossMediaManager.Current.Init(this);  
         
                   Xamarin.Essentials.Platform.Init(this, savedInstanceState);  
                   global::Xamarin.Forms.Forms.Init(this, savedInstanceState);  
                   LoadApplication(new App());  
               }  
    

    And add following permission to the AndroidManifest.xml

       <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />  
           <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />  
           <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />  
           <uses-permission android:name="android.permission.RECORD_AUDIO" />  
    

    For iOS.

    add following code to your Info.plist

       <key>NSMicrophoneUsageDescription</key>  
           <string>The [app name] wants to use your microphone to record audio.</string>  
    

    And add CrossMediaManager.Current.Init(); to FinishedLaunching method of AppDelegate.cs

    In the end, we use it in PCL.

       public partial class MainPage : ContentPage  
           {  
       AudioRecorderService recorder;  
       public MainPage()  
               {  
                   InitializeComponent();  
         
       recorder = new AudioRecorderService  
       {  
       StopRecordingOnSilence = true, //will stop recording after 2 seconds (default)  
       StopRecordingAfterTimeout = true,  //stop recording after a max timeout (defined below)  
       TotalAudioTimeout = TimeSpan.FromSeconds(180) //audio will stop recording after 3 minutes  
       };  
         
         
         
       }  
         
       async void RecordButton_Click(object sender, EventArgs e)  
       {  
       await RecordAudio();  
       }  
         
       async Task RecordAudio()  
       {  
       try  
       {  
       if (!recorder.IsRecording)  
       {  
       await recorder.StartRecording();  
       }  
       else  
       {  
       await recorder.StopRecording();  
         
         
       }  
       }  
       catch (Exception ex)  
       {  
       //...  
                }  
         
         
       }  
         
               private async void Button_Clicked(object sender, EventArgs e)  
               {  
       //var audioFile = await recorder;  
         
       if (recorder.FilePath != null) //non-null audioFile indicates audio was successfully recorded  
       {  
       //do something with the file  
       var path=recorder.FilePath;  
         
       await CrossMediaManager.Current.Play("file://"+ path);  
         
       }  
       }  
           }  
       }  
    

    Here is MainPage.xaml

       <StackLayout>  
               <Frame BackgroundColor="#2196F3" Padding="24" CornerRadius="0">  
                   <Label Text="Welcome to Xamarin.Forms!" HorizontalTextAlignment="Center" TextColor="White" FontSize="36"/>  
               </Frame>  
               <Label Text="Start developing now" FontSize="Title" Padding="30,10,30,10"/>  
               <Label Text="Make changes to your XAML file and save to see your UI update in the running app with XAML Hot Reload. Give it a try!" FontSize="16" Padding="30,0,30,0"/>  
               <Label FontSize="16" Padding="30,24,30,0">  
                   <Label.FormattedText>  
                       <FormattedString>  
                           <FormattedString.Spans>  
                               <Span Text="Learn more at "/>  
                               <Span Text="https://aka.ms/xamarin-quickstart" FontAttributes="Bold"/>  
                           </FormattedString.Spans>  
                       </FormattedString>  
                   </Label.FormattedText>  
               </Label>  
               <Button Text="recrod" Clicked="RecordButton_Click"></Button>  
               <Button Text="Get recrod" Clicked="Button_Clicked"></Button>  
           </StackLayout>  
    

    Best Regards,

    Leon Lu


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful