Audio Recording and Playing in Swift 3.0.

This tutorial provide the steps of Audio Recording and Playing in Swift programming language, In this tutorial the Audio file store in the document directory, and after completion of recording the file is Playing.




There are two main class to Record and Play audio, Class AVAudioRecorder for Audio recording and AVAudioPlayer for Audio Playing. Here we are code for only audio recording and in next tutorial for Audio Player in Swift.


Note : iOS 10 Device, You have to Added the permission in info.plist Privacy - Microphone Usage Description. Otherwise app will be crash.  See the below tutorial : Info.plist - Requesting Permission Privacy Settings in iOS 10. 

Step 1 : Import the AVFoundation framework in your file.
import AVFoundation
Step 2 :  Adding audioRecorded Delegate in your swift file.
class ViewController: UIViewController , AVAudioRecorderDelegate {
Step 3:  Adding the four property in your swift file. one record button start and stop the recording, audio session to manage recording , audio recorder object to actual audio record and save the audio data and configure setting in which format to save audio.
@IBOutlet weak var btnAudioRecord: UIButton!
var recordingSession : AVAudioSession!
var audioRecorder    :AVAudioRecorder!
var settings         = [String : Int]()
Step 4 :  Audio recording permission , audio session and audio configuration setting code in ViewDidLoad.
override func viewDidLoad() {
    super.viewDidLoad()
    recordingSession = AVAudioSession.sharedInstance()
    do {
        try recordingSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
        try recordingSession.setActive(true)
        recordingSession.requestRecordPermission() { [unowned self] allowed in
            DispatchQueue.main.async {
                if allowed {
                    print("Allow")
                } else {
                    print("Dont Allow")
                }
            }
        }
    } catch {
        print("failed to record!")
    }

   // Audio Settings 

    settings = [
        AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
        AVSampleRateKey: 12000,
        AVNumberOfChannelsKey: 1,
        AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
    ]
}
 Step 5:  The audio file name "sound.m4a" and which is stored in document directory. write below code to store audio in document directory.
func directoryURL() -> NSURL? {
    let fileManager = FileManager.default
    let urls = fileManager.urls(for: .documentDirectory, in: .userDomainMask)
    let documentDirectory = urls[0] as NSURL
    let soundURL = documentDirectory.appendingPathComponent("sound.m4a")
    print(soundURL)
    return soundURL as NSURL?
}
Step 6 : A function to start recording.
func startRecording() {
        let audioSession = AVAudioSession.sharedInstance()
            do {
                audioRecorder = try AVAudioRecorder(url: self.directoryURL()! as URL,
                                                    settings: settings)
                audioRecorder.delegate = self
                audioRecorder.prepareToRecord()
            } catch {
                finishRecording(success: false)
            }
            do {
                try audioSession.setActive(true)
                audioRecorder.record()
            } catch {
        }
    }
Step 7 : A function to finish recording. 
func finishRecording(success: Bool) {
    audioRecorder.stop()
    if success {
        print(success)
    } else {
        audioRecorder = nil
        print("Somthing Wrong.")
    }
}

Step 8 : on the button Recording event, You are Record and Stop of recording. note after successfully recording you have to set nil object of record so that you can again record.


@IBAction func click_AudioRecord(_ sender: AnyObject) {
    if audioRecorder == nil {
        self.btnAudioRecord.setTitle("Stop", for: UIControlState.normal)
        self.btnAudioRecord.backgroundColor = UIColor(red: 119.0/255.0, green: 119.0/255.0, blue: 119.0/255.0, alpha: 1.0)
        self.startRecording()
    } else {
        self.btnAudioRecord.setTitle("Record", for: UIControlState.normal)
        self.btnAudioRecord.backgroundColor = UIColor(red: 221.0/255.0, green: 27.0/255.0, blue: 50.0/255.0, alpha: 1.0)
        self.finishRecording(success: true)
    }
}
Step 9 : When you stop the recording then AVAudioRecorderDelegate called.
 AVAudioRecorderDelegate
func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
    if !flag {
        finishRecording(success: false)
    }
}

Note : After the use of Audio file, You are set audioRecorder = nil , So that you are recording the new audio.Other wise only one time you are record. it's depend you logic. You are set audioRecorder = nil, after playing the audio.

The Next : How  to play audio recorded file in swift.

Thanks.
Audio Recording and Playing in Swift 3.0. Audio Recording and Playing in Swift 3.0. Reviewed by Kirit Modi on 12:15:00 Rating: 5

No comments:

Powered by Blogger.