2024年8月27日 星期二

用Python把文字檔轉語音

以下程式是使用ChatGPT產生。

範例一、使用gTTS套件

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
# Import the Gtts module for text  
# to speech conversion 
from gtts import gTTS 
  
# import Os module to start the audio file
import os 


fh = open("test2.txt", "r",encoding="utf-8")
mytext = fh.read().replace("\n", " ")  
  
# Language we want to use 
language = "zh-tw"
myobj = gTTS(text=mytext, lang=language, slow=False) 
myobj.save("output.mp3") 
  
# Play the converted file 
os.system("output.mp3")


範例二、使用pyttsx3套件

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import pyttsx3
from pydub import AudioSegment
from pydub.playback import play
import tempfile

# Initialize the pyttsx3 engine
engine = pyttsx3.init()

# Open and read the text file
with open("test2.txt", "r", encoding="utf-8") as fh:
    mytext = fh.read().replace("\n", " ")

# Set the voice to Chinese (Taiwanese Mandarin) if available
voices = engine.getProperty('voices')
for voice in voices:
    if 'zh' in voice.languages:  # Filter for Chinese language
        engine.setProperty('voice', voice.id)
        break

# Adjust the rate (speed of speech) and volume
engine.setProperty('rate', 150)  # Speed of speech
engine.setProperty('volume', 1.0)  # Volume level between 0 and 1

# Create a temporary file to save the audio output
with tempfile.NamedTemporaryFile(delete=False, suffix='.wav') as temp_audio_file:
    temp_audio_path = temp_audio_file.name

# Save speech to the temporary WAV file
engine.save_to_file(mytext, temp_audio_path)
engine.runAndWait()

# Convert the WAV file to MP3 using pydub
sound = AudioSegment.from_wav(temp_audio_path)
sound.export("output.mp3", format="mp3")

print("Audio saved as output.mp3")


沒有留言:

張貼留言