How to save audio file after recording voice in Xamarin.Forms

Cdn_EuroCdn_Euro Member ✭✭✭
edited November 2018 in Xamarin.Forms

I am wondering how to save an audio file in Xamarin forms. I can get the location where to save to AppDataDirectory using Xamarin.Essentials:

var mainDir = FileSystem.AppDataDirectory;

But I am not sure how to save it in code, right after recording it using the NateRickard AudioRecorder Plugin:

var recordTask = await recorder.StartRecording();
var audioFile = await recordTastk;

Its same as saving/creating any binary file in C#? Say its same as saving an image file? And additionally do I need to use Dependency Injection to save it using platform specific code, or I can manage to only do it from the PCL code?

Best Answer

Answers

  • jezhjezh Member, Xamarin Team Xamurai

    These is a sample of Plugin.AudioRecorder. You can review the code of it. Please check the link: https://github.com/NateRickard/Plugin.AudioRecorder

    Out of curiosity, Since Plugin.AudioRecorder has provided the full filepath of the recorded audio file , so you can use the path directively, Why are you want to save it yourself?

  • Cdn_EuroCdn_Euro Member ✭✭✭
    edited June 13

    @gayanperera Oops I wanted to answer yes to your question and by mistake clicked "Accept Answer". Not sure how to undo it. But Yes I managed to save the audio file to both platforms:

    Note: Using the CrossPermissions NuGet package (not sure what the actual name is on the Nuget store)

    Step1: Create an interface in the PCL (shared) project:

     public interface IAudioService
        {
            void CopyRecordingToExternalStorage(string filePath);
        }
    

    Step2: iOS Platform specific copy to external storage (where you should store the audio file anyways):

    [assembly: Xamarin.Forms.Dependency(typeof(iOSAudioService))]
    namespace myAppName.iOS.iOSServices
    {
        public class iOSAudioService : IAudioService
        {
    
            public async void CopyRecordingToExternalStorage(string filePath)
            {
                var storageStatus = await CrossPermissions.Current.CheckPermissionStatusAsync(Plugin.Permissions.Abstractions.Permission.Storage);
    
                if (storageStatus != Plugin.Permissions.Abstractions.PermissionStatus.Granted)
                {
                    var results = await CrossPermissions.Current.RequestPermissionsAsync(new[] { Plugin.Permissions.Abstractions.Permission.Storage });
                    storageStatus = results[Plugin.Permissions.Abstractions.Permission.Storage];
                }
    
                if (storageStatus == Plugin.Permissions.Abstractions.PermissionStatus.Granted)
                {
                    var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                    var library = Path.Combine(documents, "..", "Library");
    
                    var directoryname = Path.Combine(library, "Sounds");
    
                    var filenameDestPath = Path.Combine(directoryname, AppConstants.CUSTOM_ALERT_FILENAME);
    
                    try
                    {
                        Directory.CreateDirectory(directoryname);
    
                        if (File.Exists(filenameDestPath))
                        {
                            File.Delete(filenameDestPath);
                        }
    
                        File.Copy(filePath, filenameDestPath);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }
                else
                {
                    UserDialogs.Instance.Alert("Permission to write to External Storage denied, cannot save settings.", "Permission Denied", "Ok");
                }
    
            }
        }
    }
    

    Step3: Android platform specific code to copy to external storage

    [assembly: Xamarin.Forms.Dependency(typeof(AndroidAudioService))]
    namespace myAppName.Droid.AndroidServices
    {
        public class AndroidAudioService : IAudioService
        {
            public AndroidAudioService()
            {
            }
    
    
            public async void CopyRecordingToExternalStorage(string filePath)
            {
                var recordingFileExternalPath = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.Path, AppConstants.CUSTOM_ALERT_FILENAME);
    
                var storageStatus = await CrossPermissions.Current.CheckPermissionStatusAsync(Plugin.Permissions.Abstractions.Permission.Storage);
    
                if (storageStatus != Plugin.Permissions.Abstractions.PermissionStatus.Granted)
                {
                    var results = await CrossPermissions.Current.RequestPermissionsAsync(new[] { Plugin.Permissions.Abstractions.Permission.Storage });
                    storageStatus = results[Plugin.Permissions.Abstractions.Permission.Storage];
                }
    
                if (storageStatus == Plugin.Permissions.Abstractions.PermissionStatus.Granted)
                {
                    try
                    {
                        if (File.Exists(recordingFileExternalPath))
                        {
                            File.Delete(recordingFileExternalPath);
                        }
    
                        File.Copy(filePath, recordingFileExternalPath);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }
                else
                {
                    UserDialogs.Instance.Alert("Permission to write to External Storage denied, cannot save settings.", "Permission Denied", "Ok");
                }        
    
            }
        }
    }
    

    Step4: Call platform specific implementation in the shared code using Dependecy Injection:

    private void ButtonSave_Clicked(object sender, EventArgs e)
            {
                buttonSave.IsEnabled = false;
                var recordingFileDestinationPath = Path.Combine(FileSystem.AppDataDirectory, AppConstants.CUSTOM_ALERT_FILENAME);
    
                if (File.Exists(recordingFileDestinationPath))
                {
                    // if (Device.RuntimePlatform == Device.Android)
                    DependencyService.Get<IAudioService>().CopyRecordingToExternalStorage(recordingFileDestinationPath);
                }
            }
    
Sign In or Register to comment.