Voice Control 2026: Tự chế loa thông minh Jarvis bằng Python, Whisper (STT) và Piper (TTS) chạy Offline

AI Hunter

Member
Voice Control 2026: Tự chế loa thông minh Jarvis bằng Python, Whisper (STT) và Piper (TTS) chạy Offline

Bạn chán ngấy giọng đọc "chị Google" đều đều? Bạn sợ Alexa nghe lén chuyện gia đình?
Đã đến lúc tự xây dựng một "Jarvis" cho riêng mình.

Voice Control 2026 Tự chế loa thông minh Jarvis bằng Python, Whisper (STT) và Piper (TTS) chạy...jpg

Mục tiêu của bài viết này:
1. **Nghe (STT):** Dùng Faster-Whisper (OpenAI) để chuyển giọng nói thành văn bản cực nhanh.
2. **Nói (TTS):** Dùng Piper để tạo giọng đọc AI tự nhiên, độ trễ thấp (Real-time).
3. **Offline 100%:** Chạy mượt trên Laptop hoặc Raspberry Pi 5 mà không cần Internet.

1. Kiến trúc hệ thống​

Luồng xử lý (Pipeline) của chúng ta:
Microphone -> [Whisper] -> Text Command -> [Python Logic] -> Response Text -> [Piper] -> Speaker

2. Chuẩn bị môi trường​

Chúng ta cần cài đặt các thư viện Python xử lý âm thanh và model AI.

Bash:
# Cài đặt thư viện
pip install faster-whisper sounddevice numpy scipy

*Lưu ý về Piper:* Piper là một phần mềm chạy dòng lệnh (binary). Bạn cần tải file chạy của Piper và model giọng nói (file `.onnx`) từ trang chủ của dự án Piper (Github), sau đó giải nén vào thư mục dự án.

3. Triển khai Code (Python)​


Tạo file jarvis_voice.py.

Bước 1: Module "Tai" (Nghe - STT)​

Sử dụng `faster-whisper` (phiên bản tối ưu hóa của OpenAI Whisper) để nhận diện giọng nói.

Python:
from faster_whisper import WhisperModel
import sounddevice as sd
import numpy as np
import queue

# Cấu hình
MODEL_SIZE = "tiny" # Dùng 'base' hoặc 'small' nếu máy mạnh
print(f"👂 Đang tải model Whisper ({MODEL_SIZE})...")
model = WhisperModel(MODEL_SIZE, device="cpu", compute_type="int8")

def record_audio(duration=5, fs=16000):
    """Ghi âm từ microphone trong 5 giây"""
    print("🔴 Đang nghe...")
    recording = sd.rec(int(duration * fs), samplerate=fs, channels=1, dtype='float32')
    sd.wait() # Chờ ghi âm xong
    print("⏹️ Đã thu xong.")
    return recording.flatten()

def transcribe_audio(audio_data):
    """Chuyển âm thanh thành văn bản"""
    segments, info = model.transcribe(audio_data, beam_size=5)
    text = "".join([segment.text for segment in segments])
    return text.strip()

Bước 2: Module "Miệng" (Nói - TTS)​

Chúng ta gọi Piper thông qua `subprocess` để đọc văn bản. Giả sử bạn đã tải piper executable và model giọng nói (ví dụ: `en_US-ryan-medium.onnx`) về thư mục `./piper`.

Python:
import subprocess
import os

PIPER_PATH = "./piper/piper" # Đường dẫn file chạy Piper
VOICE_MODEL = "./piper/en_US-ryan-medium.onnx" # Đường dẫn model giọng nói

def speak(text):
    """Đọc văn bản ra loa bằng Piper"""
    print(f"🤖 Jarvis: {text}")
  
    command = f'echo "{text}" | {PIPER_PATH} --model {VOICE_MODEL} --output_raw | aplay -r 22050 -f S16_LE -t raw -'
  
    # Lưu ý: Lệnh trên dành cho Linux/Mac (dùng aplay).
    # Nếu trên Windows, bạn cần lưu ra file .wav rồi play bằng thư viện playsound.
    subprocess.run(command, shell=True)

Bước 3: Bộ não & Vòng lặp chính​

Kết nối tất cả lại. Ở đây tôi dùng logic `if/else` đơn giản. Bạn có thể thay thế bằng API của **Ollama (Llama 3)** để Jarvis thông minh hơn.

Python:
def process_command(text):
    text = text.lower()
    if "hello" in text:
        return "Hello sir. Systems are online."
    elif "time" in text:
        from datetime import datetime
        now = datetime.now().strftime("%H:%M")
        return f"It is currently {now}."
    elif "light" in text and "on" in text:
        # Code điều khiển IoT (Home Assistant) ở đây
        return "Turning on the lights."
    else:
        return "I did not understand that command."

def main():
    while True:
        input("Nhấn Enter để nói... (Ctrl+C để thoát)")
      
        # 1. Ghi âm
        audio_data = record_audio(duration=3) # Ghi âm 3s
      
        # 2. Nhận diện (STT)
        user_text = transcribe_audio(audio_data)
        print(f"🗣️ Bạn nói: {user_text}")
      
        if not user_text: continue

        # 3. Xử lý (Brain)
        response_text = process_command(user_text)
      
        # 4. Trả lời (TTS)
        speak(response_text)

if __name__ == "__main__":
    main()

4. Tối ưu hóa cho Raspberry Pi​

Để hệ thống chạy "nuột" trên phần cứng yếu như Pi:
  • Whisper Model: Bắt buộc dùng `tiny` hoặc `tiny.en` (nếu chỉ nói tiếng Anh). Dùng bản `int8` để giảm tải CPU.
  • Piper Voice: Chọn model `low` hoặc `medium` quality. Model `high` sẽ gây delay.
  • Microphone: Nên dùng Mic USB đa hướng (Omnidirectional) để bắt giọng tốt hơn.

5. Nâng cấp: Wake Word (Từ khóa đánh thức)​

Hiện tại chúng ta đang phải "Nhấn Enter" để nói. Để Jarvis luôn lắng nghe (như "Hey Siri"), bạn cần tích hợp thêm thư viện **Porcupine** hoặc **OpenWakeWord**.
Quy trình sẽ là:
Chờ Wake Word -> (Phát hiện) -> Ghi âm Whisper -> Xử lý -> Trả lời.

Kết luận​

Chúc mừng! Bạn đã sở hữu một hệ thống giao tiếp bằng giọng nói riêng tư, bảo mật và cực ngầu. Hãy kết nối nó với hệ thống Smart Home để bật tắt đèn bằng giọng nói như Iron Man thực thụ.
 
Back
Top