构建一个语音助手,用花括号中的路径打开应用程序



我想知道是否可以添加很多路径来打开应用程序,但我的代码只有在我要求打开chrome时才会打开计算器。它向我展示了这样的The file /System/Applications/Google Chrome.app does not exist.假设你想修复我的代码,使其变得更好。顺便说一句,我在mac上。非常感谢。

我的代码:

import speech_recognition as sr
from gtts import gTTS
import playsound
import os
import subprocess as sp
import random
def take_command():
r = sr.Recognizer()
with sr.Microphone() as source:
r.adjust_for_ambient_noise(source, duration=1)
print('listening...')
audio = r.listen(source)
try:
text = r.recognize_google(audio)
text = text.lower()
print(f"user: {text}")  # print user app said
except sr.UnknownValueError:
speak('Sorry, I did not get that')
text = None
except sr.RequestError:
speak('Request error')
text = None
return text

def speak(audio_string):
tts = gTTS(text=audio_string, lang='en-uk', slow=False)  # text to speech(voice)
recognizer = random.randint(1, 20000000)
audio_file = 'audio' + str(recognizer) + '.mp3'
tts.save(audio_file)  # save as mp3
print('33[1m' f"computer: {audio_string}")  # print what app said
playsound.playsound(audio_file)  # play the audio file
os.remove(audio_file)  # remove audio file

paths = {
"chrome": ['open', '/System/Applications/Google Chrome.app'],
"excel": ['open', '/System/Applications/Microsoft Excel.app'],
"calculator": ['open', '/System/Applications/Calculator.app'],
}

if __name__ == '__main__':
while True:
query = take_command()
if str(query) in paths:
app = paths.get(query)
sp.call(app)
elif 'bye' in str(query):
exit()

else:
speak('Please repeat the command.')

终端:

listening...
user: chrome
The file /System/Applications/Google Chrome.app does not exist.
listening...
user: calculator
listening...
user: bye

尝试将Chrome路径指定为:

paths = {
"chrome": ['open', '/Applications/Google Chrome.app'],
"excel": ['open', '/System/Applications/Microsoft Excel.app'],
"calculator": ['open', '/System/Applications/Calculator.app'],
}

这是默认的chrome安装位置。

相关内容

最新更新