Search This Blog

Tuesday 10 July 2018

Xamarin IOS play and record audio

for start, play and stop recording call interface using dependency service

// write this code on the click event of button or tap gesture event of any control

start recording:
DependencyService.Get<IAudioRecorder>().StartRecording(); //click on start record button
play recording:
DependencyService.Get<IAudioRecorder>().PlayRecording(); //click on play record button
stop recording:
DependencyService.Get<IAudioRecorder>().StopRecording(); //click on stop record button
 

Create the Interface in your Xamarin Form Project 
using System;
namespace AudioRecorderProject.Interfaces
{
    public interface IAudioRecorder
    {
        void StartRecording();
        void StopRecording();
        void PlayRecording();
    }
}
 


Create the audio recorder class in your IOS Project that inherit the interface IAudioRecorder
using System;
using AudioRecorderProject.Interfaces;
using AVFoundation;
using AudioRecorderProject.iOS;
using Foundation;
using System.IO;
using UIKit;
 
[assembly:Xamarin.Forms.Dependency(typeof(AudioRecorder))]
namespace AudioRecorderProject.iOS
{
    public class AudioRecorder : IAudioRecorder
    {
 
        AVAudioRecorder recorder;
        AVPlayer player;
        NSError error;
        NSUrl url;
        NSDictionary settings;
        string audioFilePath;
 
 
        public void StartRecording()
        {
            var audioSession = AVAudioSession.SharedInstance();
            var err = audioSession.SetCategory(AVAudioSessionCategory.PlayAndRecord); 
            string fileName = string.Format("Myfile{0}.wav", DateTime.Now.ToString("yyyyMMddHHmmss"));
            audioFilePath = Path.Combine(Path.GetTempPath(), fileName);
            url = NSUrl.FromFilename(audioFilePath);
            NSObject[] values = new NSObject[]
            {
                NSNumber.FromFloat(44100.0f),
                NSNumber.FromInt32 ((int)AudioToolbox.AudioFormatType.LinearPCM),//AVFormat
                NSNumber.FromInt32 (2), //Channels
                NSNumber.FromInt32 (16), //PCMBitDepth 
                NSNumber.FromBoolean (false), //IsBigEndianKey 
                NSNumber.FromBoolean (false) //IsFloatKey
            };
            NSObject[] keys = new NSObject[]
            {
                AVAudioSettings.AVSampleRateKey,
                AVAudioSettings.AVFormatIDKey,
                AVAudioSettings.AVNumberOfChannelsKey,
                AVAudioSettings.AVLinearPCMBitDepthKey,
                AVAudioSettings.AVLinearPCMIsBigEndianKey,
                AVAudioSettings.AVLinearPCMIsFloatKey
            };
            settings = NSDictionary.FromObjectsAndKeys(values, keys);
            recorder = AVAudioRecorder.Create(url, new AudioSettings(settings), out error);
            recorder.PrepareToRecord();
            recorder.Record();
 
        }
 
 
        public void PlayRecording()
        {
            url = NSUrl.FromFilename(audioFilePath);
            var asset = AVAsset.FromUrl(url);
            var playerItem = new AVPlayerItem(asset);
            player = new AVPlayer(playerItem);
            var playerLayer = AVPlayerLayer.FromPlayer(player);
            GetController().View.Layer.AddSublayer(playerLayer);
            player.Play();
        } 
 
       public void StopRecording()
        {
            if(recorder!=null){
                recorder.Stop();
            }
        } 
       private static UIViewController GetController()
        {
            var vc = UIApplication.SharedApplication.KeyWindow.RootViewController;
            while (vc.PresentedViewController != null)
                vc = vc.PresentedViewController;
            return vc;
        } 
   }
 
}


Note: Add the NSMicrophoneUsageDescription key value in the Source tab of the Info.plist file. This is added by selecting "Privacy – Microphone Usage Description" from the property drop down, and setting an appropriate string:









No comments:

Post a Comment

Popular Posts