[swift] Swift Device의 음성 녹음 및 음성 메모 기능

목차

소개

Swift는 Apple의 주얼얼하면서도 강력한 프로그래밍 언어이며, Swift를 사용하여 iOS 기기에서 음성 녹음 및 음성 메모 기능을 구현하는 것은 굉장히 쉽습니다.

이 블로그 포스트에서는 Swift를 사용하여 기기에 내장된 마이크를 사용하여 음성 녹음 및 음성 메모 기능을 구현하는 방법을 알아보겠습니다.

녹음 기능 구현

  1. AVAudioRecorder 클래스를 사용하여 음성 녹음을 시작합니다. ```swift import AVFoundation

let recordingSession = AVAudioSession.sharedInstance() var audioRecorder: AVAudioRecorder!

func startRecording() { let audioFilename = getDocumentsDirectory().appendingPathComponent(“recording.wav”)

let settings = [
    AVFormatIDKey: Int(kAudioFormatLinearPCM),
    AVSampleRateKey: 44100,
    AVNumberOfChannelsKey: 2,
    AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
]

do {
    audioRecorder = try AVAudioRecorder(url: audioFilename, settings: settings)
    audioRecorder.record()
} catch {
    print("Recording failed.")
} }

func stopRecording() { audioRecorder.stop() }


2. getDocumentsDirectory() 함수를 사용하여 녹음 파일을 저장할 경로를 찾습니다.
```swift
func getDocumentsDirectory() -> URL {
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    let documentsDirectory = paths[0]
    return documentsDirectory
}

이렇게 간단하게 음성 녹음 기능을 구현할 수 있습니다.

음성 메모 기능 구현

  1. AVAudioPlayer 클래스를 사용하여 음성 메모를 재생합니다. ```swift import AVFoundation

var audioPlayer: AVAudioPlayer!

func playMemo() { let audioFilename = getDocumentsDirectory().appendingPathComponent(“recording.wav”)

do {
    audioPlayer = try AVAudioPlayer(contentsOf: audioFilename)
    audioPlayer.play()
} catch {
    print("Playback failed.")
} } ```
  1. 음성 메모 재생을 위해 사용자에게 권한을 요청합니다.
    func requestRecordPermission() {
     recordingSession.requestRecordPermission { (granted) in
         if granted {
             print("Record permission granted.")
             self.startRecording()
         } else {
             print("Record permission denied.")
         }
     }
    }
    
  2. 음성 메모를 재생하기 전에 사용자로부터 녹음 권한을 허용받아야 합니다. 아래의 코드를 사용하여 권한을 요청합니다.
    recordingSession.requestRecordPermission() { allowed in
     DispatchQueue.main.async {
         if allowed {
             // 권한을 허용한 경우 음성 메모를 재생할 수 있습니다.
             self.playMemo()
         } else {
             // 권한을 거부한 경우 메시지를 표시합니다.
             let alertController = UIAlertController(title: "권한 오류", message: "마이크 접근 권한이 없습니다.", preferredStyle: .alert)
             alertController.addAction(UIAlertAction(title: "확인", style: .default))
             self.present(alertController, animated: true, completion: nil)
         }
     }
    }
    

음성 메모 기능도 위와 같이 쉽게 구현할 수 있습니다.

결론

Swift를 사용하여 iOS 기기에서 음성 녹음 및 음성 메모 기능을 구현하는 방법을 알아보았습니다. AVAudioRecorder와 AVAudioPlayer를 사용하여 녹음을 시작하고, 녹음된 파일을 재생할 수 있습니다.

Swift를 사용하여 앱에 음성 기능을 추가하는 것은 사용자와의 상호작용을 향상시키는 데 도움이 됩니다. 다음번에는 이러한 기능을 활용해서 음성 인식 기능을 구현하는 방법에 대해 알아보겠습니다.

궁금한 점이 있다면 언제든지 찾아와 주세요!