한들에 Text-to-Speech (TTS) 추가하기

Kang Hee Young·2023년 12월 28일
0
post-thumbnail

한들

현재 운영중인 iOS앱인 한들에 Text-to-Speech (TTS) 추가하기

오픈소스들도 있겠지만 기본으로 애플에서 제공해주는 프레임워크를 통해서 TTS 구현이 가능하다.

TTS 기능은 AVFoundation을 이용하여 다음과 같이 구현가능하다.


import AVFoundation

struct DictView: View {
    let synthesizer = AVSpeechSynthesizer()
    
    var body: some View {
    	Button(action: { speakAnswer() }, label: {
        Image(systemName: "speaker")
            .foregroundColor(.black)
    })
    
    func speakAnswer() {
        do {
            try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
            try AVAudioSession.sharedInstance().setActive(true)
        } catch {
            print("Failed to set up AVAudioSession: \(error)")
        }
        let utterance = AVSpeechUtterance(string: answer)
        utterance.voice = AVSpeechSynthesisVoice(language: "ko-KR") // 한국어로 설정
        utterance.rate = 0.4 // 음성 속도 설정 (기본값은 1.0)
        synthesizer.speak(utterance)
    }
}

참고: 공식 문서

profile
hekang in 42Seoul.

0개의 댓글