Skip to content

Instantly share code, notes, and snippets.

@felixmon
Created June 19, 2024 00:12
Show Gist options
  • Save felixmon/ff0af2d7d38c8909124f619fd8aba5a1 to your computer and use it in GitHub Desktop.
Save felixmon/ff0af2d7d38c8909124f619fd8aba5a1 to your computer and use it in GitHub Desktop.
text to speech with pause duration
from gtts import gTTS #updated 2024-06-19-081215
from pydub import AudioSegment
import os
def text_to_speech_with_pauses(text, lang='zh-CN', pause_duration=8000):
segments = text.split(',') # Split text at comma
combined = AudioSegment.silent(duration=0) # Start with an empty segment
for segment in segments:
tts = gTTS(text=segment, lang=lang)
temp_file = "temp.mp3"
tts.save(temp_file)
audio_segment = AudioSegment.from_file(temp_file, format="mp3")
combined += audio_segment + AudioSegment.silent(duration=pause_duration)
os.remove(temp_file) # Clean up temporary file
output_file = "output_with_pauses.mp3"
combined.export(output_file, format="mp3")
print(f"Output file saved as {output_file}")
if __name__ == "__main__":
text = '台湾岛,民族,情谊,奋发,节日,春节,花灯,清明节,先人,龙舟,中秋,转眼,团圆,热闹,动物,贝壳,自己,身体,甲骨文,样子,可以,钱币,钱财,有关,比如,美食,红烧,茄子,烤鸭,羊肉,蛋炒饭,课文,彩色,脚尖,森林,雪松,歌声,苹果,精灵,季节,好像,一直,说话,童话,称呼,对岸,发现,弟弟,游戏,发明,字母,周围,补充,公主,伙伴,飞机,地道,火药,合力,忘记,屁股'
text_to_speech_with_pauses(text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment