在谷歌文本到语音转换中添加暂停



我正在寻找一个小的停顿,等待,休息或任何允许短暂休息的东西(寻找大约2秒+-,可配置将是理想的(说出所需的文本。

网上的人说,添加三个句号后跟一个空格会产生休息时间,但我似乎不明白这一点。可悲的是,下面的代码是我没有暂停的测试。 有什么想法或建议吗?

编辑:如果 gTTS 有一些命令允许我这样做,或者如果确实有效,那么使用三个句号之类的技巧将是理想的选择。

from gtts import gTTS
import os
tts = gTTS(text=" Testing ... if there is a pause ... ... ... ... ...  longer pause? ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... insane pause   " , lang='en', slow=False)
tts.save("temp.mp3")
os.system("temp.mp3")

好的,您需要语音合成标记语言(SSML(来实现此目的.
请注意,您需要设置Google Cloud Platform凭据

首先在抨击中:

pip install --upgrade google-cloud-texttospeech

那么这是代码:

import html
from google.cloud import texttospeech
def ssml_to_audio(ssml_text, outfile):
# Instantiates a client
client = texttospeech.TextToSpeechClient()
# Sets the text input to be synthesized
synthesis_input = texttospeech.SynthesisInput(ssml=ssml_text)
# Builds the voice request, selects the language code ("en-US") and
# the SSML voice gender ("MALE")
voice = texttospeech.VoiceSelectionParams(
language_code="en-US", ssml_gender=texttospeech.SsmlVoiceGender.MALE
)
# Selects the type of audio file to return
audio_config = texttospeech.AudioConfig(
audio_encoding=texttospeech.AudioEncoding.MP3
)
# Performs the text-to-speech request on the text input with the selected
# voice parameters and audio file type
response = client.synthesize_speech(
input=synthesis_input, voice=voice, audio_config=audio_config
)
# Writes the synthetic audio to the output file.
with open(outfile, "wb") as out:
out.write(response.audio_content)
print("Audio content written to file " + outfile)
def text_to_ssml(inputfile):
raw_lines = inputfile
# Replace special characters with HTML Ampersand Character Codes
# These Codes prevent the API from confusing text with
# SSML commands
# For example, '<' --> '&lt;' and '&' --> '&amp;'
escaped_lines = html.escape(raw_lines)
# Convert plaintext to SSML
# Wait two seconds between each address
ssml = "<speak>{}</speak>".format(
escaped_lines.replace("n", 'n<break time="2s"/>')
)
# Return the concatenated string of ssml script
return ssml

text = """Here are <say-as interpret-as="characters">SSML</say-as> samples.
I can pause <break time="3s"/>.
I can play a sound"""
ssml = text_to_ssml(text)
ssml_to_audio(ssml, "test.mp3")

更多文档:
使用 SSML 说话地址

但是如果你没有Google Cloud Platform 凭据,更便宜、更简单的方法是使用 time.sleep(1( 方法

如果需要任何后台等待,您可以使用时间模块进行等待,如下所示。

import time
# SLEEP FOR 5 SECONDS AND START THE PROCESS
time.sleep(5)

或者你可以做一个3次检查与等待等。

import time
for tries in range(3):
if someprocess() is False:
time.sleep(3)

您可以存储多个 mp3 文件,然后使用time.sleep()以所需的暂停时间调用每个文件:

from gtts import gTTS
import os
from time import sleep
tts1 = gTTS(text="Testingn" , lang='en', slow=False)
tts2 = gTTS(text="if there is a pause" , lang='en', slow=False)
tts3 = gTTS(text="insane pause   " , lang='en', slow=False)
tts1.save("temp1.mp3")
tts2.save("temp2.mp3")
tts3.save("temp3.mp3")
os.system("temp1.mp3")
sleep(2)
os.system("temp2.mp3")
sleep(3)
os.system("temp3.mp3")

可悲的是答案是否定的,gTTS 包没有用于pause的附加功能,2018 年已经创建了一个用于添加暂停功能的问题,但它足够智能,可以通过分词器添加自然暂停。

什么是分词器?

获取文本并将其拆分为标记(字符串(列表的函数。在 gTTS 上下文中,其目标是 将文本剪切成不超过每个 TTS API 允许的最大字符大小 (100( 的较小段 请求,同时使演讲听起来自然而连续。它通过拆分语音将要包含的文本来做到这一点 自然暂停(例如在"."上(,同时处理不应该处理的地方(例如在"10.5"或"美国"上(。 这样的规则称为分词器案例,它需要一个列表。

下面是一个示例:

text = "regular text speed no pause regular text speed comma pause, regular text speed period pause. regular text speed exclamation pause! regular text speed ellipses pause... regular text speed new line pause n regular text speed "

因此,在这种情况下,添加sleep()似乎是唯一的答案。但是欺骗分词器值得一提。

您可以通过保存和连接临时 mp3 来使用 Pydub 添加任意暂停。然后,您可以使用静音音频进行暂停。 您可以在要添加暂停的位置使用您选择的任何断点符号(此处为 $(:

from pydub import AudioSegment
from gtts import gTTS
contents = "Hello with $$ 2 seconds pause"
contents.split("$") # I have chosen this symbol for the pause.
pause2s = AudioSegment.from_mp3("silent.mp3") 
# silent.mp3 contain 2s blank mp3 
cnt = 0
for p in parts:
# The pause will happen for the empty element of the list
if not p:
combined += pause2s
else:
tts = gTTS(text=p , lang=langue, slow=False)
tmpFileName="tmp"+str(cnt)+".mp3"
tts.save(tmpFileName)
combined+=AudioSegment.from_mp3(tmpFileName) 
cnt+=1

combined.export("out.mp3", format="mp3")  

派对来晚了,但您可以考虑尝试audio_program_generator包。您提供一个由各个短语组成的文本文件,每个短语的末尾都有一个可配置的停顿。作为回报,它为您提供了一个mp3文件,将所有短语及其停顿"拼接"成一个连续的音频文件。您也可以选择在背景声音文件中进行混音。它实现了Google TTS提供的其他几个花里胡哨的功能,如口音,慢播放语音等。

免责声明:我是该软件包的作者。

我遇到了同样的问题,不想在磁盘上使用很多临时文件。此代码解析 SSML 文件,并在找到<break>标记时创建静默:

import io
from gtts import gTTS
import lxml.etree as etree
import pydub
ssml_filename = 'Section12.35-edited.ssml'
wav_filename = 'Section12.35-edited.mp3'
events = ('end',)
DEFAULT_BREAK_TIME = 250
all_audio = pydub.AudioSegment.silent(100)
for event, element in etree.iterparse(
ssml_filename,
events=events,
remove_comments=True,
remove_pis=True,
attribute_defaults=True,
):
tag = etree.QName(element).localname
if tag in ['p', 's'] and element.text:
tts = gTTS(element.text, lang='en', tld='com.au')
with io.BytesIO() as temp_bytes:
tts.write_to_fp(temp_bytes)
temp_bytes.seek(0)
audio = pydub.AudioSegment.from_mp3(temp_bytes)
all_audio = all_audio.append(audio)
elif tag == 'break':
# write silence to the file.
time = element.attrib.get('time', None)  # Shouldn't be possible to have no time value.
if time:
if time.endswith('ms'):
time_value = int(time.removesuffix('ms'))
elif time.endswith('s'):
time_value = int(time.removesuffix('s')) * 1000
else:
time_value = DEFAULT_BREAK_TIME
else:
time_value = DEFAULT_BREAK_TIME
silence = pydub.AudioSegment.silent(time_value)
all_audio = all_audio.append(silence)
with open(wav_filename, 'wb') as output_file:
all_audio.export(output_file, format='mp3')

我知道4Rom1在上面使用了这种方法,但更简单地说,我发现这对我来说真的很有效。得到一个 1 秒无声 mp3,我通过谷歌搜索 1 秒无声 mp3 找到了一个。然后使用 pydub 将音频片段添加在一起,无论您需要多少次。例如,添加 3 秒的静音

from pydub import AudioSegment
seconds = 3
output = AudioSegment.from_file("yourfile.mp3")
output += AudioSegment.from_file("1sec_silence.mp3") * seconds
output.export("newaudio.mp3", format="mp3")

最新更新