반응형
오늘은 아이폰 음성 녹음에 대해서 알아보겠습니다.
- 먼저 info에 음성 permission 작업을 해줍니다.
- AVAudioRecorder 인스턴스 변수와 녹음 파일 변수를 생성해줍니다.
var audioRecoder : AVAudioRecorder!
lazy var recordURL: URL = {
var documentsURL: URL = {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths.first!
}()
let fileName = UUID().uuidString + ".m4a"
let url = documentsURL.appendingPathComponent(fileName)
return url
}()
- 녹음 접근 권한을 판별합니다.
func requestMicrophoneAccess(
completion: @escaping (Bool) -> Void
) {
let audioSession: AVAudioSession = AVAudioSession.sharedInstance()
switch audioSession.recordPermission {
case .undetermined: // 아직 녹음 권한 요청이 되지 않음, 사용자에게 권한 요청
audioSession.requestRecordPermission({
allowed in completion(allowed)
})
case .denied: // 사용자가 녹음 권한 거부, 사용자가 직접 설정 화면에서 권한 허용을 하게끔 유도
completion(false)
case .granted: // 사용자가 녹음 권한 허용
completion(true)
default:
fatalError("[\(#function)] Record Permission is Unknown Default.")
}
}
- 녹음을 위한 초기 설정을 해줍니다.
private func initRecord() {
//포맷 : Apple Lossless
//음질 : "최대"
//비트율 : 320000bps(320kbps)
//오디오 채널 : 2
//샘플률 : 44100Hz
let recordSettings = [AVFormatIDKey : NSNumber(value: kAudioFormatAppleLossless as UInt32),
AVEncoderAudioQualityKey : AVAudioQuality.max.rawValue,
AVEncoderBitRateKey : 320000,
AVNumberOfChannelsKey : 2,
AVSampleRateKey : 44100.0 ] as [String : Any]
do {
audioRecoder = try AVAudioRecorder(
url: recordURL,
settings: recordSettings
)
} catch let error as NSError {
print("Error-setCategory = \(error)")
}
audioRecoder.delegate = self
audioRecoder.isMeteringEnabled = true
audioRecoder.prepareToRecord()
let session = AVAudioSession.sharedInstance()
do {
try session.setCategory(AVAudioSession.Category.playAndRecord)
} catch let error as NSError {
print("Error-setCategory = \(error)")
}
do {
try session.setActive(true)
} catch let error as NSError {
print("Error-setActive = \(error)")
}
}
- 녹음 중지/재생을 구현합니다.
func recording() {
if self.audioRecoder.isRecording {
self.audioRecoder.stop()
} else {
self.audioRecoder.record()
}
}
반응형
'iOS' 카테고리의 다른 글
[iOS] CocoaPods 의존성 설치 문제 해결하기 (0) | 2025.01.19 |
---|---|
[iOS] WkWebView에서 window.open / window.close 처리 (0) | 2022.06.30 |
[iOS] 그림 그리기 (0) | 2022.04.12 |
[iOS] 전화걸기 (0) | 2022.02.28 |
[iOS] [Swift] 카메라 및 앨범 사진 가져오기 (0) | 2022.02.28 |