You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
52 lines
1.9 KiB
52 lines
1.9 KiB
import tkinter as tk
|
|
from tkinter import messagebox
|
|
import speech_recognition as sr
|
|
|
|
|
|
class VoiceRecognitionApp:
|
|
def __init__(self, master):
|
|
self.master = master
|
|
master.title("语音识别工具")
|
|
|
|
# 创建开始录音的按钮
|
|
self.record_button = tk.Button(master, text="开始录音", command=self.start_listening)
|
|
self.record_button.pack(pady=10)
|
|
|
|
# 创建完成按钮,初始时禁用
|
|
self.finish_button = tk.Button(master, text="完成并识别", state=tk.DISABLED, command=self.recognize_voice)
|
|
self.finish_button.pack(pady=10)
|
|
|
|
self.recognizer = sr.Recognizer()
|
|
self.audio_data = None
|
|
|
|
def start_listening(self):
|
|
# 启动录音
|
|
self.record_button.config(state=tk.DISABLED) # 禁用开始录音按钮
|
|
self.finish_button.config(state=tk.NORMAL) # 启用完成按钮
|
|
with sr.Microphone() as source:
|
|
print("请说话...")
|
|
self.audio_data = self.recognizer.listen(source)
|
|
|
|
def recognize_voice(self):
|
|
if self.audio_data is not None:
|
|
try:
|
|
recognized_text = self.recognizer.recognize_google(self.audio_data, language='zh-CN')
|
|
messagebox.showinfo("识别结果", f"你说的是: {recognized_text}")
|
|
except sr.UnknownValueError:
|
|
messagebox.showerror("错误", "无法识别你的语音")
|
|
except sr.RequestError as e:
|
|
messagebox.showerror("错误", f"服务不可用; {e}")
|
|
finally:
|
|
self.reset_ui() # 识别完成后重置UI状态
|
|
|
|
def reset_ui(self):
|
|
# 重置按钮状态和音频数据
|
|
self.record_button.config(state=tk.NORMAL)
|
|
self.finish_button.config(state=tk.DISABLED)
|
|
self.audio_data = None
|
|
|
|
|
|
# 创建主窗口并启动应用
|
|
app = tk.Tk()
|
|
VoiceRecognitionApp(app)
|
|
app.mainloop() |