本文整理汇总了Python中google.cloud.texttospeech.TextToSpeechClient方法的典型用法代码示例。如果您正苦于以下问题:Python texttospeech.TextToSpeechClient方法的具体用法?Python texttospeech.TextToSpeechClient怎么用?Python texttospeech.TextToSpeechClient使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类google.cloud.texttospeech
的用法示例。
在下文中一共展示了texttospeech.TextToSpeechClient方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: generateAudioClip
# 需要导入模块: from google.cloud import texttospeech [as 别名]
# 或者: from google.cloud.texttospeech import TextToSpeechClient [as 别名]
def generateAudioClip(self):
self.text = self.text.replace("<NL>", "")
self.text = self.text.replace("\"", "'")
if self.text == ".":
self.text = " "
elif self.text == "":
self.text = " "
self.text = self.text.replace("*", " ")
self.text = self.text.replace("\"", " ")
self.text = self.text.replace("\n", " ")
#if not using google tts use balcon as default
if settings.use_google_tts:
client = texttospeech.TextToSpeechClient()
synthesis_input = texttospeech.types.SynthesisInput(text=self.text)
voice = texttospeech.types.VoiceSelectionParams(
language_code=settings.google_tts_language_code,
name=settings.google_tts_voice,
ssml_gender=texttospeech.enums.SsmlVoiceGender.MALE)
audio_config = texttospeech.types.AudioConfig(
audio_encoding=texttospeech.enums.AudioEncoding.LINEAR16)
response = client.synthesize_speech(synthesis_input, voice, audio_config)
with open(self.audio_path2, 'wb') as out:
out.write(response.audio_content)
if settings.use_balcon:
command = "%s -t \"%s\" -n %s -w %s" % (settings.balcon_location,
self.text, settings.balcon_voice, "\"" + self.audio_path2 + "\"")
process = subprocess.call(command, shell=True)
开发者ID:HA6Bots,项目名称:Automatic-Youtube-Reddit-Text-To-Speech-Video-Generator-and-Uploader,代码行数:38,代码来源:imageframe.py
示例2: process_input_files
# 需要导入模块: from google.cloud import texttospeech [as 别名]
# 或者: from google.cloud.texttospeech import TextToSpeechClient [as 别名]
def process_input_files(input_path: Path,
output_directory_path: Path,
client: texttospeech.TextToSpeechClient,
voice: texttospeech.types.VoiceSelectionParams,
audio_config: texttospeech.types.AudioConfig
) -> None:
"""
Process every file inside `input_directory_path` and save results in `output_directory_path`.
:param input_path: Full path to the input directory or a singular file (inside the mapped input directory).
:param output_directory_path: Full path to the output directory.
:param client: TextToSpeechClient instance.
:param voice: VoiceSelectionParams instance.
:param audio_config: AudioConfig instance.
:return: None
"""
if input_path.is_dir():
input_files = collect_input_files(input_directory_path=input_path)
processed_files = 0
for input_file in input_files:
process_input_file(client=client, voice=voice, audio_config=audio_config, input_file=input_file,
output_directory_path=output_directory_path)
processed_files += 1
logger.info(f'Files processed from input directory {input_path}: {processed_files}.')
else:
process_input_file(client=client, voice=voice, audio_config=audio_config, input_file=input_path,
output_directory_path=output_directory_path)
示例3: main
# 需要导入模块: from google.cloud import texttospeech [as 别名]
# 或者: from google.cloud.texttospeech import TextToSpeechClient [as 别名]
def main():
client = texttospeech.TextToSpeechClient()
available_voices = list_voices(client=client)
args = parse_arguments()
if args.list_voices:
print(f'Available voices\n{available_voices}\n')
return
use_voice = args.voice
if use_voice not in available_voices:
exit('Invalid voice! Use -list-voices to see all available options.')
use_language = '-'.join(use_voice.split('-')[0:2])
logger.info(f'Using voice `{use_voice}` in language `{use_language}`')
voice = texttospeech.types.VoiceSelectionParams(language_code=use_language, name=use_voice)
audio_config = texttospeech.types.AudioConfig(audio_encoding=texttospeech.enums.AudioEncoding.MP3)
if args.input:
input_path = Path('/data/input') / Path(args.input)
else:
input_path = Path('/data/input')
process_input_files(
input_path=input_path, output_directory_path=Path('/data/output'),
client=client, voice=voice, audio_config=audio_config
)
logger.info('Done!')
logger.info('Failures have been saved next to their respective output files.')
示例4: __init__
# 需要导入模块: from google.cloud import texttospeech [as 别名]
# 或者: from google.cloud.texttospeech import TextToSpeechClient [as 别名]
def __init__(self, params):
super().__init__(params)
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = self.params['google-speech-to-text-credential-file']
# Instantiates a client
self.client = texttospeech.TextToSpeechClient()
# Build the voice request, select the language code ("en-US") and the ssml
# voice gender ("neutral")
self.voice = texttospeech.types.VoiceSelectionParams(
language_code='en-US',
ssml_gender=texttospeech.enums.SsmlVoiceGender.NEUTRAL)
# Select the type of audio file you want returned
self.audio_config = texttospeech.types.AudioConfig(
audio_encoding=texttospeech.enums.AudioEncoding.MP3)
示例5: say
# 需要导入模块: from google.cloud import texttospeech [as 别名]
# 或者: from google.cloud.texttospeech import TextToSpeechClient [as 别名]
def say(self,
text: str,
language: Optional[str] = None,
voice: Optional[str] = None,
gender: Optional[str] = None,
player_args: Optional[List[str]] = None):
"""
Say a phrase.
:param text: Text to say.
:param language: Language code override.
:param voice: Voice type override.
:param gender: Gender override.
:param player_args: Player args override.
"""
from google.cloud import texttospeech
client = texttospeech.TextToSpeechClient()
synthesis_input = texttospeech.types.SynthesisInput(text=text)
language = self._parse_language(language)
voice = self._parse_voice(language, voice)
if gender is None:
gender = self.gender
else:
gender = getattr(texttospeech.enums.SsmlVoiceGender, gender.upper())
player_args = player_args or self.player_args
voice = texttospeech.types.VoiceSelectionParams(
language_code=language, ssml_gender=gender,
name=voice)
audio_config = texttospeech.types.AudioConfig(
audio_encoding=texttospeech.enums.AudioEncoding.MP3)
response = client.synthesize_speech(synthesis_input, voice, audio_config)
with tempfile.NamedTemporaryFile() as f:
f.write(response.audio_content)
cmd = ['mplayer -ao alsa -really-quiet -noconsolecontrols {} "{}"'.format(
' '.join(player_args), f.name)]
try:
return subprocess.check_output(
cmd, stderr=subprocess.STDOUT, shell=True).decode('utf-8')
except subprocess.CalledProcessError as e:
raise RuntimeError(e.output.decode('utf-8'))
# vim:sw=4:ts=4:et:
示例6: text_to_speech
# 需要导入模块: from google.cloud import texttospeech [as 别名]
# 或者: from google.cloud.texttospeech import TextToSpeechClient [as 别名]
def text_to_speech(text, outfile):
"""Converts plaintext to SSML and
generates synthetic audio from SSML
ARGS
text: text to synthesize
outfile: filename to use to store synthetic audio
RETURNS
nothing
"""
# Replace special characters with HTML Ampersand Character Codes
# These Codes prevent the API from confusing text with
# SSML commands
# For example, '<' --> '<' and '&' --> '&'
escaped_lines = html.escape(text)
# Convert plaintext to SSML in order to wait two seconds
# between each line in synthetic speech
ssml = '<speak>{}</speak>'.format(
escaped_lines.replace('\n', '\n<break time="2s"/>'))
# Instantiates a client
client = texttospeech.TextToSpeechClient()
# Sets the text input to be synthesized
synthesis_input = texttospeech.SynthesisInput(ssml=ssml)
# 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
request = texttospeech.SynthesizeSpeechRequest(
input=synthesis_input,
voice=voice,
audio_config=audio_config
)
response = client.synthesize_speech(request=request)
# 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)
# [END translate_hybrid_tts]
# [START translate_hybrid_integration]
示例7: text_to_mp3
# 需要导入模块: from google.cloud import texttospeech [as 别名]
# 或者: from google.cloud.texttospeech import TextToSpeechClient [as 别名]
def text_to_mp3(client: texttospeech.TextToSpeechClient,
voice: texttospeech.types.VoiceSelectionParams,
audio_config: texttospeech.types.AudioConfig,
text: str,
output_file_path: Path) -> None:
"""
Convert a string into voice and save it in an .mp3 file.
:param client: TextToSpeechClient instance.
:param voice: VoiceSelectionParams instance.
:param audio_config: AudioConfig instance.
:param text: String to synthesise.
:param output_file_path: Full path to the output .mp3 file.
:return: None
"""
lines = text.splitlines()
logger.info(f'Synthesising {len(lines)} lines ...')
output_file_log = output_file_path.parent / (output_file_path.stem + '_log.json')
with output_file_path.open(mode='wb') as output_file:
for (i, text_chunk) in enumerate(lines):
# skip empty lines
if len(text_chunk) > 0:
input_text = texttospeech.types.SynthesisInput(text=text_chunk)
try:
logger.info(f'Synthesising speech for chunk `{i}`, size: `{len(text_chunk)}`')
response = client.synthesize_speech(input_text, voice, audio_config)
except Exception as e:
# If a line could not be synthesised properly, return it along with the error message
# It is possible that textract could not extract the text properly.
logger.error(f'Speech synthesising failed! Chunk text: `{input_text}`\nError: {e}\n')
_error_log = {
'chunk_number': i,
'chunk_length': len(text_chunk),
'chunk_text': str(text_chunk),
'Error message': traceback.format_exc()
}
with open(f'{output_file_log}', 'w') as log_out:
json.dump(_error_log, log_out)
continue
output_file.write(response.audio_content)
logger.info(f'Audio content written to `{output_file_path}`!')
logger.info(f'Output saved to `{output_file_path}`')
logger.info(f'logs at `{output_file_log}`')
示例8: setup
# 需要导入模块: from google.cloud import texttospeech [as 别名]
# 或者: from google.cloud.texttospeech import TextToSpeechClient [as 别名]
def setup(robot_config):
global tempDir
global client
global voice
global hwNum
global audio_config
global keyFile
global languageCode
global voicePitch
global voiceSpeakingRate
global ssmlEnabled
global randomVoices
global messenger
ssmlEnabled = robot_config.getboolean('google_cloud', 'ssml_enabled')
voice = robot_config.get('google_cloud', 'voice')
keyFile = robot_config.get('google_cloud', 'key_file')
languageCode = robot_config.get('google_cloud', 'language_code')
voicePitch = robot_config.getfloat('google_cloud', 'voice_pitch')
voiceSpeakingRate = robot_config.getfloat(
'google_cloud', 'voice_speaking_rate')
messenger = robot_config.getboolean('messenger', 'enable')
if robot_config.has_option('google_cloud', 'random_voices'):
randomVoices = robot_config.getboolean('google_cloud', 'random_voices')
else:
randomVoices = False
if robot_config.has_option('tts', 'speaker_num'):
hwNum = robot_config.get('tts', 'speaker_num')
else:
hwNum = robot_config.get('tts', 'hw_num')
client = texttospeech.TextToSpeechClient(
credentials=service_account.Credentials.from_service_account_file(
keyFile)
)
if randomVoices:
import extended_command
extended_command.add_command('.new_voice', new_voice)
audio_config = texttospeech.types.AudioConfig(
audio_encoding=texttospeech.enums.AudioEncoding.LINEAR16,
pitch=voicePitch,
speaking_rate=voiceSpeakingRate
)
tempDir = tempfile.gettempdir()