음성 인식은 홈 오토메이션, 인공지능(AI) 등 다양한 애플리케이션에서 가장 유용하게 활용되는 기능 중 하나입니다. 이 글에서는 Python과 Google Speech API를 사용해 음성 인식을 구현하는 방법을 단계별로 살펴보겠습니다.
여기서는 마이크를 통해 음성을 입력받아 인식하는 방식으로 진행합니다. 마이크를 올바르게 설정하려면 몇 가지 파라미터를 지정해야 합니다.
필요한 모듈 설치
먼저 SpeechRecognition 모듈을 설치해야 합니다. 추가로 pyaudio 모듈을 설치하면(선택 사항) 다양한 오디오 모드를 설정할 수 있어 더욱 편리합니다.
sudo pip3 install SpeechRecognition sudo apt-get install python3-pyaudio
마이크 설정 시 고려해야 할 파라미터
외부 마이크 / USB 마이크 지정
외부 마이크나 USB 마이크를 사용하는 경우에는 정확한 마이크 장치를 지정해야 문제없이 동작합니다. 리눅스에서는 터미널에 lsusb 명령어를 입력하면 연결된 USB 장치 정보를 확인할 수 있습니다.
청크 크기(Chunk Size)
청크 크기는 한 번에 읽어들일 데이터의 양을 지정하는 값입니다. 반드시 2의 거듭제곱 형태여야 하며, 예를 들어 1024나 2048 같은 값을 사용합니다.
샘플링 레이트(Sampling Rate)
샘플링 레이트는 데이터가 처리를 위해 얼마나 자주 기록되는지를 결정합니다.
주변 소음 조정(Ambient Noise Adjustment)
주변 환경에서 발생하는 불가피한 잡음이 있을 수 있으므로, 주변 소음을 보정하여 원하는 목소리만 정확하게 입력받도록 조정해야 합니다.
음성 인식 진행 단계
마이크와 관련된 각종 정보를 가져옵니다.
청크 크기, 샘플링 레이트, 주변 소음 보정 등으로 마이크를 구성합니다.
음성 입력을 받기 위해 잠시 대기합니다.
음성이 인식되면 텍스트로 변환하고, 실패하면 오류를 발생시킵니다.
프로세스를 종료합니다.
예제 코드: 마이크 입력 음성 인식
import speech_recognition as spreg
# 샘플링 레이트와 데이터 크기 설정
sample_rate = 48000
data_size = 8192
recog = spreg.Recognizer()
with spreg.Microphone(sample_rate=sample_rate, chunk_size=data_size) as source:
recog.adjust_for_ambient_noise(source)
print('Tell Something: ')
speech = recog.listen(source)
try:
text = recog.recognize_google(speech)
print('You have said: ' + text)
except spreg.UnknownValueError:
print('Unable to recognize the audio')
except spreg.RequestError as e:
print("Request error from Google Speech Recognition service; {}".format(e))실행 결과
$ python3 318.speech_recognition.py Tell Something: You have said: here we are considering the asymptotic notation Pico to calculate the upper bound of the time complexity so then the definition of the big O notation is like this one $
오디오 파일로 음성 인식하기
마이크 없이도 오디오 파일을 입력으로 받아 음성을 텍스트로 변환할 수 있습니다. 파일 기반 인식은 녹음본 전사나 배치 처리 작업에 특히 유용합니다.
예제 코드: 오디오 파일 음성 인식
import speech_recognition as spreg
sound_file = 'sample_audio.wav'
recog = spreg.Recognizer()
with spreg.AudioFile(sound_file) as source:
speech = recog.record(source) # listen 대신 record 사용
try:
text = recog.recognize_google(speech)
print('The file contains: ' + text)
except spreg.UnknownValueError:
print('Unable to recognize the audio')
except spreg.RequestError as e:
print("Request error from Google Speech Recognition service; {}".format(e))실행 결과
$ python3 318a.speech_recognition_file.py The file contains: staying ahead of the curve demand planning new technology it also helps you progress in your career $