Skip to content

Instantly share code, notes, and snippets.

@myawesomehub
Created February 13, 2021 15:12
Show Gist options
  • Save myawesomehub/f86f10d157e1b097e1869fdf10783cfc to your computer and use it in GitHub Desktop.
Save myawesomehub/f86f10d157e1b097e1869fdf10783cfc to your computer and use it in GitHub Desktop.
This Snippet of Code Includes the Start Recording and Stop Feature
import Foundation
import AVFoundation
class VoiceViewModel : NSObject , ObservableObject , AVAudioPlayerDelegate {
var audioRecorder : AVAudioRecorder!
var audioPlayer : AVAudioPlayer!
@Published var isRecording : Bool = false
@Published var recordingsList = [Recording]()
override init(){
super.init()
}
func startRecording(){
let recordingSession = AVAudioSession.sharedInstance()
do {
try recordingSession.setCategory(.playAndRecord, mode: .default)
try recordingSession.setActive(true)
} catch {
print("Can not setup the Recording")
}
let path = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let fileName = path.appendingPathComponent("CO-Voice : \(Date().toString(dateFormat: "dd-MM-YY 'at' HH:mm:ss")).m4a")
let settings = [
AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
AVSampleRateKey: 12000,
AVNumberOfChannelsKey: 1,
AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
]
do {
audioRecorder = try AVAudioRecorder(url: fileName, settings: settings)
audioRecorder.prepareToRecord()
audioRecorder.record()
isRecording = true
} catch {
print("Failed to Setup the Recording")
}
}
func stopRecording(){
audioRecorder.stop()
isRecording = false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment