跳到主要內容

簡單的 語音助手

 前言

藉由開發可直接執行的簡單的語音助手專案,了解如何運用 python 語音套件:

1. 語音輸入(SpeechRecognition),把「人講的話」轉成文字(Speech → Text

2. 語音輸出(pyttsx3,把「文字」轉成語音(Text → Speech


簡單流程

  1. 開啟麥克風
  2. 接收聲音
  3. 將聲音送去辨識,呼叫語音辨識引擎(例如 Google Speech API)
  4. 得到文字結果
  5. 將文字丟給 TTS(文字轉語音引擎)
  6. 由電腦播放出聲音

安裝所需套件

# 如果需要使用麥克風,建議安裝此套件
pip3 install pyaudio

註:
pyaudio 如出現問題 ->
note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for pyaudio
原因 ->
pyaudio 需要編譯 C 擴展,但你的系統缺少底層音訊函式庫
macOS 處理->
        步驟 1:安裝 PortAudio
        brew install portaudio
        步驟 2:重新安裝 PyAudio
        pip3 install pyaudio

# 「文字轉語音(Text-to-Speech, TTS)」套件
pip3 install pyttsx3

# 「語音(音訊)」轉成「文字」
pip3 install SpeechRecognition

程式碼
import random
import speech_recognition as sr
import datetime
import pyttsx3

engine = pyttsx3.init()
engine.setProperty('rate', 160)

def speak(text):
engine.say(text)
engine.runAndWait()
intents = {
"greeting": ["你好", "嗨", "您好"],
"farewell": ["再見", "拜拜", "下次見"],
"query": ["你是誰","幫助","你可以做什麼"],
"time": ["現在幾點","現在時間",],
"weather": ["今天天氣如何","天氣怎麼樣",]
}

responses = {
"greeting": [
"你好!很高興見到你!",
"哈囉~今天過得如何?",
"嗨,有什麼我可以幫忙的嗎?"
],
"farewell": [
"See you later!",
"再見!祝你有美好的一天!",
"拜拜~期待下次聊天!"
],
"query": [
"我是一個簡單的聊天機器人,隨時準備和你聊天!",
"我很好,謝謝你的關心!你呢?",
"我在這裡幫助你解答問題或是陪你聊天!"
],
"weather": [
"The weather is sunny today!",
"我目前無法提供天氣資訊,但你可以試著問問其他問題!",
"抱歉,我還在學習中,暫時無法回答天氣相關的問題。",
"我還不太懂天氣,但我可以陪你聊聊其他話題!"
],
"time": [
"The current time is " + datetime.datetime.now().strftime("%I:%M %p") + ".",
"我目前無法提供時間資訊,但你可以試著問問其他問題!",
"抱歉,我還在學習中,暫時無法回答時間相關的問題。",
"我還不太懂時間,但我可以陪你聊聊其他話題!"
]
}

def recognize_speech():
recognizer = sr.Recognizer()
with sr.Microphone() as source:
print("請說話...")
recognizer.adjust_for_ambient_noise(source, duration=1)
audio = recognizer.listen(source, timeout=5)

try:
text = recognizer.recognize_google(audio, language="zh-TW")
print(f"你說: {text}")
return text
except sr.UnknownValueError:
print("抱歉,我聽不懂你在說什麼")
return None
except sr.RequestError:
print("無法從 Google 服務取得結果")
return None
if __name__ == "__main__":
while True:
user_input = recognize_speech()
if user_input:
response = None
for intent, data in intents.items():
for pattern in data:
if pattern in user_input:
response = random.choice(responses[intent])
break
if response:
print(f"AI: {response}")
speak(response)
elif user_input in ["退出", "離開", "結束"]:
print("再見!")
speak("再見!")
break
else:
print("抱歉,我不太明白你的意思。")
speak("抱歉,我不太明白你的意思。")

終端機 測試






留言

這個網誌中的熱門文章

初探 Vue 呼叫 API 出現 CORS 跨來源資源共享 問題原因

提要:   在 {初探Vue 與 Spring boot 的對話} 專案 ,前端 Vue 應用程式 串接 後端 API 伺服器 ,axios 呼叫 API 時出現以下,”無法取得回應內容 (No 'Access-Control-Allow-Origin' header is present on the requested resource):” 錯誤訊息,根據查找相關資料 ,出現以下原因。 瀏覽器開發工具 錯誤訊息 畫面 錯誤原因: “ Access to XMLHttpRequest at ” from origin ‘http://localhost:8080’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource” 瀏覽器為了安全考量,實施了同源政策。 當您的前端應用程式 (http://localhost:8080) 嘗試呼叫一個不同來源 (不同協議、不同域名或不同埠號) 的 API 伺服器 (http://localhost:8088) 時,瀏覽器會主動阻止這個請求,除非伺服器明確地允許這個跨來源的存取。 同源政策限制(Same-Origin Policy): 同源政策限制了程式碼和不同網域資源間的互動,同源是指兩份網頁具備相同協定、埠號(如果有指定)以及主機位置 範例: 表列哪些 URL 與 URL http://www.example.com/api/p1 屬於同源: URL                                                   | 結果   | 原因 --------------------------------------------------------------------- http://www.example.com/api/p2     |...

初探 Vue 與 Spring boot 的對話之Frontend (Vue-Frontend)

  Front-end Vue 使用 REST API 建立 Vite 專案 可參考 { Vue 3 初探}  文章 danny@Danny-Yu projects % npm create vite@latest Need to install the following packages: create-vite@8.2.0 Ok to proceed? (y) y > npx > "create-vite" │ ◇   Project name: │   vue-frontend │ ◇   Select a framework: │   Vue │ ◇   Select a variant: │   TypeScript │ ◇   Use rolldown-vite (Experimental)?: │   No │ ◇   Install with npm and start now? │   Yes │ ◇   Scaffolding project in /Users/danny/Desktop/projects/vue-frontend... │ ◇   Installing dependencies with npm... added 47 packages, and audited 48 packages in 27s 6 packages are looking for funding   run `npm fund` for details found 0 vulnerabilities │ ◇   Starting dev server... > vue-frontend@0.0.0 dev > vite   VITE v7.2.4   ready in 411 ms   ➜   Local:   http://localhost:5173/   ➜   Network: use --host to expose   ➜   press h + enter to show...

初探 Spring 中的循環依賴

原因: 當兩個或多個 bean 直接或間接地相互依賴時, 就會出現 Circular Dependency (循環依賴) 如: Bean A -> Bean B -> Bean A import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class BeanA {          @Autowired     private BeanB beanB;     public String sayHi() {         return "Hi! 我是 Class A.";     } } import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class BeanB {          @Autowired     private BeanA beanA;     public String sayHi() {         return "Hi! 我是 Class B.";     } } 編譯時不會出現問題 danny@Danny-Yu demo % mvn clean install -Dmaven.test.skip=true                           ... ... [INFO] Installing /Users/danny/Desktop/projects/demo/target/dem...