Speech Recognition เป็นฟีเจอร์สำคัญสำหรับ Home Automation, AI Assistant, Voice Control ใช้ไลบรารี SpeechRecognition ร่วมกับ Google Web Speech API
การติดตั้ง
pip install SpeechRecognition # สำหรับ Microphone (Linux) sudo apt-get install python3-pyaudio
การตั้งค่า Microphone
- Device Index: ระบุ Microphone ที่ถูกต้อง (ใช้
lsusbดู USB Device) - Chunk Size: ขนาดข้อมูลต่อครั้ง (Power of 2: 1024, 2048, 4096...)
- Sample Rate: อัตราการ Sample (Hz) เช่น 48000, 16000
- Ambient Noise Adjustment: ปรับระดับเสียงรบกวนรอบข้าง
ขั้นตอนการทำงาน
- ตั้งค่า Microphone Parameters
- ปรับ Ambient Noise
- รอฟังเสียงพูด
- ส่งไป Google Speech API แปลงเป็น Text
- จัดการ Error (UnknownValueError, RequestError)
โค้ดตัวอย่าง: ใช้ Microphone
import speech_recognition as sr
sample_rate = 48000
chunk_size = 8192
r = sr.Recognizer()
with sr.Microphone(sample_rate=sample_rate, chunk_size=chunk_size) as source:
r.adjust_for_ambient_noise(source)
print('Tell Something: ')
audio = r.listen(source)
try:
text = r.recognize_google(audio)
print('You said: ' + text)
except sr.UnknownValueError:
print('Unable to recognize audio')
except sr.RequestError as e:
print(f"Request error: {e}")
โค้ดตัวอย่าง: ใช้ Audio File
import speech_recognition as sr
r = sr.Recognizer()
sound_file = 'sample_audio.wav'
with sr.AudioFile(sound_file) as source:
audio = r.record(source) # ใช้ record แทน listen
try:
text = r.recognize_google(audio)
print('File contains: ' + text)
except sr.UnknownValueError:
print('Unable to recognize audio')
except sr.RequestError as e:
print(f"Request error: {e}")
ผลลัพธ์ตัวอย่าง
$ python3 speech_recognition.py Tell Something: You said: here we are considering the asymptotic notation... $ python3 speech_recognition_file.py File contains: staying ahead of the curve demand planning new technology...
เคล็ดลับและข้อจำกัด
- ต้องมี Internet (Google API)
- ภาษาไทย: รองรับได้ แต่ความแม่นยำขึ้นอยู่กับสำเนียง/เสียงรบกวน
- Offline Alternative: ใช้
voskหรือwhisper - Real-time Streaming: ใช้
r.listen_in_background()