Skip to content

Instantly share code, notes, and snippets.

@dhavaln
Last active May 15, 2020 15:57
Show Gist options
  • Save dhavaln/ac8170b53dee13073883 to your computer and use it in GitHub Desktop.
Save dhavaln/ac8170b53dee13073883 to your computer and use it in GitHub Desktop.
Record User Sound in Swift iOS - XCode 6.4
import UIKit
import AVFoundation
class RecordSoundsViewController: UIViewController, AVAudioRecorderDelegate {
var audioPlayer: AVAudioPlayer
@IBAction func recordAudio(sender: UIButton) {
let dirPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as? String
// Create File name based on current date/time value
let currentDate = NSDate()
let formatter = NSDateFormatter()
formatter.dateFormat = "ddMMyyyy-HHmmss";
let recordingName = formatter.stringFromDate(currentDate) + ".wav" ;
let filePath = dirPath?.stringByAppendingPathComponent(recordingName);
let fileUrl = NSURL(fileURLWithPath: filePath!);
// We need to set the recording category
var session = AVAudioSession.sharedInstance()
session.setCategory(AVAudioSessionCategoryPlayAndRecord, error: nil)
audioRecorder = AVAudioRecorder(URL: fileUrl, settings: nil, error: nil)
audioRecorder.delegate = self
audioRecorder.meteringEnabled = true;
audioRecorder.record()
}
@IBAction func stopRecording(sender: UIButton) {
// Stop the recorder
audioRecorder.stop()
var audioSession = AVAudioSession.sharedInstance()
audioSession.setActive(false, error: nil);
println("Recording stopped");
}
func audioRecorderDidFinishRecording(recorder: AVAudioRecorder!, successfully flag: Bool) {
if flag {
// recording is done
}else{
println("Error while recording the audio");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment