Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีแปลง Text เป็น Speech ใน Python

Text to Speech ใน Python ด้วย gTTS

การแปลง Text to Speech หมายถึงโปรแกรมที่รับ Input เป็น Text และ Output เป็น Speech (เสียงพูด)

Python มี API สำหรับ Text-to-Speech หนึ่งในนั้นคือ Google Text-to-Speech (gTTS) สามารถแปลงข้อความเป็นเสียงและบันทึกเป็นไฟล์ Audio ได้

ขั้นตอนที่ 1: ติดตั้ง gTTS

pip install gTTS

ขั้นตอนที่ 2: เขียนโปรแกรมแปลง Text to Speech

  1. Import gTTS
  2. ระบุข้อความที่ต้องการแปลง
  3. เรียก gTTS() ซึ่งรับ 3 Parameter:
    • text: ข้อความ Input ที่ต้องการแปลง
    • lang: ภาษา (รองรับหลายภาษา: 'en', 'th', 'hi', 'fr', 'de', etc.)
    • slow: ความเร็วเสียง (True = ช้า, False = เร็ว)
  4. Output จะถูกคืนค่าให้ตัวแปร สามารถบันทึกเป็นไฟล์ .mp3 ได้
  5. เล่นไฟล์เสียงด้วย os.system() (ต้อง import os)

ตัวอย่างโค้ด

from gtts import gTTS
import os

myText = "I want to learn Python"
# หรือภาษาไทย
# myText = "ฉันอยากเรียน Python"

# สร้าง gTTS object
speech = gTTS(text=myText, lang="en", slow=False)

# บันทึกเป็นไฟล์ MP3
speech.save("tts.mp3")

# เล่นไฟล์เสียง (Windows)
os.system("start tts.mp3")

# Linux/Mac
# os.system("xdg-open tts.mp3")  # Linux
# os.system("open tts.mp3")      # Mac

ตัวอย่างเต็ม: รองรับหลายภาษา

from gtts import gTTS
import os

texts = {
    "en": "Hello, welcome to Python programming",
    "th": "สวัสดีครับ ยินดีต้อนรับสู่ Python",
    "ja": "こんにちは、Pythonへようこそ",
    "ko": "안녕하세요, 파이썬에 오신 것을 환영합니다",
    "zh": "你好,欢迎来到 Python"
}

for lang, text in texts.items():
    print(f"Generating {lang}...")
    tts = gTTS(text=text, lang=lang, slow=False)
    filename = f"welcome_{lang}.mp3"
    tts.save(filename)
    print(f"Saved: {filename}")

# เล่นไฟล์ภาษาไทย
os.system("start welcome_th.mp3")

ข้อจำกัดของ gTTS

  • ต้องการ Internet Connection (เรียก Google API)
  • มีข้อจำกัดความยาวข้อความ (~100-200 ตัวอักษรต่อ Request)
  • ไม่สามารถควบคุม Voice/Speaker ได้รายละเอียด

Alternative: pyttsx3 (Offline)

pip install pyttsx3
import pyttsx3

engine = pyttsx3.init()
engine.say("Hello, this works offline!")
engine.runAndWait()

# ปรับเสียง
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)  # Female voice
engine.setProperty('rate', 150)  # Speed
engine.say("Thai language may not be supported well")
engine.runAndWait()

หมายเหตุ: pyttsx3 รองรับภาษาไทยไม่ดีเท่า gTTS แนะนำใช้ gTTS สำหรับภาษาไทย