我们从Python开源项目中,提取了以下47个代码示例,用于说明如何使用gtts.gTTS()。
def speak(text, lang='es'): """Text to speech. For funp.""" try: from googletrans import Translator from gtts import gTTS from pygame import mixer from tempfile import TemporaryFile translator = Translator() tts = gTTS(text=translator.translate(text, dest=lang).text, lang=lang) mixer.init() sf = TemporaryFile() tts.write_to_fp(sf) sf.seek(0) mixer.music.load(sf) mixer.music.play() except Exception: raise
def __init__(self, *commands, key=None, use_yandex=True, prefixes=None, strict=False): """Answers with audio message of user's text""" if not commands: commands = ["?????", "?????????"] super().__init__(*commands, prefixes=prefixes, strict=strict) if not key: self.key = "e02d4514-b2a7-4edb-8ee8-825f854ef890" else: self.key = key self.providers = [(lambda text, lang, key=None: gTTS(text=text, lang=lang)), (lambda text, lang, key=None: yTTS(text=text, lang=lang, key=key)),] if use_yandex: self.providers[0], self.providers[1] = self.providers[1], self.providers[0] example = self.command_example() self.description = [f"????? ? ????", f"{example} [????] - ?????????? ????? (+ ?????? ???????? ????? ??????? ???????)."]
def speak(say): endProg(command='music') print("GENERATING VOICE") tts = gTTS(text=say, lang='en') tts.save("voice/temp/temp.mp3") voice = "runuser -l pi -c 'cvlc --play-and-exit /home/pi/computer/voice/temp/temp.mp3' " subprocess.call(voice, shell=True) endProg(command="exit") return
def __init__(self, *args, **kwargs): plugin.TTSPlugin.__init__(self, *args, **kwargs) try: orig_language = self.profile['language'] except: orig_language = 'en-US' language = orig_language.lower() if language not in gtts.gTTS.LANGUAGES: language = language.split('-')[0] if language not in gtts.gTTS.LANGUAGES: raise ValueError("Language '%s' ('%s') not supported" % (language, orig_language)) self.language = language
def play_answer(self, action, software=None, text=None): if software: if not path.isfile("answers/{}_{}.mp3".format(action, software)): tts = gTTS( text="Très bien, je {} {}...".format(action, software), lang="fr") tts.save("answers/{}_{}.mp3".format(action, software)) notify("Alexa: Très bien, je {} {} ... ".format( action, software), self.icon) Popen(["mplayer", "answers/{}_{}.mp3".format(action, software)]) else: if not path.isfile("answers/{}.mp3".format(action)): tts = gTTS(text=text, lang="fr") tts.save("answers/{}.mp3".format(action)) notify("Alexa: {}".format(text), self.icon) call(["mplayer", "answers/{}.mp3".format(action)]) self.end = True #--------------------------------------------------------------#
def speak(out_string): """ Speaks using gTTs from the internet. """ path = os.getcwd() + "/Text_Files/ping_result.txt" path_os = path.replace(" ", "\ ") path_os = path_os.replace("(", "\(") path_os = path_os.replace(")", "\)") os.system("if ! ping -c 1 www.google.com>/dev/null;" "then echo fail >"+ path_os +";" "else echo success>"+ path_os + ";fi;") f_ping = open(path) result = f_ping.read().strip().split("\n") f_ping.close() print '\033[1m' + 'Tzara: ' + '\033[0m' + out_string if result[0] == 'success': tts = gTTS(text = out_string, lang = 'en') tts.save("hello.mp3") os.system("mpg321 -q hello.mp3")
def enqueue_tts(self, vchan: discord.Channel, text: str, vol: int=None, priority: int=5, tchan: discord.Channel=None, language: str=None): if vol is None: vol = self.tts_volume if language is None: language = self.language tts = gTTS(text=text, lang=language) path = self.temp_filepath + ''.join(random.choice( '0123456789ABCDEF') for i in range(12)) + ".mp3" tts.save(path) try: item = {'cid': vchan.id, 'path': path, 'vol': vol, 'priority': priority, 'delete': True, 'tchan': tchan} self.master_queue.put_nowait(item) return True except asyncio.QueueFull: return False
def process_message(self, msg): command, text = self.parse_message(msg, full_text=True) if not text: return await msg.answer('??????? ????? ??? ???????? ??? ? ????!') answer, answer_file = await self.create_audio(gTTS, text) if answer_file is None: return await msg.answer(answer) audio = await upload_audio_message(self.api, answer_file, msg.user_id) answer_file.close() return await msg.answer("", attachment=str(audio))
def __init__(self, bot): self.bot = bot.bot self.description = "*/voice* _<message>_ - using gTTS a voice message of _<message>_ is created" self.queue_in=Queue() #self.queue_out=Queue() thread.start_new_thread(self.run,()) #self.resttime=0 #self.lastcmd=0
def run(self): while 1: msg=self.queue_in.get() # get() is blocking chat_id=msg.get_chat_id() if re.search(r'^(?:/|!)voice ', msg.get_text().lower()) and len(msg.get_text().split(" "))>=2: tts=msg.get_text().split(" ",1)[1].lower().replace("Ä","ae").replace("ä","ae").replace("Ü","ue").replace("ü","ue").replace("Ö","oe").replace("ö","oe").replace("ß","ss") with tempfile.NamedTemporaryFile(suffix=".mp3") as temporaryfile: gtts.gTTS(text=tts,lang="de").write_to_fp(temporaryfile) temporaryfile.seek(0) self.bot.sendAudio(chat_id,temporaryfile,title="Abb1tvoice")
def make_tts_file(content, lang): fp = mktemp() tts = gTTS(text=content, lang=lang) tts.save(fp) return fp
def get_speech(self, phrase): if self.language not in self.languages: raise ValueError("Language '%s' not supported by '%s'", self.language, self.SLUG) tts = gtts.gTTS(text=phrase, lang=self.language) with tempfile.NamedTemporaryFile(suffix='.mp3', delete=False) as f: tmpfile = f.name tts.save(tmpfile) return tmpfile
def play_tts(text, lang='en', slow=False): tts = gTTS(text=text, lang=lang, slow=slow) filename = slugify(text+"-"+lang+"-"+str(slow)) + ".mp3" path = "/static/cache/" cache_filename = "." + path + filename tts_file = Path(cache_filename) if not tts_file.is_file(): logging.info(tts) tts.save(cache_filename) urlparts = urlparse(request.url) mp3_url = "http://" +urlparts.netloc + path + filename logging.info(mp3_url) play_mp3(mp3_url)
def speak(whattosay): print (whattosay) audio_file = "response.mp3" tts = gTTS(text=str(whattosay), lang="en") tts.save(audio_file) playsound(audio_file) os.remove(audio_file)
def speak(self, whattosay): """ Converts text to speech :param whattosay: Text to speak """ print (self.name.upper() + " > " + whattosay) audio_file = "response.mp3" tts = gTTS(text=str(whattosay), lang="en") tts.save(audio_file) self.playsound(audio_file) os.remove(audio_file)
def recognize_from_google(self, text): try: self.tts = gTTS(text=text, lang='en') return True except Exception: raise Exception
def read_nicely_text(txt, instance_vlc, player_vlc): tts = gTTS(text=txt,lang='en') tts.save("rss_read.mp3") media = instance_vlc.media_new("rss_read.mp3") player_vlc.set_media(media) player_vlc.play()
def GenerateAudio(text, output_path, audio_accent): print "Generating Audio." ttsKey = gTTS(text=text, lang=audio_accent) ttsKey.save(output_path)
def speak_tts(ttstext, language="en-us"): tts = gTTS(text=ttstext, lang=language) tts.save("answer.mp3") call(["mpg123", "answer.mp3"]) # turn_on_led schaltet die LED an.
def say(self, phrase, *args): self._logger.debug("Saying '%s' with '%s'", phrase, self.SLUG) if self.language not in self.languages: raise ValueError("Language '%s' not supported by '%s'", self.language, self.SLUG) tts = gtts.gTTS(text=phrase, lang=self.language) with tempfile.NamedTemporaryFile(suffix='.mp3', delete=False) as f: tmpfile = f.name tts.save(tmpfile) self.play_mp3(tmpfile) os.remove(tmpfile)
def speakResponse(response): #tts = gTTS(text=response, lang='en') tts = gTTS(text=response, lang='en') tts.save("resources/bot_output.wav") os.system("start resources/bot_output.wav")
def speak(self, text): """ Processes the text and reproduces it (TTS method) """ tts = gTTS(text=(text), lang='en') path = os.path.dirname(os.path.realpath(__file__)) tts.save(path+"/data/speech.mp3") os.system("mpg321 "+path+ "/data/speech.mp3 -quiet")
def requested_donna_audio(): response_donna = "Hello Kevin, sure give me a moment!" tts = gTTS(text= response_donna, lang='en') # Google text to speech requires MP3 file tts.save('response_donna.mp3') # We are using Alsa as output to play the MP3 os.system('mpg321 -o alsa response_donna.mp3') os.remove('response_donna.mp3')
def addedSong(title): donna = "Hello, I just added the song: {} to your favorites on Youtube! Have a nice day".format(title) tts = gTTS(text= donna, lang='en') tts.save('added_default.mp3') os.system('mpg321 -o alsa added_default.mp3') os.remove('added_default.mp3')
def speak(engine, message): try: tts = gTTS(text=message, lang='en') tts.save('out.mp3') system('mpg123 out.mp3 && rm out.mp3') except: engine.say(message) engine.runAndWait()
def say(self,text,lang,priority,volume="00"): ############################################ # the TTS function. make a mp3 from the text # and put a file in the prioritylist ############################################ self.soundlog("say; put text in waitingrow: " + text) with tempfile.NamedTemporaryFile(suffix='.mp3', delete=False) as f: fname = f.name tts = gTTS(text=text, lang=lang) tts.save(fname) self. write_in_prioritylist(priority,fname,"1",volume)
def say(self, phrase): tts = gtts.gTTS(text=phrase, lang=self.language) with tempfile.NamedTemporaryFile(suffix='.mp3', delete=False) as f: tmpfile = f.name tts.save(tmpfile) data = self.mp3_to_wave(tmpfile) os.remove(tmpfile) return data
def chatter(bot,update): chat_id = update.message.chat_id message = update.message.text if message == 'foto': bot.sendChatAction(chat_id=chat_id, action=telegram.ChatAction.UPLOAD_PHOTO) bot.sendPhoto(chat_id=chat_id, photo='https://unsplash.it/600?random') else: k = aiml.Kernel() k.learn("std-startup.xml") k.respond("sara") k.setBotPredicate("name", "Sara") k.setBotPredicate("anyo_nacimiento", "2015") k.setBotPredicate("edad", str(date.today().year-2015) ) k.setBotPredicate("botmaster", 'Alexander' ) k.setBotPredicate("nombre_bot", 'Sara' ) k.setBotPredicate("birthday", '17/12/2015' ) bot.sendChatAction(chat_id=chat_id, action=telegram.ChatAction.TYPING) response = k.respond(message) #bot.sendMessage(chat_id, text=response) tts = gTTS(text=response, lang='es') file = str(chat_id) + str(time.time()) + '.ogg' tts.save(file) bot.sendVoice(chat_id=chat_id, voice=open(file, 'rb')) os.remove(file)
def tts_save(filename, text, lang): # run_command(["pico2wave", "--wave", filename, "-l", "en-GB", text]) try: tts = gTTS(text=text, lang=lang) tts.save(filename) except AttributeError: raise UserError("Whoops. Looks like gtts is broken right now.") except (RecursionError, requests.exceptions.HTTPError): raise UserError("There was a problem converting that via gtts")
def speak_text(self, text): """Speak a single text""" from gtts import gTTS tts = gTTS(text=text, lang=self.lang) # save the speech to temp file tmp_file = NamedTemporaryFile() tts.write_to_fp(tmp_file) # play it with pyaudio from utils.ev3 import audio audio.play(tmp_file.name) # remove it tmp_file.close()
def generate_tts(text, lang): tts = gTTS(text=text, lang=lang) filename = datetime.now() if not os.path.exists('audios'): os.makedirs('audios') tts.save('audios/%s.ogg'%filename) return filename
def to_speech(text): tts = gTTS(text=text, lang = 'en') return tts
def tts_voice_clip(voice_client, text): with(yield from tts_lock): tts = gTTS(text=text, lang='en') tts.save('data/tts.mp3') yield from voice_clip(voice_client, 'data/tts.mp3') os.remove('data/tts.mp3')
def text_to_speech(txt, language): tts = gTTS(text=u''+txt, lang=language, slow=False) #tts = gTTS(text='What the hell are you doing? Cannot you do it properly.', lang='hi', slow=False) #tts = gTTS(text="Dans l'arriere-pays de Provence, 30 kilometres au sud-ouest de Draguignan", lang='fr', slow=False) tts.save('hello.mp3')
def speech(self, narration, lang, voice=None, **kwargs): """ Returns the get HTTP response by doing a GET to /v1/synthesize with text, voice, accept """ resp = gTTS(text=narration, lang=lang) resp.save('/tmp/google.mp3') content = open('/tmp/google.mp3', 'rb').read() return content, 'mp3'
def speak(text): if connectionStatus()==True: path = homeDir + "/Downloads/speech.mp3" tts = gTTS(text, lang="hi") tts.save(path) getoutput("mpg123 " + path) else: call(['say', text]) #wikipedia coreection
def tts(self, ctx, *text: str): """Play a TTS clip in your current channel""" if not gTTS_avail: await self.bot.say("You do not have gTTS installed.") return vchan = ctx.message.author.voice_channel if vchan is None: await self.bot.say("You are not connected to a voice channel.") return self.enqueue_tts(vchan, " ".join(text))
def SpeakWord( word ): tts = gTTS(text=word, lang='en') tts.save("Sounds/LastSpoken.mp3") s.sudo("mpg123 Sounds/LastSpoken.mp3").run()
def makeSpeech(poem,poem_filename, voice): tts = gTTS(text=poem, lang=voice) tts.save(poem_filename)
def __init__(self): self.tts_engine = gTTS(' ') self.filename = ''
def execute(self, text, filename='current_text.mp3'): self.tts_engine = gTTS(text=text, lang='en') self.filename = filename self.tts_engine.save(savefile=self.filename) os.system('mpg321 current_text.mp3 2> /dev/null') self.post_execute() pass
def play_message(message, language="en-us"): audio_mp3_file = "/tmp/audio.mp3" text_to_message = gTTS(message, language) text_to_message.save(audio_mp3_file) play_audio_file(audio_mp3_file)
def make_an_audio(url, filename, lang=None): if lang is None: lang = 'en' article = Article(url) article.download() article.parse() tts = gTTS(text=article.text, lang=lang) f = open(join('audio', filename), 'wb') tts.write_to_fp(f) f.close()
def say_loading(): speech = "checking weather..." print("[AUDIO]", speech) filename = 'loading.mp3' if not os.path.isfile('./' + filename): print("[TTS] generating: " + filename) tts = gTTS(text=speech, lang='en').save(filename) play_sound(filename)
def say_weather(speech): filename = 'weather.mp3' print("[TTS] generating weather speech...") tts = gTTS(text=speech, lang='en').save(filename) print("[AUDIO]", speech) play_sound(filename)
def say(self, message, speak_aloud=True, title='Speak'): # May eventually be moved into its own plugin message = str(message) if not message.strip(): click.echo("No text to speak.") return computer_os = system() folder = os.path.split(title)[0] folder_path = os.path.join(self.speech_file_location, folder) if not os.path.exists(folder_path): os.makedirs(folder_path) home = settings['home'] if self.input_system == 'google': # Create the MP3 file which will speak the text title += '.wav' path = os.path.join(home, title) tts = gTTS(message, lang=self.spoken_language) tts.save(path) speech_file = "start /MIN {}" if computer_os != 'Windows': speech_file = "mpg123 {}" speech_file = speech_file.format(os.path.join(home, title)) else: # Create the Visual Basic code which will speak the text title += '.vbs' path = os.path.join(home, title) message = re.sub('["\n\t]', '', message) # Strip out characters that would be spoken by the system. if computer_os == "Windows": with open(path, 'w') as file: file.write( """ speaks="{}" Dim speaks, speech Set speech=CreateObject("sapi.spvoice") speech.Speak speaks """.format(message)) # Set up the file to be executed speech_file = ["cscript.exe", title] if computer_os != "Windows": speech_file = ["espeak", message] if speak_aloud: try: call(speech_file) except FileNotFoundError: if self.debugging: click.echo("File not accessible:" + str(speech_file))