본문 바로가기

Cloud/AZURE

Azure AI Service : Speech Service로 음성 인식하기

Azure Speech Service를 사용하기 위해서 SDK를 pip을 이용해서 설치합니다.

pip install azure-cognitiveservices-speech

 

Speech Service SDK를 import하고,

speech 서비스 사용을 위해서 key와 현재 speech service가 배포된 리전을 변수로 만듭니다.

import azure.cognitiveservices.speech as speechsdk

speech_key = "Azure AI Speech service key"
service_region = "koreacentral"

 

Key와 리전은 Azure에서 배포된 Speech 서비스에서 다음과 같이 확인이 가능합니다.

 

이제 음성 인식 내용을Text로 반환하는 함수를 아래와 같이 작성합니다.

Speech Config에 앞서 변수에 설정한 key와 리전 값으로 Config 객체를 만듭니다.

인식 할 언어를 설정하는 데, 여기에서는 한국어인 'ko-KR'로 설정을 했습니다.

기본 값은 영어(en-US)입니다.

마이크로 입력받기 위한 audio_config 속성을 만들어서, SpeechRecognizer 객체를 만듭니다.

이제 음성 인식을 시작하고, 인식 된 내용을 화면에 출력합니다.

만약 인식이 안됐을 경우나, 인식이 취소된 경우에 대한 처리를 해줍니다.  

def speech_recognize_once_from_mic():
    # 마이크로 음성 인식을 위한 SpeechConfig 생성
    speech_config = speechsdk.SpeechConfig(subscription=speech_key, region=service_region)
    speech_config.speech_recognition_language="ko-KR"
    # 마이크로 입력을 위한 SpeechRecognizer 생성
    audio_config = speechsdk.audio.AudioConfig(use_default_microphone=True)
    speech_recognizer = speechsdk.SpeechRecognizer(speech_config=speech_config,audio_config=audio_config)
    

    print("마이크로부터 음성을 듣고 있습니다. 말을 해보세요...")

    # 단일 인식 결과를 가져옵니다.
    result = speech_recognizer.recognize_once_async().get()

    # 결과 처리
    if result.reason == speechsdk.ResultReason.RecognizedSpeech:
        print(f"인식된 텍스트: {result.text}")
    elif result.reason == speechsdk.ResultReason.NoMatch:
        print("음성 인식에 실패했습니다.")
    elif result.reason == speechsdk.ResultReason.Canceled:
        cancellation_details = result.cancellation_details
        print(f"음성 인식 취소됨: {cancellation_details.reason}")
        if cancellation_details.reason == speechsdk.CancellationReason.Error:
            print(f"오류 코드: {cancellation_details.error_details}")

 

이제, 위의 함수를 호출하면 인식을 시작하고  최대 30초 혹은 침묵이 감지 될 때까지의 음성을 인식해서 출력해줍니다.

speech_recognize_once_from_mic()

 

다음은 실제 호출해서 인식한 결과입니다.

 

 

아래 코드는, 

마이크로 음성 인식을 해야 하는 데, 현재 장비에서 사용 가능한 오디오 장치가 있는지를 확인하는 코드입니다. 

실제 실행과는 상관이 없지만, 정상적으로 음성 인식이 안될 때, 사용 가능한 장치 확인용으로 사용 가능합니다. 

import pyaudio

# PyAudio 초기화
p = pyaudio.PyAudio()

# 사용 가능한 오디오 장치의 수 확인
info = p.get_host_api_info_by_index(0)
numdevices = info.get('deviceCount')

# 사용 가능한 입력(마이크) 장치가 있는지 확인
input_devices = []
for i in range(0, numdevices):
    if (p.get_device_info_by_host_api_device_index(0, i).get('maxInputChannels')) > 0:
        input_devices.append(p.get_device_info_by_host_api_device_index(0, i).get('name'))

# 사용 가능한 마이크 장치가 없을 경우
if len(input_devices) == 0:
    print("No microphone devices found. Please connect a microphone and try again.")
else:
    # 사용 가능한 마이크 장치가 있을 경우, 장치 목록 출력
    print("Found the following input devices:")
    for device in input_devices:
        print(device)

p.terminate()