Created
February 13, 2021 15:12
-
-
Save thatswiftguy/f86f10d157e1b097e1869fdf10783cfc to your computer and use it in GitHub Desktop.
This Snippet of Code Includes the Start Recording and Stop Feature
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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