englishtokorea/my_speech.py
2025-05-28 14:26:49 +09:00

93 lines
3.4 KiB
Python

import speech_recognition as sr
import pygame
import time
from mutagen.mp3 import MP3
command_first_list = ['석렬아','성렬아','성열아', '건희야','건이야', '쥴리야', '줄리야', '동훈아']
command_second_list = ['현제시간', '시간알려줘', '시계', '날씨', '오늘날씨', '전주날씨','달라환율','오늘환율','환율','그만','처음으로','멈춰']
def listen_for_command():
recognizer = sr.Recognizer()
while True:
# 첫 번째 명령어 대기
first_command = listen_for_speech(recognizer, 'first_command')
# 사용자의 첫번째 음성 입력과 각 명령어를 비교
for command in command_first_list:
if command in first_command:
print(f"인식된 명령어: {command}")
res = perform_action(command)
# 사용자의 두번째 음성 입력과 각 명령어를 비교
if res:
recognizer2 = sr.Recognizer()
while True:
# 두 번째 명령어 대기
second_command = listen_for_speech(recognizer2, 'second_command')
loop=False
for command2 in command_second_list:
if command2 in second_command:
print(f"인식된 두번째 명령어: {command2}")
loop = perform_action(command2)
break
if loop:
break
def listen_for_speech(recognizer, no):
with sr.Microphone() as source:
try:
print(no,"명령어를 말할 때까지 대기 중입니다...")
recognizer.adjust_for_ambient_noise(source)
audio_data = recognizer.listen(source, timeout=None)
text = recognizer.recognize_google(audio_data, language="ko-KR")
print(f"인식된 텍스트: {text}")
return text
except sr.UnknownValueError:
print("음성을 인식할 수 없습니다.")
return ""
except sr.RequestError as e:
print(f"음성 서비스 오류: {e}")
return ""
def perform_action(command):
# 각 명령어에 따른 동작 수행
command_weather = ['날씨', '오늘날씨', '전주날씨']
command_exchangerate = ['달라환율','오늘환율','환율']
command_nowtime = ['현제시간', '시간알려줘', '시계']
command_stop = ['그만','처음으로','멈춰']
if command in command_first_list:
# mp3파일 재생
audio = MP3("mp3/order.mp3")
times = audio.info.length
print(times)
pygame.mixer.init()
pygame.mixer.music.load("mp3/order.mp3")
pygame.mixer.music.play()
time.sleep(times)
return True
elif command in command_nowtime:
print("시간을 알려드립니다.")
return True
elif command in command_weather:
print("날씨 알려드립니다.")
return True
elif command in command_exchangerate:
print("환율을 알려드립니다.")
return True
elif command in command_stop:
print("두번째 명령 끝.")
return True
else:
return False
# 추가적인 명령어와 동작을 여기에 추가할 수 있습니다.
if __name__ == "__main__":
listen_for_command()