How to use gTTS - 10 common examples

To help you get started, we’ve selected a few gTTS examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github flapjax / FlapJack-Cogs / sfx / sfx.py View on Github external
def enqueue_tts(self, vchan: discord.VoiceChannel,
                           text: str,
                            vol: int=None,
                       priority: int=5,
                          tchan: discord.TextChannel=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': False, 'tchan': tchan}
            self.master_queue.put_nowait(item)
            return True
        except asyncio.QueueFull:
            return False
github NaomiProject / Naomi / plugins / tts / google-tts / google.py View on Github external
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
github nimotli / SmartAssistantArab / rendez-vous.py View on Github external
if month in text:
                    foundMonth=True
                    monthvalue = months.index(month)+1
                    if monthvalue<= 9:
                        monthvalue="0"+str(monthvalue)
                        noveau_text= text.replace(month,monthvalue)
                        tts=gTTS(repns1,"ar")
                        tts.save("audioBase/repns1.mp3")     
                        playsound("audioBase/repns1.mp3")
                        
                        f=open('monfichier.txt', 'ab')
                        f.write(str(noveau_text+"\n").encode('utf-8')) 
                    break

            if foundMonth==False:
                tts=gTTS(repns,"ar")
                tts.save("audioBase/repns.mp3")     
                playsound("audioBase/repns.mp3")        
    else:
        if mot3==i:
            fichier=open(r"C:/Users/SanaAb/Documents/master/S2/Machine_learning/PROJET/ImageToSpeachPython/monfichier.txt","r",encoding="utf_8").readlines()
            for line in fichier :
                ttt=[]
                ttt=re.findall('\d+', line)
                listtt=[]
                listtt+=ttt
                dateee=listtt[2]+"-"+listtt[1]+"-"+listtt[0]
                maintenant = datetime.now()
                dt=str(maintenant.date())
                if (dateee== dt):
                    type_rendez_vous= line.split(" ")
                    liste_type_rendez_vous=""
github radiodee1 / awesome-chatbot / bot / game_voice.py View on Github external
def speech_out(self,text=""):
        if len(text) > 0 and text.split(' ')[0] not in ['.','!','?',',']:
            try:
                #mp3_fp = BytesIO()
                tts = gTTS(text=text, lang='en', slow=False, lang_check=False)
                #tts.write_to_fp(mp3_fp)
                #path = os.path.join(self.dir_out,"temp_speech.mp3")
                #tts.save(path)
            except AssertionError:
                print('assertion error.')
                pass
            except:
                pass
            pass
            #os.system("mpg123 " + path + " > /dev/null 2>&1 ")
            with BytesIO() as f:
                pygame.mixer.init(24000, -16, 1, 4096)

                tts.write_to_fp(f)
                f.seek(0)
                pygame.mixer.music.load(f)
github SPARC-Auburn / Lab-Assistant / PCKaren / Lab-Assistant / PCKaren / Speech.py View on Github external
def Speak(whatToSay):
    try:
	print(whatToSay)
        tts = gTTS(text=whatToSay, lang='en')
        tts.save("temp.mp3")
        pygame.init()
	pygame.mixer.init()
	pygame.mixer.music.load("temp.mp3")
	pygame.mixer.music.play()
	while pygame.mixer.music.get_busy():
		pygame.time.Clock().tick(10)
    except:
	print("Error in TTS")
        print(whatToSay)
        return False

    remove("temp.mp3")  # remove temperory file
github Canule / Mash-Cogs / gtts / gtts.py View on Github external
async def transfer_playlist(self, message):
        msg = message.attachments[0]
        if msg["filename"].endswith(".txt"):
            if not fileIO("data/audio/playlists/" + msg["filename"], "check"): #returns false if file already exists
                r = await aiohttp.get(msg["url"])
                r = await r.text()
                data = r.replace("\r", "")
                data = data.split()
                if self.is_playlist_valid(data) and self.is_playlist_name_valid(msg["filename"].replace(".txt", "")):
                    data = { "author" : message.author.id,
                             "playlist": data,
                             "link"    : False}
                    fileIO("data/audio/playlists/" + msg["filename"], "save", data)
                    await self.bot.send_message(message.channel, "Playlist added. Name: {}".format(msg["filename"].replace(".txt", "")))
                else:
                    await self.bot.send_message(message.channel, "Something is wrong with the playlist or its filename.") # Add formatting info
            else:
                await self.bot.send_message(message.channel, "A playlist with that name already exists. Change the filename and resubmit it.")
github NaomiProject / Naomi / plugins / tts / google-tts / google.py View on Github external
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
github pndurette / gTTS / gtts / cli.py View on Github external
def print_languages(ctx, param, value):
    """Callback for  flag.
    Prints formatted sorted list of supported languages and exits
    """
    if not value or ctx.resilient_parsing:
        return
    try:
        langs = tts_langs()
        langs_str_list = sorted("{}: {}".format(k, langs[k]) for k in langs)
        click.echo('  ' + '\n  '.join(langs_str_list))
    except RuntimeError as e:  # pragma: no cover
        log.debug(str(e), exc_info=True)
        raise click.ClickException("Couldn't fetch language list.")
    ctx.exit()
github Aculeasis / mdmTerminal2 / src / lib / gtts_monkey_patching.py View on Github external
def gtts_version() -> tuple:
    try:
        return tuple(int(x) for x in gtts.__version__.split('.'))
    except (TypeError, ValueError):
        return 0, 0, 0
github SPARC-Auburn / Lab-Assistant / assistant / properties.py View on Github external
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)